mic-bot/bot/bot.ts

51 lines
1.6 KiB
TypeScript

import { Bot, Context, session, BotError, GrammyError, HttpError } from "https://deno.land/x/grammy/mod.ts";
import { Ctx, defaultSessionData } from "./ctx.ts";
import { BotConfig } from "../cfg/config.ts"
import { ERR_CODES, Err } from "../utils/errors.ts";
import { I18n } from "https://deno.land/x/grammy_i18n@v1.1.0/mod.ts";
class BotUnknownOnStartErr extends Err {
code: ERR_CODES = ERR_CODES.UnknownErr
}
export const runBot = async (cfg: BotConfig, initMode: (bot: Bot<Ctx>) => void) => {
const bot = new Bot<Ctx>(cfg.bot_token)
const i18n = new I18n<Ctx>({
defaultLocale: "en",
directory: cfg.locales_dir,
localeNegotiator: (ctx) =>
ctx.from?.language_code ?? "en"
})
console.log("Loaded locales: ", i18n.locales)
bot.use(session({ initial: defaultSessionData }), i18n)
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({
allowed_updates: [
"chat_member",
"message",
"inline_query"
]
}).catch(err => console.log(err))
await bot.stop();
}