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.". 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() }