Skip to content
← Public packages

@kody/telegram

Read Telegram chats the bot can see and send confirmed messages through the Bot API using telegramBotToken.

src/get-me.ts

73 lines · 2.2 KB · TypeScript
Raw
/**
 * @fileoverview Return the authenticated Telegram bot identity via `getMe`.
 * Use as a smoke check after setting the bot token secret.
 *
 * @example
 * import getMe from 'kody:@kody/telegram/get-me'
 * const me = await getMe()
 */

import { inputRecord, secretNameFrom } from './validation.ts'
import { telegramRequest } from './request.ts'

export type TelegramUser = {
	id?: number
	is_bot?: boolean
	first_name?: string
	username?: string
	can_join_groups?: boolean
	can_read_all_group_messages?: boolean
	supports_inline_queries?: boolean
	[key: string]: unknown
}

/**
 * Return the authenticated Telegram bot identity via `getMe`.
 * Use as a smoke check after setting the bot token secret.
 *
 * @param bot - Raw Telegram user/bot object from getMe.
 * @returns Compact bot summary fields.
 *
 * @example
 * import getMe from 'kody:@kody/telegram/get-me'
 * const me = await getMe()
 */
export function summarizeBot(bot: TelegramUser) {
	return {
		id: typeof bot.id === 'number' ? bot.id : null,
		isBot: bot.is_bot === true,
		hasUsername: typeof bot.username === 'string' && bot.username.length > 0,
		username: typeof bot.username === 'string' ? bot.username : null,
		firstName: typeof bot.first_name === 'string' ? bot.first_name : null,
		canJoinGroups: bot.can_join_groups === true,
		canReadAllGroupMessages: bot.can_read_all_group_messages === true,
		supportsInlineQueries: bot.supports_inline_queries === true,
	}
}

/** Return the authenticated bot identity via getMe. */
/**
 * Return the authenticated Telegram bot identity via `getMe`.
 * Use this as a smoke check after setting the bot token secret.
 *
 * @param params.secretName - Optional bot-token secret name override.
 * @returns `{ ok, secretName, bot }` with a compact bot summary.
 *
 * @example
 * import getMe from 'kody:@kody/telegram/get-me'
 * const me = await getMe()
 * // => { ok: true, secretName: 'telegramBotToken', bot: { id: …, username: '…', isBot: true } }
 */
export default async function getMe(params: Record<string, unknown> = {}) {
	const input = inputRecord(params)
	const secretName = secretNameFrom(input)
	const bot = await telegramRequest<TelegramUser>({
		method: 'getMe',
		secretName,
	})
	return {
		ok: true,
		secretName,
		bot: summarizeBot(bot),
	}
}