mic-bot/bot/bot.ts
2024-10-25 19:35:12 +02:00

34 lines
1.2 KiB
TypeScript

import { Bot, Context, session, BotError, GrammyError, HttpError } from "https://deno.land/x/grammy/mod.ts";
import { Ctx, defaultSessionData } from "./ctx.ts";
import * as config from "../cfg/config.ts"
import { ERR_CODES, Err } from "../utils/errors.ts";
class BotUnknownOnStartErr extends Err {
code: ERR_CODES = ERR_CODES.UnknownErr;
}
export const runBot = async (cfg: config.BotConfig, initMode: (bot: Bot<Ctx>) => void) => {
const bot = new Bot<Ctx>(cfg.bot_token)
bot.use(session({ initial: defaultSessionData }))
bot.catch((err: BotError<Context>) => {
const ctx = err.ctx;
console.error(`Error while handling update ${ctx.update.update_id}:`);
const e = err.error;
if (e instanceof GrammyError) {
if (e.error_code === 400 && e.method === "deleteMessage") return
console.error("Error in request:", e.description);
} else if (e instanceof HttpError) {
console.error("Could not contact Telegram:", e);
} else {
throw new BotUnknownOnStartErr("Unknown error while starting the bot",
{ cause: err })
}
})
initMode(bot)
await bot.init()
console.log(`starting bot ${bot.botInfo.username}`)
await bot.start().catch(err => console.log(err))
}