diff --git a/CHANGELOG.md b/CHANGELOG.md index adf20dc..f7c109f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,15 @@ See [`docs/versioning.md`](docs/versioning.md) for what the numbers mean and ## Unreleased +### Added + +- The DM has a keyboard under the message field: Play, Today's result and + Menu. The menu button there opens the Mini App and hides the command + list, so a new player had nothing to press after the first game. Today's + result says, before the evening, whether you have answered and how long + until the result, and after it your score and place in the world. The + keyboard follows a language change; groups never get it. + ## v0.0.1-alpha.20 - 2026-11-10 For the operator: no migration and no new setting. diff --git a/internal/bot/bot.go b/internal/bot/bot.go index a9f9f27..6e44a99 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -44,6 +44,8 @@ type Store interface { Contexts(ctx context.Context, userID int64) ([]db.Context, error) Deadline(ctx context.Context, zones round.Zones, userID int64, d round.Date, own *time.Location) (time.Time, error) InsertGuess(ctx context.Context, g db.NewGuess) error + GuessOf(ctx context.Context, d round.Date, userID int64) (db.Guess, bool, error) + World(ctx context.Context, d round.Date) (db.World, error) } type Telegram interface { @@ -52,6 +54,7 @@ type Telegram interface { SetMyCommandsForScope(ctx context.Context, commands []tg.BotCommand, scope *tg.BotCommandScope) error SendText(ctx context.Context, chatID int64, text string, markup telegram.Markup) (tg.Message, error) SendTextIn(ctx context.Context, chatID int64, thread int, text string, markup telegram.Markup) (tg.Message, error) + SendKeyboard(ctx context.Context, chatID int64, text string, kb telegram.Keyboard) (tg.Message, error) EditText(ctx context.Context, chatID, messageID int64, text string, markup telegram.Markup) error EditAnimation(ctx context.Context, chatID, messageID int64, a telegram.Animation, caption string, markup telegram.Markup) (tg.Message, error) DeleteMessage(ctx context.Context, chatID, messageID int64) error @@ -229,8 +232,12 @@ func (b *Bot) handle(ctx context.Context, u tg.Update) { } var err error switch { + // The keyboard's buttons come as plain messages, so they are read before + // any other text and count as nothing else. + case u.Message != nil && keyOf(u.Message) != "": + err = b.onKey(ctx, u.Message, keyOf(u.Message)) case u.Message != nil && b.isStart(u.Message): - err = b.sendHome(ctx, u.Message) + err = b.onStart(ctx, u.Message) case u.Message != nil && u.Message.Chat.Type == "private": if p, ok := locationOf(u.Message); ok { err = b.onLocation(ctx, u.Message, p) diff --git a/internal/bot/bot_test.go b/internal/bot/bot_test.go index c3bd1fa..39b53b7 100644 --- a/internal/bot/bot_test.go +++ b/internal/bot/bot_test.go @@ -36,6 +36,8 @@ type fakeStore struct { settings map[int64]db.Settings rounds map[string]bool guesses []db.NewGuess + scored map[int64]db.Guess + world db.World } func newStore() *fakeStore { @@ -140,6 +142,18 @@ func (f *fakeStore) Contexts(context.Context, int64) ([]db.Context, error) { ret func (f *fakeStore) Deadline(_ context.Context, _ round.Zones, _ int64, d round.Date, own *time.Location) (time.Time, error) { return d.Reveal(own), nil } +func (f *fakeStore) GuessOf(_ context.Context, d round.Date, userID int64) (db.Guess, bool, error) { + if g, ok := f.scored[userID]; ok { + return g, true, nil + } + for _, g := range f.guesses { + if g.UserID == userID && g.Date.String() == d.String() { + return db.Guess{UserID: userID, Pin: g.Pin, AnsweredAt: g.AnsweredAt}, true, nil + } + } + return db.Guess{}, false, nil +} +func (f *fakeStore) World(context.Context, round.Date) (db.World, error) { return f.world, nil } func (f *fakeStore) InsertGuess(_ context.Context, g db.NewGuess) error { for _, old := range f.guesses { if old.UserID == g.UserID && old.Date.String() == g.Date.String() { @@ -176,6 +190,18 @@ type fakeTelegram struct { animated chan struct{} // told after each animation, when set editErr error // every EditText fails with it, when set threads []int // the forum topic of each send + keyboards []keyboardSent +} + +type keyboardSent struct { + chatID int64 + text string + kb telegram.Keyboard +} + +func (f *fakeTelegram) SendKeyboard(_ context.Context, chatID int64, text string, kb telegram.Keyboard) (tg.Message, error) { + f.keyboards = append(f.keyboards, keyboardSent{chatID, text, kb}) + return tg.Message{MessageID: 101, Chat: tg.Chat{ID: chatID}, Text: text}, nil } func (f *fakeTelegram) EditAnimation(_ context.Context, chatID, messageID int64, a telegram.Animation, caption string, markup telegram.Markup) (tg.Message, error) { diff --git a/internal/bot/keyboard.go b/internal/bot/keyboard.go new file mode 100644 index 0000000..1c27e1c --- /dev/null +++ b/internal/bot/keyboard.go @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: Apache-2.0 +package bot + +import ( + "context" + "fmt" + "math" + "strconv" + "strings" + "time" + + "github.com/FreshLabDev/tg" + + "github.com/FreshLabDev/maply/internal/i18n" + "github.com/FreshLabDev/maply/internal/round" + "github.com/FreshLabDev/maply/internal/telegram" +) + +// The DM's reply keyboard. In a DM the menu button opens the Mini App, which +// hides the command list, so these three buttons are what a newcomer has to +// press. A group never gets it: there it would sit under every member's +// input field. There is no location button: a location in a DM is the +// day's answer, and one press must not send it. +const ( + keyPlay = "play" + keyResult = "result" + keyMenu = "menu" +) + +var keyLabels = map[string]string{keyPlay: "btn.play", keyResult: "kb.result", keyMenu: "kb.menu"} + +// keyTexts maps each button's label in every language to the button. The +// client sends a text button back as a plain message in the language the +// keyboard was drawn in, which may no longer be the person's. +var keyTexts = func() map[string]string { + m := map[string]string{} + for _, code := range i18n.Codes() { + for key, label := range keyLabels { + m[i18n.T(code, label)] = key + } + } + return m +}() + +// keyOf is the keyboard button a DM message is, or "". +func keyOf(m *tg.Message) string { + if m.Chat.Type != "private" || m.From == nil || m.From.IsBot { + return "" + } + return keyTexts[strings.TrimSpace(m.Text)] +} + +// keyboard is Play over Today's result and Menu. Play opens the day in the +// Mini App; without one it is a text button that sends the menu. +func (b *Bot) keyboard(lang string) telegram.Keyboard { + play := telegram.KeyButton{Text: i18n.T(lang, "btn.play"), Style: tg.StylePrimary} + if b.opts.AppURL != "" { + play.WebApp = appPage(b.opts.AppURL, "/today") + } + return telegram.Keyboard{ + Rows: [][]telegram.KeyButton{ + {play}, + {{Text: i18n.T(lang, "kb.result")}, {Text: i18n.T(lang, "kb.menu")}}, + }, + Placeholder: i18n.T(lang, "kb.placeholder"), + } +} + +// sendKeyboard puts the keyboard under a DM's input field, in lang. Any +// other chat gets nothing. +func (b *Bot) sendKeyboard(ctx context.Context, chat tg.Chat, lang string) error { + if chat.Type != "private" { + return nil + } + if _, err := b.tg.SendKeyboard(ctx, chat.ID, i18n.T(lang, "kb.ready"), b.keyboard(lang)); err != nil { + return fmt.Errorf("send keyboard to %d: %w", chat.ID, err) + } + return nil +} + +// onStart answers /start: in a DM the keyboard first, then the panel, so +// the panel is what the person sees last. +func (b *Bot) onStart(ctx context.Context, m *tg.Message) error { + if m.Chat.Type == "private" { + raw, err := b.personLang(ctx, *m.From) + if err != nil { + return err + } + if err := b.sendKeyboard(ctx, m.Chat, i18n.Resolve(raw)); err != nil { + // The panel still works without the keyboard. + b.log.Warn("keyboard not sent", "error", err) + } + } + return b.sendHome(ctx, m) +} + +func (b *Bot) onKey(ctx context.Context, m *tg.Message, key string) error { + if key == keyResult { + return b.sendToday(ctx, m) + } + return b.sendHome(ctx, m) +} + +// sendToday is the person's day, read in their DM's zone. Before the DM's +// reveal it says whether they have answered and how long until the result. +// From the reveal it gives their score and their place in the world, the +// same rank the Mini App shows without names, with the result one tap away. +func (b *Bot) sendToday(ctx context.Context, m *tg.Message) error { + raw, err := b.personLang(ctx, *m.From) + if err != nil { + return err + } + lang := i18n.Resolve(raw) + zone, err := b.store.ChatZone(ctx, m.From.ID) + if err != nil { + return err + } + loc := b.opts.Zones.For(zone, raw) + now := b.opts.Now() + d := round.DateIn(now, loc) + say := func(text string, markup telegram.Markup) error { + _, err := b.tg.SendText(ctx, m.Chat.ID, text, markup) + return err + } + if _, ok, err := b.store.RoundOn(ctx, d); err != nil { + return err + } else if !ok { + return say(i18n.T(lang, "today.none"), nil) + } + guess, answered, err := b.store.GuessOf(ctx, d, m.From.ID) + if err != nil { + return err + } + reveal := d.Reveal(loc) + if now.Before(reveal) { + key := "today.answered" + if !answered { + // An earlier reveal in one of their groups may have closed + // the day for them already. + deadline, err := b.deadline(ctx, m.From.ID, d, loc) + if err != nil { + return err + } + if !now.Before(deadline) { + return say(i18n.T(lang, "loc.closed"), nil) + } + key = "today.waiting" + } + return say(i18n.T(lang, key, + "time", i18n.At(lang, revealTime(), round.Name(zone, raw)), + "left", until(lang, reveal.Sub(now))), nil) + } + if !answered { + return say(i18n.T(lang, "result.missed"), nil) + } + world, err := b.store.World(ctx, d) + if err != nil { + return err + } + lines := []string{"" + i18n.T(lang, "kb.result") + ""} + if guess.Km != nil { + score := i18n.T(lang, "app.km_points", + "points", i18n.FormatNumber(lang, guess.Total()), "km", i18n.FormatDistance(lang, *guess.Km)) + lines = append(lines, i18n.T(lang, "today.score", "score", score)) + } + if rank := world.RankOf(m.From.ID); rank > 0 { + // Zones still before their reveal are still answering. + key := "today.world" + if now.Before(b.opts.Zones.LastReveal(d)) { + key = "result.world_now" + } + lines = append(lines, i18n.T(lang, key, + "rank", i18n.FormatNumber(lang, rank), "n", i18n.FormatNumber(lang, world.Players()))) + } + var markup telegram.Markup + if b.opts.AppURL != "" { + markup = telegram.Markup{{{Text: i18n.T(lang, "btn.result"), WebApp: appPage(b.opts.AppURL, "/today"), Style: tg.StylePrimary}}} + } + return say(strings.Join(lines, "\n"), markup) +} + +// until is how long is left, rounded up to the minute so it never reads 0. +func until(lang string, d time.Duration) string { + mins := int(math.Ceil(d.Minutes())) + if mins < 1 { + mins = 1 + } + if h := mins / 60; h > 0 { + return i18n.T(lang, "unit.hm", "h", strconv.Itoa(h), "m", strconv.Itoa(mins%60)) + } + return i18n.T(lang, "unit.min", "m", strconv.Itoa(mins)) +} diff --git a/internal/bot/keyboard_test.go b/internal/bot/keyboard_test.go new file mode 100644 index 0000000..1e16f3e --- /dev/null +++ b/internal/bot/keyboard_test.go @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: Apache-2.0 +package bot + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/FreshLabDev/tg" + + "github.com/FreshLabDev/maply/internal/db" + "github.com/FreshLabDev/maply/internal/i18n" + "github.com/FreshLabDev/maply/internal/round" +) + +// A label that meant two buttons in two languages would do the wrong one. +func TestKeyLabelsAreUnambiguous(t *testing.T) { + seen := map[string]string{} + for _, code := range i18n.Codes() { + for key, label := range keyLabels { + text := i18n.T(code, label) + if other, ok := seen[text]; ok && other != key { + t.Fatalf("%q is both %s and %s", text, other, key) + } + seen[text] = key + } + } +} + +// Every language's label is its button in a DM, whatever the person's +// language is now; in a group, or from a bot, it is just text. +func TestKeyOfMatchesEveryLanguageInDMsOnly(t *testing.T) { + for _, code := range i18n.Codes() { + for key, label := range keyLabels { + text := i18n.T(code, label) + m := command(private(member), member, text).Message + if got := keyOf(m); got != key { + t.Fatalf("%s %q = %q, want %q", code, text, got, key) + } + if got := keyOf(command(group, member, text).Message); got != "" { + t.Fatalf("%s %q in a group = %q", code, text, got) + } + bot := tg.User{ID: 7, IsBot: true} + if got := keyOf(command(private(bot), bot, text).Message); got != "" { + t.Fatalf("a bot's %q = %q", text, got) + } + } + } + for _, text := range []string{"", "hello", "/start", "Меню please"} { + if got := keyOf(command(private(member), member, text).Message); got != "" { + t.Fatalf("%q = %q", text, got) + } + } +} + +func TestStartSendsTheKeyboardInDMsOnly(t *testing.T) { + b, _, client := testBot(t) + ctx := context.Background() + b.handle(ctx, command(private(member), member, "/start")) + if len(client.keyboards) != 1 || len(client.sends) != 1 { + t.Fatalf("keyboards = %d, sends = %d, want the keyboard and the panel", len(client.keyboards), len(client.sends)) + } + k := client.keyboards[0] + if k.chatID != userID || k.text != i18n.T("ru", "kb.ready") || k.kb.Placeholder != i18n.T("ru", "kb.placeholder") { + t.Fatalf("keyboard = %+v", k) + } + rows := k.kb.Rows + if len(rows) != 2 || len(rows[0]) != 1 || len(rows[1]) != 2 { + t.Fatalf("rows = %+v", rows) + } + play := rows[0][0] + if play.Text != "Играть" || play.WebApp != "https://maply.example/today" || play.Style != tg.StylePrimary { + t.Fatalf("play = %+v", play) + } + if rows[1][0].Text != "Итог дня" || rows[1][1].Text != "Меню" || rows[1][0].WebApp != "" || rows[1][1].WebApp != "" { + t.Fatalf("second row = %+v", rows[1]) + } + + // A group gets its panel and never the keyboard, nor an answer to a + // label typed there. + b.handle(ctx, command(group, admin, "/start")) + b.handle(ctx, command(group, member, "Меню")) + b.handle(ctx, command(group, member, "Итог дня")) + if len(client.keyboards) != 1 || len(client.sends) != 2 { + t.Fatalf("a group got keyboards %d, sends %d", len(client.keyboards), len(client.sends)) + } + if err := b.sendKeyboard(ctx, group, "ru"); err != nil || len(client.keyboards) != 1 { + t.Fatalf("sendKeyboard to a group: err %v, keyboards %d", err, len(client.keyboards)) + } +} + +// Menu sends the home panel, in any language's label; a label is never +// taken for anything else. +func TestMenuButtonSendsTheHome(t *testing.T) { + b, store, client := testBot(t) + ctx := context.Background() + b.handle(ctx, command(private(member), member, "Меню")) + b.handle(ctx, command(private(member), member, "Menu")) + if len(client.sends) != 2 || len(client.keyboards) != 0 { + t.Fatalf("sends = %d, keyboards = %d", len(client.sends), len(client.keyboards)) + } + for _, s := range client.sends { + if !strings.Contains(s.text, i18n.T("ru", "home.hint")) { + t.Fatalf("menu = %q", s.text) + } + } + if len(store.guesses) != 0 { + t.Fatal("a button counted as an answer") + } +} + +func TestTodaysResult(t *testing.T) { + b, store, client := testBot(t) + ctx := context.Background() + today := func() string { + b.handle(ctx, command(private(member), member, "Итог дня")) + return client.sends[len(client.sends)-1].text + } + if got := today(); got != i18n.T("ru", "today.none") { + t.Fatalf("no round: %q", got) + } + d := round.DateIn(winterDay, b.opts.Zones.For("", "ru")) + store.rounds[d.String()] = true + // 14:00 in Kyiv, six hours before the result. + if got, want := today(), i18n.T("ru", "today.waiting", "time", "20:00 (Киев)", "left", "6 ч 0 мин"); got != want { + t.Fatalf("before answering: %q, want %q", got, want) + } + b.handle(ctx, location(member, 48.85, 2.35)) + b.opts.Now = func() time.Time { return winterDay.Add(5*time.Hour + 30*time.Second) } + if got, want := today(), i18n.T("ru", "today.answered", "time", "20:00 (Киев)", "left", "1 ч 0 мин"); got != want { + t.Fatalf("after answering: %q, want %q", got, want) + } + + // 21:00 in Kyiv: the score and the place in the world, which the zones + // to the west are still adding to. + b.opts.Now = func() time.Time { return winterDay.Add(7 * time.Hour) } + km, ptsKm, bonus := 312.0, 3000, 500 + store.scored = map[int64]db.Guess{userID: {UserID: userID, Km: &km, PtsKm: &ptsKm, PtsBonus: &bonus}} + store.world = db.World{Entries: []db.Entry{{Rank: 1, UserID: 99}, {Rank: 2, UserID: userID}, {Rank: 3, UserID: 98}}} + got := today() + for _, want := range []string{"3 500 за 312 км", i18n.T("ru", "result.world_now", "rank", "2", "n", "3")} { + if !strings.Contains(strings.ReplaceAll(got, " ", " "), want) { + t.Fatalf("after the reveal: %q, want %q in it", got, want) + } + } + m := client.sends[len(client.sends)-1].markup + if len(m) != 1 || m[0][0].Text != i18n.T("ru", "btn.result") || m[0][0].WebApp != "https://maply.example/today" { + t.Fatalf("result button = %+v", m) + } + + // Someone who did not answer is told so, and gets no button. + b.handle(ctx, command(private(admin), admin, "Підсумок дня")) + last := client.sends[len(client.sends)-1] + if last.text != i18n.T("uk", "result.missed") || last.markup != nil { + t.Fatalf("missed = %+v", last) + } +} + +// Before the DM's reveal, an earlier reveal in a group may have closed the +// day; the button says so instead of counting down. +func TestTodaysResultAfterTheDeadline(t *testing.T) { + b, store, client := testBot(t) + b.store = deadlineStore{store, winterDay.Add(-time.Hour)} + d := round.DateIn(winterDay, b.opts.Zones.For("", "ru")) + store.rounds[d.String()] = true + b.handle(context.Background(), command(private(member), member, "Итог дня")) + if got := client.sends[0].text; got != i18n.T("ru", "loc.closed") { + t.Fatalf("closed = %q", got) + } +} + +type deadlineStore struct { + *fakeStore + at time.Time +} + +func (s deadlineStore) Deadline(context.Context, round.Zones, int64, round.Date, *time.Location) (time.Time, error) { + return s.at, nil +} + +// A new language brings the keyboard again in it; the same one does not. +func TestLanguageChangeResendsTheKeyboard(t *testing.T) { + b, _, client := testBot(t) + ctx := context.Background() + b.handle(ctx, press(private(member), member, cb(userID, "lang:en"))) + if len(client.keyboards) != 1 || client.keyboards[0].kb.Rows[1][1].Text != "Menu" { + t.Fatalf("keyboards = %+v", client.keyboards) + } + b.handle(ctx, press(private(member), member, cb(userID, "lang:en"))) + if len(client.keyboards) != 1 { + t.Fatalf("the same language sent the keyboard again: %d", len(client.keyboards)) + } + // Following Telegram goes back to the client's Russian. + b.handle(ctx, press(private(member), member, cb(userID, actLangAuto))) + if len(client.keyboards) != 2 || client.keyboards[1].kb.Rows[1][1].Text != "Меню" { + t.Fatalf("keyboards = %+v", client.keyboards) + } + // A forged language press in a group changes no keyboard. + b.handle(ctx, press(group, member, cb(userID, "lang:de"))) + b.handle(ctx, press(group, member, cb(userID, actLangAuto))) + if len(client.keyboards) != 2 { + t.Fatalf("a group got a keyboard: %d", len(client.keyboards)) + } +} diff --git a/internal/bot/menu.go b/internal/bot/menu.go index 039a687..45094dc 100644 --- a/internal/bot/menu.go +++ b/internal/bot/menu.go @@ -222,12 +222,15 @@ func (v view) home(appURL string, admin bool, zone string) (string, telegram.Mar } // freeURL opens the Mini App on the free game: its page /play. -func freeURL(appURL string) string { +func freeURL(appURL string) string { return appPage(appURL, "/play") } + +// appPage is the Mini App's address of one of its pages. +func appPage(appURL, page string) string { u, err := url.Parse(appURL) if err != nil { return appURL } - u.Path = strings.TrimSuffix(u.Path, "/") + "/play" + u.Path = strings.TrimSuffix(u.Path, "/") + page return u.String() } diff --git a/internal/bot/panels.go b/internal/bot/panels.go index c07bade..d62eb9a 100644 --- a/internal/bot/panels.go +++ b/internal/bot/panels.go @@ -373,8 +373,9 @@ func (b *Bot) runAction(ctx context.Context, cq *tg.CallbackQuery, owner int64, if err != nil { return "", err } + was := v.lang v.lang = i18n.Resolve(raw) - return edit(v.language()) + return b.relabel(ctx, chat, was, v.lang, func() (string, error) { return edit(v.language()) }) case actSettings: return settings() case actZone: @@ -402,8 +403,9 @@ func (b *Bot) runAction(ctx context.Context, cq *tg.CallbackQuery, owner int64, if err := b.store.SetUserLang(ctx, cq.From.ID, code); err != nil { return "", err } + was := v.lang v.lang = code - return edit(v.language()) + return b.relabel(ctx, chat, was, code, func() (string, error) { return edit(v.language()) }) } if code, ok := strings.CutPrefix(action, actGroupLang+":"); ok { if !i18n.IsSupported(code) || v.sc != scopeGroup { @@ -469,6 +471,19 @@ func (b *Bot) runAction(ctx context.Context, cq *tg.CallbackQuery, owner int64, return "", nil } +// relabel redraws the language panel and, when the language changed, sends +// the DM's keyboard again in the new one: a reply keyboard cannot be edited. +func (b *Bot) relabel(ctx context.Context, chat tg.Chat, was, now string, redraw func() (string, error)) (string, error) { + alert, err := redraw() + if err != nil || was == now { + return alert, err + } + if err := b.sendKeyboard(ctx, chat, now); err != nil { + b.log.Warn("keyboard not sent", "error", err) + } + return alert, nil +} + // onMembership sets a group up when maply is added and marks it when maply // is removed. In a DM the same update says the person blocked or unblocked // maply. A restricted maply is still in the group: an admin who turned off diff --git a/internal/i18n/translations.json b/internal/i18n/translations.json index 180dd90..dd223ec 100644 --- a/internal/i18n/translations.json +++ b/internal/i18n/translations.json @@ -10889,6 +10889,78 @@ "uk": "Поки у світі найбільше шпильок: {continent} ({pct}%).", "zh": "目前全世界图钉最多的地方:{continent}({pct}%)。" }, + "kb.menu": { + "ar": "القائمة", + "be": "Меню", + "ca": "Menú", + "cs": "Menu", + "de": "Menü", + "en": "Menu", + "es": "Menú", + "fr": "Menu", + "it": "Menu", + "ja": "メニュー", + "pl": "Menu", + "ru": "Меню", + "sv": "Meny", + "tr": "Menü", + "uk": "Меню", + "zh": "菜单" + }, + "kb.placeholder": { + "ar": "مكان واحد في اليوم، دبوس واحد", + "be": "Адно месца на дзень, адна шпілька", + "ca": "Un lloc al dia, una agulla", + "cs": "Jedno místo denně, jeden špendlík", + "de": "Ein Ort am Tag, eine Nadel", + "en": "One place a day, one pin", + "es": "Un lugar al día, un pin", + "fr": "Un lieu par jour, une épingle", + "it": "Un luogo al giorno, uno spillo", + "ja": "1日1か所、ピンは1本", + "pl": "Jedno miejsce dziennie, jedna pinezka", + "ru": "Одно место в день, одна булавка", + "sv": "En plats om dagen, en nål", + "tr": "Günde bir yer, bir iğne", + "uk": "Одне місце на день, одна шпилька", + "zh": "每天一个地点,一枚图钉" + }, + "kb.ready": { + "ar": "الأزرار في الأسفل دائمًا في متناولك: اللعب ونتيجة اليوم والقائمة.", + "be": "Кнопкі ўнізе заўсёды пад рукой: гульня, вынік дня і меню.", + "ca": "Els botons de sota sempre a mà: jugar, el resultat del dia i el menú.", + "cs": "Tlačítka dole máš vždy po ruce: hra, výsledek dne a menu.", + "de": "Die Tasten unten bleiben griffbereit: spielen, Tagesergebnis und Menü.", + "en": "The buttons below stay with you: play, today's result and the menu.", + "es": "Los botones de abajo siempre a mano: jugar, el resultado del día y el menú.", + "fr": "Les boutons en bas restent à portée : jouer, le résultat du jour et le menu.", + "it": "I pulsanti in basso restano a portata di mano: gioca, il risultato del giorno e il menu.", + "ja": "下のボタンはいつでも使えます:プレイ、今日の結果、メニュー。", + "pl": "Przyciski na dole są zawsze pod ręką: gra, wynik dnia i menu.", + "ru": "Кнопки внизу всегда под рукой: игра, итог дня и меню.", + "sv": "Knapparna nedan finns alltid till hands: spela, dagens resultat och menyn.", + "tr": "Aşağıdaki düğmeler hep elinin altında: oyna, günün sonucu ve menü.", + "uk": "Кнопки внизу завжди під рукою: гра, підсумок дня і меню.", + "zh": "下方的按钮随时可用:开始玩、今日结果和菜单。" + }, + "kb.result": { + "ar": "نتيجة اليوم", + "be": "Вынік дня", + "ca": "Resultat del dia", + "cs": "Výsledek dne", + "de": "Tagesergebnis", + "en": "Today's result", + "es": "Resultado del día", + "fr": "Résultat du jour", + "it": "Risultato del giorno", + "ja": "今日の結果", + "pl": "Wynik dnia", + "ru": "Итог дня", + "sv": "Dagens resultat", + "tr": "Günün sonucu", + "uk": "Підсумок дня", + "zh": "今日结果" + }, "lang.group_hint": { "ar": "لغة المجموعة: تصل بها المنشورات والنتائج. يغيّرها المشرفون فقط.", "be": "Мова групы: на ёй прыходзяць пасты і вынікі. Мяняюць толькі адміны.", @@ -12041,6 +12113,114 @@ "uk": "Статистика", "zh": "统计" }, + "today.answered": { + "ar": "وصلت إجابتك. النتيجة في الساعة {time}، بعد {left}.", + "be": "Твой адказ прыняты. Вынік у {time}, праз {left}.", + "ca": "La teva resposta ja hi és. El resultat arriba a les {time}, d’aquí a {left}.", + "cs": "Tvoje odpověď je přijata. Výsledek ve {time}, za {left}.", + "de": "Deine Antwort ist da. Das Ergebnis kommt um {time}, in {left}.", + "en": "Your answer is in. The result is at {time}, in {left}.", + "es": "Tu respuesta está dentro. El resultado llega a las {time}, dentro de {left}.", + "fr": "Ta réponse est enregistrée. Le résultat tombe à {time}, dans {left}.", + "it": "La tua risposta è arrivata. Il risultato arriva alle {time}, tra {left}.", + "ja": "回答を受け付けました。結果は{time}、あと{left}です。", + "pl": "Twoja odpowiedź jest przyjęta. Wynik o {time}, za {left}.", + "ru": "Твой ответ принят. Итог в {time}, через {left}.", + "sv": "Ditt svar är inne. Resultatet kommer klockan {time}, om {left}.", + "tr": "Cevabın alındı. Sonuç saat {time}, {left} sonra.", + "uk": "Твою відповідь прийнято. Підсумок о {time}, через {left}.", + "zh": "你的回答已收到。{time} 公布结果,还有 {left}。" + }, + "today.none": { + "ar": "لا يوجد مكان اليوم. المكان التالي يصل في الصباح.", + "be": "Сёння месца няма. Наступнае прыйдзе раніцай.", + "ca": "Avui no hi ha lloc. El pròxim arriba al matí.", + "cs": "Dnes žádné místo není. Další přijde ráno.", + "de": "Heute gibt es keinen Ort. Der nächste kommt am Morgen.", + "en": "There is no place today. The next one comes in the morning.", + "es": "Hoy no hay lugar. El próximo llega por la mañana.", + "fr": "Pas de lieu aujourd’hui. Le prochain arrive dans la matinée.", + "it": "Oggi non c’è un luogo. Il prossimo arriva domattina.", + "ja": "今日は場所がありません。次は朝に届きます。", + "pl": "Dziś nie ma miejsca. Następne pojawi się rano.", + "ru": "Сегодня места нет. Следующее придёт утром.", + "sv": "Ingen plats idag. Nästa kommer på morgonen.", + "tr": "Bugün yer yok. Sıradaki sabah geliyor.", + "uk": "Сьогодні місця немає. Наступне прийде вранці.", + "zh": "今天没有地点。下一个早晨公布。" + }, + "today.score": { + "ar": "إجابتك اليوم: {score}.", + "be": "Твой адказ сёння: {score}.", + "ca": "La teva resposta d’avui: {score}.", + "cs": "Tvoje dnešní odpověď: {score}.", + "de": "Deine Antwort heute: {score}.", + "en": "Your answer today: {score}.", + "es": "Tu respuesta de hoy: {score}.", + "fr": "Ta réponse du jour : {score}.", + "it": "La tua risposta di oggi: {score}.", + "ja": "今日の回答:{score}。", + "pl": "Twoja dzisiejsza odpowiedź: {score}.", + "ru": "Твой ответ сегодня: {score}.", + "sv": "Ditt svar idag: {score}.", + "tr": "Bugünkü cevabın: {score}.", + "uk": "Твоя відповідь сьогодні: {score}.", + "zh": "你今天的回答:{score}。" + }, + "today.waiting": { + "ar": "لم تُجب بعد. النتيجة في الساعة {time}، بعد {left}.", + "be": "Адказу ад цябе пакуль няма. Вынік у {time}, праз {left}.", + "ca": "Encara no has respost. El resultat arriba a les {time}, d’aquí a {left}.", + "cs": "Odpověď od tebe zatím není. Výsledek ve {time}, za {left}.", + "de": "Von dir gibt es noch keine Antwort. Das Ergebnis kommt um {time}, in {left}.", + "en": "No answer from you yet. The result is at {time}, in {left}.", + "es": "Aún no has respondido. El resultado llega a las {time}, dentro de {left}.", + "fr": "Pas encore de réponse de ta part. Le résultat tombe à {time}, dans {left}.", + "it": "Non hai ancora risposto. Il risultato arriva alle {time}, tra {left}.", + "ja": "まだ回答していません。結果は{time}、あと{left}です。", + "pl": "Nie ma jeszcze twojej odpowiedzi. Wynik o {time}, za {left}.", + "ru": "Ответа от тебя пока нет. Итог в {time}, через {left}.", + "sv": "Inget svar från dig än. Resultatet kommer klockan {time}, om {left}.", + "tr": "Henüz cevap vermedin. Sonuç saat {time}, {left} sonra.", + "uk": "Відповіді від тебе поки немає. Підсумок о {time}, через {left}.", + "zh": "你还没有回答。{time} 公布结果,还有 {left}。" + }, + "today.world": { + "ar": "مركزك في العالم: {rank} من {n}.", + "be": "Месца ў свеце: {rank} з {n}.", + "ca": "Lloc al món: {rank} de {n}.", + "cs": "Místo ve světě: {rank} z {n}.", + "de": "Platz weltweit: {rank} von {n}.", + "en": "Place in the world: {rank} of {n}.", + "es": "Puesto en el mundo: {rank} de {n}.", + "fr": "Place dans le monde : {rank} sur {n}.", + "it": "Posto nel mondo: {rank} su {n}.", + "ja": "世界順位:{n}人中{rank}位。", + "pl": "Miejsce na świecie: {rank} z {n}.", + "ru": "Место в мире: {rank} из {n}.", + "sv": "Plats i världen: {rank} av {n}.", + "tr": "Dünya sıran: {n} kişi arasında {rank}.", + "uk": "Місце у світі: {rank} з {n}.", + "zh": "世界名次:{n} 人中第 {rank} 名。" + }, + "unit.hm": { + "ar": "{h} س {m} د", + "be": "{h} гадз {m} хв", + "ca": "{h} h {m} min", + "cs": "{h} h {m} min", + "de": "{h} Std. {m} Min.", + "en": "{h} h {m} min", + "es": "{h} h {m} min", + "fr": "{h} h {m} min", + "it": "{h} h {m} min", + "ja": "{h}時間{m}分", + "pl": "{h} godz. {m} min", + "ru": "{h} ч {m} мин", + "sv": "{h} h {m} min", + "tr": "{h} sa {m} dk", + "uk": "{h} год {m} хв", + "zh": "{h} 小时 {m} 分钟" + }, "unit.km": { "ar": "{km} كم", "be": "{km} км", @@ -12077,6 +12257,24 @@ "uk": "{m} м", "zh": "{m} 米" }, + "unit.min": { + "ar": "{m} د", + "be": "{m} хв", + "ca": "{m} min", + "cs": "{m} min", + "de": "{m} Min.", + "en": "{m} min", + "es": "{m} min", + "fr": "{m} min", + "it": "{m} min", + "ja": "{m}分", + "pl": "{m} min", + "ru": "{m} мин", + "sv": "{m} min", + "tr": "{m} dk", + "uk": "{m} хв", + "zh": "{m} 分钟" + }, "world.day": { "ar": "الخطأ المعتاد {km}، وأصاب {pct}% البلد.", "be": "У паловы промах меншы за {km}, краіну ўгадалі {pct}%.", diff --git a/internal/telegram/telegram.go b/internal/telegram/telegram.go index df215e8..58ea611 100644 --- a/internal/telegram/telegram.go +++ b/internal/telegram/telegram.go @@ -78,6 +78,61 @@ func (m Markup) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]any{"inline_keyboard": rows}) } +// KeyButton is one button of a reply keyboard: text the client sends back +// as a message, or a Mini App to open when WebApp is set. Style is tg's, as +// on a Button. +type KeyButton struct { + Text string + WebApp string + Style string +} + +// Keyboard is a reply keyboard that stays under the input field: persistent +// and sized to its buttons. It offers nothing but text and web_app buttons. +type Keyboard struct { + Rows [][]KeyButton + Placeholder string +} + +func (k Keyboard) MarshalJSON() ([]byte, error) { + type webApp struct { + URL string `json:"url"` + } + type button struct { + Text string `json:"text"` + WebApp *webApp `json:"web_app,omitempty"` + Style string `json:"style,omitempty"` + } + rows := make([][]button, len(k.Rows)) + for i, row := range k.Rows { + rows[i] = make([]button, len(row)) + for j, b := range row { + if b.Text == "" { + return nil, fmt.Errorf("keyboard button %d:%d has no text", i, j) + } + rows[i][j] = button{Text: b.Text, Style: b.Style} + if b.WebApp != "" { + rows[i][j].WebApp = &webApp{URL: b.WebApp} + } + } + } + out := map[string]any{"keyboard": rows, "is_persistent": true, "resize_keyboard": true} + if k.Placeholder != "" { + out["input_field_placeholder"] = k.Placeholder + } + return json.Marshal(out) +} + +// SendKeyboard posts an HTML message that puts kb under the input field. A +// message has one reply_markup, so the keyboard cannot ride on a panel. +func (c *Client) SendKeyboard(ctx context.Context, chatID int64, text string, kb Keyboard) (tg.Message, error) { + return call[tg.Message](ctx, c, "sendMessage", map[string]any{ + "chat_id": chatID, "text": text, "parse_mode": "HTML", + "link_preview_options": map[string]bool{"is_disabled": true}, + "reply_markup": kb, + }) +} + type envelope[T any] struct { OK bool `json:"ok"` Result T `json:"result"` diff --git a/internal/telegram/telegram_test.go b/internal/telegram/telegram_test.go index 1a83966..b1534ad 100644 --- a/internal/telegram/telegram_test.go +++ b/internal/telegram/telegram_test.go @@ -251,3 +251,33 @@ func TestTextPanelCarriesStyleAndWebApp(t *testing.T) { t.Fatalf("send into a topic = %+v", topic.body) } } + +// The DM's keyboard stays under the input field, sized to its buttons, and +// carries a Mini App button beside plain text ones. +func TestKeyboardMarkup(t *testing.T) { + c, fake := client(t) + kb := Keyboard{ + Rows: [][]KeyButton{ + {{Text: "Play", WebApp: "https://maply.example/today", Style: tg.StylePrimary}}, + {{Text: "Today's result"}, {Text: "Menu"}}, + }, + Placeholder: "One place a day", + } + if _, err := c.SendKeyboard(context.Background(), 42, "hi", kb); err != nil { + t.Fatal(err) + } + req := fake.requests[0] + if req.method != "sendMessage" { + t.Fatalf("method = %s", req.method) + } + got, _ := json.Marshal(req.body["reply_markup"]) + want := `{"input_field_placeholder":"One place a day","is_persistent":true,` + + `"keyboard":[[{"style":"primary","text":"Play","web_app":{"url":"https://maply.example/today"}}],` + + `[{"text":"Today's result"},{"text":"Menu"}]],"resize_keyboard":true}` + if string(got) != want { + t.Fatalf("reply_markup = %s\nwant %s", got, want) + } + if _, err := json.Marshal(Keyboard{Rows: [][]KeyButton{{{}}}}); err == nil { + t.Fatal("a button without text marshalled") + } +}