/
Dante
/
node-core
Обзор
Документация
Войти
/
Dante
/
node-core
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
node_modules/lib-git/src/telegram-bot.class.ts
63 строки
2 KB
Александр Данилюк
add
24 сен 2024, 12:59
24 сен 2024, 12:59
9eaeea8
Код
Авторство
О чём код?
import { Bot, Context, } from "grammy"; import EventEmitter from "node:events"; export interface SetUrlEvent { type: 'set_url'; url: string; } export interface BotStartEvent { type: 'bot-start'; } export type DomainEvent = BotStartEvent | SetUrlEvent; export type DomainEventType = DomainEvent['type']; export type DomainEventData<T extends DomainEventType = DomainEventType> = Extract< DomainEvent, { type: T; } >; export type DomainEventPayload<T extends DomainEventType = DomainEventType> = Omit<DomainEventData<T>, 'type'>; // announce<T extends DomainEvent>(event: T, context?: DomainEventsContext<T['type']>): void { export class TelegramBot { protected bot: Bot<Context>; protected eventBus: EventEmitter; constructor(config: {telegramBotToken: string}, eventBus: EventEmitter){ this.bot = new Bot(config.telegramBotToken); this.eventBus = eventBus; } public async sendMessage(chat_id: number, msg: string): Promise<void> { await this.bot.api.sendMessage(chat_id, msg); } public async startBot(): Promise<void> { //this.bot.on("message", (ctx) => ctx.reply("Hi there!")); this.bot.command("url", async (ctx) => { // `item` will be "apple pie" if a user sends "/add apple pie". try { const url = new URL(ctx.match); this.eventBus.emit('set_url', url.href); return ctx.reply("I take the URL for processing"); } catch (error) { this.eventBus.emit('invalid_url'); return ctx.reply("The URL invalid"); } }); this.bot.start(); } public async stopBot(): Promise<void> { this.bot.stop(); } }