mic-bot/bot/bot.ts

51 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

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