From e4bfc6ab0ea889f3e783a113cc3a75226d710e05 Mon Sep 17 00:00:00 2001 From: LittleC Date: Mon, 7 Aug 2023 15:23:44 +0800 Subject: [PATCH] feat(telegram): slash command --- adapters/telegram/src/bot.ts | 26 ++++++++++++++++++++++++++ adapters/telegram/src/utils.ts | 9 ++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/adapters/telegram/src/bot.ts b/adapters/telegram/src/bot.ts index d8261417..ccddaf7c 100644 --- a/adapters/telegram/src/bot.ts +++ b/adapters/telegram/src/bot.ts @@ -284,6 +284,32 @@ export class TelegramBot exte user.avatar = `${endpoint}/${file.file_path}` } } + + async updateCommands(commands: Universal.Command[]) { + const languages = this.ctx.i18n.fallback([]) + const order = languages.filter(v => v.length === 2) + const languageSubset = order.map(v => languages.filter(l => l.startsWith(v))) + type LangCode = string + const result = {} as Record + for (const subset of languageSubset) { + const code6391 = subset.find(v => v.length === 2) + result[code6391] ||= [] + for (const cmd of commands) { + const { name, description } = cmd + const cmdDesc = subset.map(lang => description[lang]).filter(v => v)?.[0] ?? cmd.name + result[code6391].push({ command: name, description: cmdDesc }) + } + } + for (const lang of Object.keys(result)) { + await this.internal.setMyCommands({ + commands: result[lang], + language_code: lang, + }) + } + await this.internal.setMyCommands({ + commands: commands.map(({ name }) => ({ command: name, description: name })), + }) + } } TelegramBot.prototype.platform = 'telegram' diff --git a/adapters/telegram/src/utils.ts b/adapters/telegram/src/utils.ts index 05c93639..efe42b11 100644 --- a/adapters/telegram/src/utils.ts +++ b/adapters/telegram/src/utils.ts @@ -46,9 +46,16 @@ export async function handleUpdate(update: Telegram.Update, bot: TelegramBot) { Object.assign(session.telegram, update) const message = update.message || update.edited_message || update.channel_post || update.edited_channel_post - if (message) { + const isBotCommand = update.message && update.message.entities?.[0].type === 'bot_command' + if (message && !isBotCommand) { session.type = update.message || update.channel_post ? 'message' : 'message-updated' await bot.adaptMessage(message, session) + } else if (isBotCommand) { + session.type = 'message' + const p = bot.ctx.root.config.prefix + const prefix = (Array.isArray(p) ? p[0] : p) ?? '' + await bot.adaptMessage(message, session) + session.content = prefix + session.content.slice(1) } else if (update.chat_join_request) { session.timestamp = update.chat_join_request.date * 1000 session.type = 'guild-member-request'