Phase 6: inline mode and docs

- Inline mode (INLINE_MODE_ENABLED): "@bot <link>" sends the cached file
  by file_id when the user's limits admit it without payment, and
  otherwise one result that opens the bot with /start il_<token> for the
  link. An inline send counts as a download when Telegram reports it
  chosen (inline feedback). The bot asks Telegram for inline_query and
  chosen_inline_result updates.
- README, OPERATIONS and ARCHITECTURE describe the new flows, Stars,
  inline mode and every new setting; docs/SCREENS.md regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 21:47:26 +00:00
co-authored by Claude Opus 5.5
parent d64db03f21
commit 44d0905fa3
18 changed files with 591 additions and 27 deletions
+17
View File
@@ -103,6 +103,8 @@ type Bot struct {
// cancelledAt is when each user last sent /cancel. A playlist item
// that was already being looked up at that moment must not start.
cancelledAt map[int64]time.Time
// inlineChoices are cached files offered inline, by result token.
inlineChoices map[string]inlineChoice
// menuButtons is the language each private chat's menu button was
// last labelled in.
menuButtons map[int64]string
@@ -164,6 +166,7 @@ func New(ctx context.Context, d Deps) (*Bot, error) {
cancelledAt: map[int64]time.Time{},
broadcasts: map[string]string{},
menuButtons: map[int64]string{},
inlineChoices: map[string]inlineChoice{},
reloadI18n: d.ReloadI18n,
broadcastGap: 50 * time.Millisecond,
admins: d.Admins,
@@ -304,6 +307,10 @@ func updateChatID(u telego.Update) int64 {
return u.MyChatMember.Chat.ID
case u.PreCheckoutQuery != nil:
return u.PreCheckoutQuery.From.ID
case u.InlineQuery != nil:
return u.InlineQuery.From.ID
case u.ChosenInlineResult != nil:
return u.ChosenInlineResult.From.ID
case u.WidgetQuery != nil:
if u.WidgetQuery.Chat != nil {
return u.WidgetQuery.Chat.ID
@@ -336,6 +343,10 @@ func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) {
b.handleWidgetQuery(ctx, u.WidgetQuery)
case u.PreCheckoutQuery != nil:
b.handlePreCheckout(ctx, u.PreCheckoutQuery)
case u.InlineQuery != nil:
b.handleInlineQuery(ctx, u.InlineQuery)
case u.ChosenInlineResult != nil:
b.handleChosenInlineResult(ctx, u.ChosenInlineResult)
}
}
@@ -353,6 +364,8 @@ func updateUser(u telego.Update) (*telego.User, *telego.Chat) {
return &u.CallbackQuery.From, nil
case u.PreCheckoutQuery != nil:
return &u.PreCheckoutQuery.From, nil
case u.InlineQuery != nil:
return &u.InlineQuery.From, nil
}
return nil, nil
}
@@ -369,6 +382,10 @@ func updateType(u telego.Update) string {
return "widget_query"
case u.PreCheckoutQuery != nil:
return "pre_checkout_query"
case u.InlineQuery != nil:
return "inline_query"
case u.ChosenInlineResult != nil:
return "chosen_inline_result"
}
return "other"
}
+6
View File
@@ -313,6 +313,12 @@ func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) {
case payload == "buy":
b.showBuy(ctx, m.Chat.ID, act)
return
case strings.HasPrefix(payload, inlineStartPrefix):
b.startInlineLink(ctx, m, act, strings.TrimPrefix(payload, inlineStartPrefix))
return
case payload == "inline":
b.inlineHint(ctx, m.Chat.ID, act.lang)
return
default:
b.applyReferral(ctx, act, payload)
}
+236
View File
@@ -0,0 +1,236 @@
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 <link>" 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_<token>, 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 <link>".
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_<token>: 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)
}