Files
Media-download-telegram-bot/internal/bot/menu.go
T
MichilisandClaude Opus 5.5 6843053582 Phase 1: quick flow fixes
- One message per job: the status message is deleted once the file is
  sent, or shortened to "Sent." when Telegram keeps it.
- No reply quotes in private chats; groups keep them.
- Queue status only mentions the position when the wait is above
  QUEUE_NOTICE_THRESHOLD_SECONDS or somebody is ahead. Status edits are
  throttled to one per 2.5 s per message; a state that arrives too soon
  is shown later instead of dropped. The wait estimate is 0 with a free
  slot.
- Caption with title (uploader and date when generic), uploader,
  duration, a short source link without tracking parameters and an
  optional "via @bot" line (CAPTION_ATTRIBUTION). Uploaded videos get a
  320 px JPEG thumbnail; merged MP4s are written with faststart.
- Buttons under the result: Audio (MP3), Other quality, Thumbnail,
  Delete. Requester only in groups.
- Language resolved once per update and passed in the context. A
  fallback to English is logged as a bug; a test walks every screen in
  Spanish and Dutch. Language picker on the first /start.
- Sizes without a zero decimal ("50 MB").
- First link of a new user shows the card once and sets the default to
  "best that fits my limit".
- Errors offer the next step (Try again, Smaller quality, Upgrade, Open
  app); passing lookup failures are retried once.
- Up to MULTI_LINK_MAX links per message; a link sent a moment ago gets
  "already sent" with a Send again button.
- Mini App menu button, labelled per private chat in the user's
  language.
- Personal /settings in private chats with an "Add me to a group"
  button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:08:58 +00:00

256 lines
8.7 KiB
Go

