mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-20 11:10:49 +08:00
feat(telegram): register command menu and menu button on bot start
Add setMyCommands and setChatMenuButton to the Telegram Bot API client and register a 12-command menu with a commands-type menu button when a bot runtime connects. Menu setup failures are logged as warnings and do not block startup. Co-authored-by: xmanrui <841206367@qq.com>
This commit is contained in:
parent
7fbb459e00
commit
60e00bbca9
4 changed files with 284 additions and 132 deletions
|
|
@ -16,6 +16,18 @@ export function validTelegramToken(value) {
|
|||
return typeof value === 'string' && /^\d{5,20}:[A-Za-z0-9_-]{20,}$/.test(value.trim());
|
||||
}
|
||||
|
||||
const TELEGRAM_COMMAND_NAME = /^[a-z0-9_]{1,32}$/;
|
||||
|
||||
function validBotCommand(value) {
|
||||
return Boolean(value)
|
||||
&& typeof value === 'object' && !Array.isArray(value)
|
||||
&& typeof value.command === 'string' && TELEGRAM_COMMAND_NAME.test(value.command)
|
||||
&& typeof value.description === 'string' && value.description.length >= 1
|
||||
&& value.description.length <= 256;
|
||||
}
|
||||
|
||||
export const COMMANDS_MENU_BUTTON = Object.freeze({ type: 'commands' });
|
||||
|
||||
export class TelegramApi {
|
||||
#token;
|
||||
#fetch;
|
||||
|
|
@ -113,6 +125,25 @@ export class TelegramApi {
|
|||
}, { signal });
|
||||
}
|
||||
|
||||
async setMyCommands({ commands, scope, languageCode, signal } = {}) {
|
||||
if (!Array.isArray(commands) || commands.length === 0
|
||||
|| commands.some((command) => !validBotCommand(command))) {
|
||||
throw new TypeError('Telegram bot commands are invalid');
|
||||
}
|
||||
return this.#call('setMyCommands', {
|
||||
commands,
|
||||
...(scope ? { scope } : {}),
|
||||
...(cleanString(languageCode) ? { language_code: cleanString(languageCode) } : {}),
|
||||
}, { signal });
|
||||
}
|
||||
|
||||
async setChatMenuButton({ menuButton = COMMANDS_MENU_BUTTON, signal } = {}) {
|
||||
if (!menuButton || typeof menuButton !== 'object' || Array.isArray(menuButton)) {
|
||||
throw new TypeError('Telegram menu button is invalid');
|
||||
}
|
||||
return this.#call('setChatMenuButton', { menu_button: menuButton }, { signal });
|
||||
}
|
||||
|
||||
async #call(method, payload, { signal, timeoutMs = 15_000 } = {}) {
|
||||
const url = new URL(this.#baseUrl);
|
||||
url.pathname = `${url.pathname.replace(/\/$/, '')}/bot${this.#token}/${method}`;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue