|
| 1 | +const { Opengram, session } = require('opengram') |
| 2 | +const { MediaGroup } = require('@opengram/media-group') |
| 3 | +const { BOT_TOKEN } = require('../config') |
| 4 | +const { handlers } = require('../middlewares/handlers') |
| 5 | +const { logger } = require('./logger') |
| 6 | +const { stage } = require('../middlewares/stage') |
| 7 | +const { authorization } = require('../middlewares/authorization') |
| 8 | +const { StickerSet, User } = require('./models') |
| 9 | +const { i18nFactory } = require('../middlewares/i18n') |
| 10 | +const i18next = require('i18next') |
| 11 | +const fetch = require('node-fetch') |
| 12 | +const { sha1 } = require('./utils') |
| 13 | + |
| 14 | +const bot = new Opengram(BOT_TOKEN) |
| 15 | + |
| 16 | +bot.context.model = { |
| 17 | + User, |
| 18 | + StickerSet |
| 19 | +} |
| 20 | + |
| 21 | +async function startBot () { |
| 22 | + bot.context.loadBotsAPIReference = async function () { |
| 23 | + const data = await fetch('https://ark0f.github.io/tg-bot-api/custom.json') |
| 24 | + .then(x => x.json()) |
| 25 | + |
| 26 | + data.objects.forEach((v, i) => { |
| 27 | + data.objects[i].__object = true |
| 28 | + data.objects[i].id = sha1([v.name, 'type'].join()) |
| 29 | + }) |
| 30 | + |
| 31 | + data.methods.forEach((v, i) => { |
| 32 | + data.methods[i].__method = true |
| 33 | + data.methods[i].id = sha1([v.name, 'method'].join()) |
| 34 | + }) |
| 35 | + |
| 36 | + bot.context.botsAPIReference = data |
| 37 | + } |
| 38 | + |
| 39 | + await bot.context.loadBotsAPIReference() |
| 40 | + |
| 41 | + await i18next.init({ |
| 42 | + lng: 'ru', |
| 43 | + fallbackLng: 'ru', |
| 44 | + debug: true, |
| 45 | + resources: { |
| 46 | + ru: require('../../locales/ru') |
| 47 | + } |
| 48 | + }) |
| 49 | + |
| 50 | + bot.use( |
| 51 | + new MediaGroup(), |
| 52 | + session({ |
| 53 | + /** |
| 54 | + * Session key generator |
| 55 | + * |
| 56 | + * @param {OpengramContext} ctx Context |
| 57 | + * @return {null|string} |
| 58 | + */ |
| 59 | + getSessionKey: (ctx) => { |
| 60 | + if (ctx.from.id && ctx.chat?.id) { |
| 61 | + return `${ctx.from.id}:${ctx.chat.id}` |
| 62 | + } |
| 63 | + |
| 64 | + if (ctx.inlineQuery || ctx.callbackQuery?.inline_message_id) { |
| 65 | + return `${ctx.from.id}:${ctx.from.id}` |
| 66 | + } |
| 67 | + |
| 68 | + return null |
| 69 | + } |
| 70 | + }), |
| 71 | + i18nFactory(i18next), |
| 72 | + authorization, |
| 73 | + stage, |
| 74 | + handlers |
| 75 | + ) |
| 76 | + |
| 77 | + bot.catch(err => logger.error('Bot error:', err)) |
| 78 | + |
| 79 | + return bot.launch({ |
| 80 | + polling: { |
| 81 | + allowedUpdates: ['callback_query', 'message', 'inline_query'] |
| 82 | + } |
| 83 | + }) |
| 84 | + .then(() => logger.info('Bot started successfully')) |
| 85 | +} |
| 86 | + |
| 87 | +module.exports = startBot |
0 commit comments