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
+1 -1
View File
@@ -371,7 +371,7 @@ func New(ctx context.Context, opts Options) (*App, error) {
}
// allowedUpdates is the list of update types the bot asks Telegram for.
var allowedUpdates = []string{"message", "callback_query", "my_chat_member", "widget_query", "pre_checkout_query"}
var allowedUpdates = []string{"message", "callback_query", "my_chat_member", "widget_query", "pre_checkout_query", "inline_query", "chosen_inline_result"}
// Run starts every loop and blocks until ctx ends. Shutdown is ordered:
// updates stop first, then the worker hands back its jobs, then the
+123
View File
@@ -0,0 +1,123 @@
package app_test
import (
"encoding/json"
"strings"
"testing"
"time"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/tg/fakeserver"
)
type inlineAnswer struct {
Results []struct {
Type string `json:"type"`
ID string `json:"id"`
VideoFileID string `json:"video_file_id"`
Caption string `json:"caption"`
ReplyMarkup struct {
Rows [][]struct {
URL string `json:"url"`
} `json:"inline_keyboard"`
} `json:"reply_markup"`
}
Button struct {
Text string `json:"text"`
StartParameter string `json:"start_parameter"`
}
Personal bool
}
func (h *harness) inline(user int64, query string) inlineAnswer {
h.t.Helper()
seq := h.srv.Seq()
id := h.srv.PushInlineQuery(user, query)
c := h.wait(seq, "answerInlineQuery", func(c fakeserver.Call) bool { return c.Params["inline_query_id"] == id })
var a inlineAnswer
if err := json.Unmarshal([]byte(c.Params["results"]), &a.Results); err != nil {
h.t.Fatalf("results: %v (%s)", err, c.Params["results"])
}
_ = json.Unmarshal([]byte(c.Params["button"]), &a.Button)
a.Personal = c.Params["is_personal"] == "true"
return a
}
func TestInlineModeSendsCachedFilesWithinLimits(t *testing.T) {
h := start(t, nil, func(c *config.Config) {
c.InlineModeEnabled = true
c.Limits.Free.DailyDownloads = 1
})
h.fetch(alice, link) // the file is now in the cache
entry := h.entry(link, "best")
// Bob gets the cached file itself, by file_id, with the usual caption.
a := h.inline(bob, link)
if len(a.Results) != 1 || a.Results[0].Type != "video" || a.Results[0].VideoFileID != entry.TgFileID || !a.Personal {
t.Fatalf("answer = %+v, want the cached video %q", a, entry.TgFileID)
}
if !strings.Contains(a.Results[0].Caption, "<b>Test Video</b>") {
t.Fatalf("caption = %q", a.Results[0].Caption)
}
if n := len(h.fake.Downloads()); n != 1 {
t.Fatalf("an inline answer downloaded (%d downloads)", n)
}
// Sending it counts as his download of the day.
h.srv.PushChosenInlineResult(bob, a.Results[0].ID, link)
waitFor(t, func() bool { return h.usage(bob).Downloads == 1 })
// The same result reported twice counts once.
h.srv.PushChosenInlineResult(bob, a.Results[0].ID, link)
// His one download is used up: no file, a way into the bot instead.
a = h.inline(bob, link)
if len(a.Results) != 1 || a.Results[0].Type != "article" {
t.Fatalf("over the limit: %+v", a)
}
if u := h.usage(bob); u.Downloads != 1 {
t.Fatalf("usage = %+v", u)
}
}
func TestInlineModeOpensTheBotForWhatIsNotCached(t *testing.T) {
h := start(t, nil, func(c *config.Config) { c.InlineModeEnabled = true })
a := h.inline(carol, "look https://example.com/new?utm_source=x")
if len(a.Results) != 1 || a.Results[0].Type != "article" || !strings.HasPrefix(a.Button.StartParameter, "il_") {
t.Fatalf("answer = %+v", a)
}
open := a.Results[0].ReplyMarkup.Rows[0][0].URL
if open != "https://t.me/"+fakeserver.BotUsername+"?start="+a.Button.StartParameter || len(a.Button.StartParameter) > 64 {
t.Fatalf("deep link %q, start parameter %q", open, a.Button.StartParameter)
}
// Opening the bot with it runs the usual flow for the link.
seq := h.srv.Seq()
h.srv.PushMessage(carol, carol, "/start "+a.Button.StartParameter)
h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok && c.ChatID() == carol })
// Not a link: a button that explains inline mode in the bot.
if a := h.inline(carol, "cats"); len(a.Results) != 0 || a.Button.StartParameter != "inline" {
t.Fatalf("no link: %+v", a)
}
seq = h.srv.Seq()
h.srv.PushMessage(carol, carol, "/start inline")
h.wait(seq, "sendMessage", textHas("@"+fakeserver.BotUsername))
}
func TestInlineModeIsOffByDefault(t *testing.T) {
h := start(t, nil, nil)
h.fetch(alice, link)
if a := h.inline(bob, link); len(a.Results) != 0 {
t.Fatalf("inline mode answered while off: %+v", a)
}
}
// waitFor polls a condition for a few seconds.
func waitFor(t *testing.T, cond func() bool) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatal("condition not met in time")
}
time.Sleep(20 * time.Millisecond)
}
}
+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)
}
+5
View File
@@ -128,6 +128,11 @@ type Config struct {
// Telegram). Turn it on once the program is set up for the bot, see
// docs/AFFILIATE.md.
AffiliateEnabled bool `toml:"affiliate_enabled" env:"AFFILIATE_ENABLED"`
// InlineModeEnabled answers "@bot <link>" in any chat: the cached file
// when the user's limits allow it, a link into the bot otherwise. Inline
// mode must also be switched on in @BotFather (/setinline), and inline
// feedback (/setinlinefeedback) for inline sends to count as downloads.
InlineModeEnabled bool `toml:"inline_mode_enabled" env:"INLINE_MODE_ENABLED"`
}
// StarsPrice returns the price in Stars of a product, or false when it
+1
View File
@@ -41,6 +41,7 @@ type API interface {
CreateInvoiceLink(ctx context.Context, params *telego.CreateInvoiceLinkParams) (*string, error)
AnswerPreCheckoutQuery(ctx context.Context, params *telego.AnswerPreCheckoutQueryParams) error
RefundStarPayment(ctx context.Context, params *telego.RefundStarPaymentParams) error
AnswerInlineQuery(ctx context.Context, params *telego.AnswerInlineQueryParams) error
}
var _ API = (*telego.Bot)(nil)
+27
View File
@@ -399,6 +399,33 @@ func (s *Server) pushPaymentLocked(userID int64, field string, body map[string]a
}})
}
// PushInlineQuery queues "@bot <query>" typed by a user, and returns the
// query ID.
func (s *Server) PushInlineQuery(userID int64, query string) string {
s.mu.Lock()
defer s.mu.Unlock()
id := fmt.Sprintf("iq%d", s.updateID+1)
s.pushLocked(map[string]any{"inline_query": map[string]any{
"id": id,
"from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": s.userLang(userID)},
"query": query,
"offset": "",
}})
return id
}
// PushChosenInlineResult queues the report that a user sent an inline
// result (inline feedback).
func (s *Server) PushChosenInlineResult(userID int64, resultID, query string) {
s.mu.Lock()
defer s.mu.Unlock()
s.pushLocked(map[string]any{"chosen_inline_result": map[string]any{
"result_id": resultID,
"from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": s.userLang(userID)},
"query": query,
}})
}
// PushRaw queues an arbitrary update body, for example my_chat_member.
func (s *Server) PushRaw(update map[string]any) {
s.mu.Lock()