package bot
import (
"context"
"crypto/sha256"
"encoding/hex"
"strings"
"time"
"github.com/mymmrac/telego"
)
// The command menus. Names are lowercase ASCII in every language; only the
// descriptions are translated, under "menu.<name>". Each list is published
// for every language, in three scopes: private chats, group members and
// group admins. Owner commands are never listed.
var (
privateMenu = []string{
"dl", "audio", "thumb", "subs", "info", "queue", "cancel", "history",
"account", "buy", "credits", "limits", "redeem", "referral", "donate",
"settings", "quality", "language", "app", "support", "privacy", "terms", "help",
}
groupMenu = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "groupwallet", "grouppass", "app", "help"}
adminMenu = append(append([]string{}, groupMenu...),
"settings", "grouplang", "autodetect", "allow", "block", "spending", "groupstats")
)
func (b *Bot) menu(lang string, names []string, private bool) []telego.BotCommand {
cmds := make([]telego.BotCommand, 0, len(names))
for _, name := range names {
if name == "app" && !b.cfg.MiniAppEnabled() {
continue
}
key := "menu." + name
if name == "settings" && private {
key = "menu.settings_private" // /settings in a private chat is personal
}
cmds = append(cmds, telego.BotCommand{Command: name, Description: b.tr.T(lang, key, nil)})
}
return cmds
}
// menuLangs are the languages menus and profile texts are published for.
// Telegram takes a two-letter code only, so a regional catalog (es-PY)
// shares its base language's slot, and the pseudo-locale is left out.
func (b *Bot) menuLangs() []string {
var out []string
seen := map[string]bool{}
for _, l := range b.tr.Langs() {
if b.tr.Hidden(l) || len(l) != 2 || seen[l] {
continue
}
seen[l] = true
out = append(out, l)
}
return out
}
// RegisterCommands publishes the command menus and the bot's profile texts
// in every language. The source language is also the default for clients
// in languages without a catalog. A failure is logged and otherwise
// ignored: the bot works without a menu.
func (b *Bot) RegisterCommands(ctx context.Context) {
scopes := []struct {
scope telego.BotCommandScope
names []string
private bool
}{
{&telego.BotCommandScopeAllPrivateChats{Type: telego.ScopeTypeAllPrivateChats}, privateMenu, true},
{&telego.BotCommandScopeAllGroupChats{Type: telego.ScopeTypeAllGroupChats}, groupMenu, false},
{&telego.BotCommandScopeAllChatAdministrators{Type: telego.ScopeTypeAllChatAdministrators}, adminMenu, false},
}
b.setDefaultMenuButton(ctx)
for i, lang := range b.menuLangs() {
code := lang
if i == 0 {
code = "" // the default menu
}
for _, s := range scopes {
err := b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{
Commands: b.menu(lang, s.names, s.private), Scope: s.scope, LanguageCode: code,
})
if err != nil {
b.log.Warn("setMyCommands failed", "lang", lang, "scope", s.scope.ScopeType(), "err", err)
}
}
if b.cfg.Telegram.SetProfile {
b.setProfile(ctx, lang, code)
}
}
}
// setProfile sets the bot's name and descriptions for one language. These
// calls are rate limited hard by Telegram, so they are made only when the
// catalog text changed since the last time they went through.
func (b *Bot) setProfile(ctx context.Context, lang, code string) {
name := b.tr.T(lang, "profile.name", nil)
about := b.tr.T(lang, "profile.about", nil)
short := b.tr.T(lang, "profile.short", nil)
sum := sha256.Sum256([]byte(name + "\x00" + about + "\x00" + short))
hash := hex.EncodeToString(sum[:])
key := "profile:" + lang
if old, _ := b.store.GetKV(ctx, key); old == hash {
return
}
steps := []func() error{
func() error { return b.api.SetMyName(ctx, &telego.SetMyNameParams{Name: name, LanguageCode: code}) },
func() error {
return b.api.SetMyDescription(ctx, &telego.SetMyDescriptionParams{Description: about, LanguageCode: code})
},
func() error {
return b.api.SetMyShortDescription(ctx, &telego.SetMyShortDescriptionParams{ShortDescription: short, LanguageCode: code})
},
}
for _, step := range steps {
if err := step(); err != nil {
// Not recorded, so the next start tries again.
b.log.Warn("setting the bot profile failed", "lang", lang, "err", err)
return
}
}
if err := b.store.SetKV(ctx, key, hash); err != nil {
b.log.Warn("remember bot profile", "lang", lang, "err", err)
}
}
// SyncUserMenu makes the command menu of a private chat follow the user's
// language setting. Telegram picks a menu by the language of the app, so a
// user who chose another language in the bot gets a menu for that chat
// alone. An empty lang removes it, and the app's language applies again.
func (b *Bot) SyncUserMenu(ctx context.Context, userID int64, lang string) {
if !b.rate.allow("menu:"+itoa(userID), 6, time.Minute) {
return
}
scope := &telego.BotCommandScopeChat{Type: telego.ScopeTypeChat, ChatID: telego.ChatID{ID: userID}}
var err error
if lang == "" {
err = b.api.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{Scope: scope})
} else {
err = b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{Commands: b.menu(lang, privateMenu, true), Scope: scope})
}
if err != nil {
b.log.Warn("set the menu of a chat", "chat_id", userID, "err", err)
}
}
// SyncGroupMenu does the same for a group with its own language: one menu
// for its members and one for its admins.
func (b *Bot) SyncGroupMenu(ctx context.Context, chatID int64, lang string) {
if !b.rate.allow("menu:"+itoa(chatID), 6, time.Minute) {
return
}
id := telego.ChatID{ID: chatID}
scopes := []struct {
scope telego.BotCommandScope
names []string
}{
{&telego.BotCommandScopeChat{Type: telego.ScopeTypeChat, ChatID: id}, groupMenu},
{&telego.BotCommandScopeChatAdministrators{Type: telego.ScopeTypeChatAdministrators, ChatID: id}, adminMenu},
}
for _, s := range scopes {
var err error
if lang == "" {
err = b.api.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{Scope: s.scope})
} else {
err = b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{Commands: b.menu(lang, s.names, false), Scope: s.scope})
}
if err != nil {
b.log.Warn("set the menu of a group", "chat_id", chatID, "err", err)
}
}
}
// visibleLangs lists the languages a user may pick. The pseudo-locale is
// for owners only.
func (b *Bot) visibleLangs(userID int64) []string {
var out []string
for _, l := range b.tr.Langs() {
if !b.tr.Hidden(l) || b.cfg.IsOwner(userID) {
out = append(out, l)
}
}
return out
}
// findLang matches a language code typed by a user against the catalogs.
func (b *Bot) findLang(code string, userID int64) string {
for _, l := range b.visibleLangs(userID) {
if strings.EqualFold(l, code) {
return l
}
}
return ""
}
// menuButton is the button left of the message field that opens the Mini
// App. The command list stays one tap away in the "/" button of the field.
func (b *Bot) menuButton(lang string) *telego.MenuButtonWebApp {
return &telego.MenuButtonWebApp{
Type: telego.ButtonTypeWebApp,
Text: b.tr.T(lang, "btn.open_app", nil),
WebApp: telego.WebAppInfo{URL: b.cfg.PublicURL + "/app/"},
}
}
// setDefaultMenuButton makes the Mini App the menu button of every chat,
// labelled in the source language. setChatMenuButton takes no language,
// so each private chat gets its own label later, by syncMenuButton.
func (b *Bot) setDefaultMenuButton(ctx context.Context) {
if !b.cfg.MiniAppEnabled() {
return
}
if err := b.api.SetChatMenuButton(ctx, &telego.SetChatMenuButtonParams{MenuButton: b.menuButton(b.tr.Langs()[0])}); err != nil {
b.log.Warn("setChatMenuButton failed", "err", err)
}
}
// syncMenuButton labels the menu button of a private chat in the user's
// language. It runs once per user and language: what was set is kept in
// memory and in the database, so it survives a restart.
func (b *Bot) syncMenuButton(ctx context.Context, act actor) {
if !b.cfg.MiniAppEnabled() {
return
}
lang := b.userLang(act.user)
b.statusMu.Lock()
known := b.menuButtons[act.user.ID] == lang
b.statusMu.Unlock()
if known {
return
}
key := "menubtn:" + itoa(act.user.ID)
if old, _ := b.store.GetKV(ctx, key); old == lang {
b.rememberMenuButton(act.user.ID, lang)
return
}
if !b.rate.allow("menubtn:"+itoa(act.user.ID), 3, time.Minute) {
return
}
err := b.api.SetChatMenuButton(ctx, &telego.SetChatMenuButtonParams{ChatID: act.user.ID, MenuButton: b.menuButton(lang)})
if err != nil {
b.log.Warn("setChatMenuButton failed", "chat_id", act.user.ID, "err", err)
return
}
if err := b.store.SetKV(ctx, key, lang); err != nil {
b.log.Warn("remember menu button", "chat_id", act.user.ID, "err", err)
}
b.rememberMenuButton(act.user.ID, lang)
}
func (b *Bot) rememberMenuButton(userID int64, lang string) {
b.statusMu.Lock()
b.menuButtons[userID] = lang
b.statusMu.Unlock()
}