package bot import ( "context" "crypto/rand" "encoding/base32" "strings" "time" "github.com/mymmrac/telego" "github.com/noderunners/dlbot/internal/cache" "github.com/noderunners/dlbot/internal/i18n" "github.com/noderunners/dlbot/internal/links" "github.com/noderunners/dlbot/internal/media" "github.com/noderunners/dlbot/internal/service" ) // Inline mode: typing "@bot " in any chat. A file that is in the // cache, and that the user's limits allow without paying, comes back as // the file itself (by file_id). Anything else comes back as one result // that opens the bot with a /start payload for the link, where the usual // flow takes over. Inline mode must also be switched on in @BotFather. // // A file sent inline counts against the daily limits when Telegram says // it was chosen (chosen_inline_result, which needs inline feedback on in // @BotFather). Without that, a result is only offered when it is within // the limits. // inlineStartPrefix starts the /start payload of an inline deep link: // il_, where the token names the link in the kv table. const inlineStartPrefix = "il_" // inlineProbeTimeout bounds a lookup while Telegram waits for the answer. const inlineProbeTimeout = 5 * time.Second // inlineChoice is a cached file offered inline, kept until it is chosen. type inlineChoice struct { userID int64 size int64 at time.Time } func inlineToken() string { var b [8]byte _, _ = rand.Read(b[:]) return strings.ToLower(strings.TrimRight(base32.StdEncoding.EncodeToString(b[:]), "=")) } // handleInlineQuery answers "@bot ". func (b *Bot) handleInlineQuery(ctx context.Context, q *telego.InlineQuery) { act, ok := actorFrom(ctx) if !b.cfg.InlineModeEnabled || !ok || act.user.Banned { b.answerInline(ctx, q, nil, nil) return } lang := act.lang urls := links.Extract(q.Query, nil) if len(urls) == 0 { // Not a link (yet): a button that explains itself in the bot. b.answerInline(ctx, q, nil, &telego.InlineQueryResultsButton{ Text: b.tr.T(lang, "inline.paste_link", nil), StartParameter: "inline", }) return } url := urls[0] if !b.rate.allow("u:"+itoa(act.user.ID), b.cfg.Rate.UserPerMinute, time.Minute) { b.answerInline(ctx, q, nil, nil) return } if r := b.inlineCached(ctx, act, url); r != nil { b.answerInline(ctx, q, []telego.InlineQueryResult{r}, nil) return } results, button := b.inlineDeepLink(ctx, lang, url) b.answerInline(ctx, q, results, button) } // inlineCached returns the cached file for a link as an inline result, or // nil when there is none, or the user's limits do not allow it without // paying. func (b *Bot) inlineCached(ctx context.Context, act actor, url string) telego.InlineQueryResult { pctx, cancel := context.WithTimeout(ctx, inlineProbeTimeout) defer cancel() probed, err := b.svc.ProbeAny(pctx, url) if err != nil || probed.Info == nil { return nil } info := probed.Info who := service.Who{UserID: act.user.ID, ChatID: act.user.ID, ChatType: telego.ChatTypePrivate} dec, err := b.svc.Entitlement(ctx, who, false) if err != nil || dec.Charge > 0 { return nil // paying needs the bot chat } profile := b.inlineProfile(act, info, dec.Limits.MaxSize) ext, vid := cache.Canonical(info.Extractor, info.VideoID, url) e, err := b.cache.Lookup(ctx, ext, vid, profile) if err != nil || e == nil || e.TgFileID == "" || e.Private { return nil } // The same rules as every other path, on what the cache holds. known := *info known.Sizes = map[string]int64{string(profile): e.Size} if e.Duration > 0 { known.Duration = e.Duration } if err := b.svc.Preview(ctx, who, url, &known, profile); err != nil { return nil } token := inlineToken() b.statusMu.Lock() for k, c := range b.inlineChoices { if time.Since(c.at) > time.Hour { delete(b.inlineChoices, k) } } b.inlineChoices[token] = inlineChoice{userID: act.user.ID, size: e.Size, at: time.Now()} b.statusMu.Unlock() id := "c_" + token caption := clip(b.caption(act.lang, info, url, profile), 1024) title, _ := b.displayTitle(act.lang, info) title = shorten(title, 60) desc := b.profileLabel(act.lang, profile) if e.Size > 0 { desc += " ยท " + b.tr.Size(act.lang, e.Size) } switch profile.Kind() { case media.KindAudio: return &telego.InlineQueryResultCachedAudio{Type: telego.ResultTypeAudio, ID: id, AudioFileID: e.TgFileID, Caption: caption, ParseMode: telego.ModeHTML} case media.KindVideo: if streamable(e.FileExt) || e.FileExt == "" { return &telego.InlineQueryResultCachedVideo{Type: telego.ResultTypeVideo, ID: id, VideoFileID: e.TgFileID, Title: title, Description: desc, Caption: caption, ParseMode: telego.ModeHTML} } } return &telego.InlineQueryResultCachedDocument{Type: telego.ResultTypeDocument, ID: id, DocumentFileID: e.TgFileID, Title: title, Description: desc, Caption: caption, ParseMode: telego.ModeHTML} } // inlineProfile is the format an inline request means: the user's default, // with "ask every time" read as Best. func (b *Bot) inlineProfile(act actor, info *service.CardInfo, maxSize int64) media.Profile { switch q := act.user.Quality; q { case qualityUnset, qualityFit: p, _ := service.BestFit(info, min64(maxSize, b.cfg.MaxUploadBytes())) return p case qualityAsk: return media.Best default: if p, err := media.Parse(q); err == nil { return p } } return media.Best } // inlineDeepLink is the one result for a link that is not ready to send // inline: choosing it posts the link with a button that opens the bot, // and the button above the results opens the bot directly. Both carry a // /start payload that names the link. func (b *Bot) inlineDeepLink(ctx context.Context, lang, url string) ([]telego.InlineQueryResult, *telego.InlineQueryResultsButton) { token := inlineToken() if err := b.store.SetKV(ctx, "inline:"+token, url); err != nil { b.log.Error("remember inline link", "err", err) return nil, nil } start := inlineStartPrefix + token open := "https://t.me/" + b.username + "?start=" + start clean := links.Clean(url) result := &telego.InlineQueryResultArticle{ Type: telego.ResultTypeArticle, ID: "d_" + token, Title: b.tr.T(lang, "inline.download_title", nil), Description: links.Short(clean, 60), InputMessageContent: &telego.InputTextMessageContent{ MessageText: clean, LinkPreviewOptions: noPreview, }, ReplyMarkup: keyboard([]telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "inline.open_bot", nil), open)}), } return []telego.InlineQueryResult{result}, &telego.InlineQueryResultsButton{ Text: b.tr.T(lang, "inline.open_bot", nil), StartParameter: start, } } func (b *Bot) answerInline(ctx context.Context, q *telego.InlineQuery, results []telego.InlineQueryResult, button *telego.InlineQueryResultsButton) { if results == nil { results = []telego.InlineQueryResult{} } err := b.api.AnswerInlineQuery(ctx, &telego.AnswerInlineQueryParams{ InlineQueryID: q.ID, Results: results, Button: button, // Answers depend on the user's limits, so they are not shared. IsPersonal: true, CacheTime: 10, }) if err != nil { b.log.Debug("answerInlineQuery failed", "err", err) } } // handleChosenInlineResult counts a cached file that was sent inline as a // download of the user who sent it, once. func (b *Bot) handleChosenInlineResult(ctx context.Context, r *telego.ChosenInlineResult) { token, ok := strings.CutPrefix(r.ResultID, "c_") if !ok { return } b.statusMu.Lock() c, found := b.inlineChoices[token] delete(b.inlineChoices, token) b.statusMu.Unlock() if !found || c.userID != r.From.ID { return } if err := b.store.AddUsage(ctx, c.userID, service.Day(time.Now()), 1, c.size); err != nil { b.log.Error("count inline download", "user_id", c.userID, "err", err) } b.metrics.Delivered("inline") } // startInlineLink handles /start il_: the link from an inline // query, downloaded in the private chat like a pasted link. func (b *Bot) startInlineLink(ctx context.Context, m *telego.Message, act actor, token string) { url, err := b.store.GetKV(ctx, "inline:"+token) if err != nil || url == "" { _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "notice.expired", nil), nil) return } b.startLink(ctx, linkRequest{ chatID: m.Chat.ID, chatType: m.Chat.Type, act: act, url: url, preset: presetFor(act, nil), }) } // inlineHint is the welcome for "/start inline": how inline mode works. func (b *Bot) inlineHint(ctx context.Context, chat int64, lang string) { _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "inline.hint", i18n.Args{"Bot": b.username}), nil) }