|
| 1 | +import type { User } from '@roll-stack/database' |
| 2 | +import type { Context } from 'grammy' |
| 3 | +import { createId } from '@paralleldrive/cuid2' |
| 4 | +import { db } from '@roll-stack/database' |
| 5 | +import { Bot } from 'grammy' |
| 6 | +import { generateAccessCode, getBotToken, requestContactPhone } from './common' |
| 7 | + |
| 8 | +const logger = useLogger('telegram:hub-bot') |
| 9 | +const { telegram } = useRuntimeConfig() |
| 10 | + |
| 11 | +let bot: Bot | null = null |
| 12 | + |
| 13 | +export async function useCreateHubBot() { |
| 14 | + const token = await getBotToken(telegram.wasabiBotId) |
| 15 | + if (!token) { |
| 16 | + throw new Error('Hub bot is not configured') |
| 17 | + } |
| 18 | + |
| 19 | + bot = new Bot(token, { |
| 20 | + client: { apiRoot: telegram.localBotApiServerUrl }, |
| 21 | + }) |
| 22 | + |
| 23 | + bot.on('message:text', async (ctx) => { |
| 24 | + if (ctx.hasCommand('start')) { |
| 25 | + return handleStart(ctx) |
| 26 | + } |
| 27 | + |
| 28 | + return handleMessage(ctx) |
| 29 | + }) |
| 30 | + |
| 31 | + // User shared contact |
| 32 | + bot.on('message:contact', async (ctx) => { |
| 33 | + return handleContact(ctx) |
| 34 | + }) |
| 35 | + |
| 36 | + // Somebody invited bot to a group |
| 37 | + bot.on('my_chat_member', async (ctx) => { |
| 38 | + logger.log('my_chat_member', ctx.update) |
| 39 | + }) |
| 40 | + |
| 41 | + try { |
| 42 | + await bot.start() |
| 43 | + logger.info('Hub bot started successfully') |
| 44 | + } catch (error) { |
| 45 | + logger.error('Failed to start Hub bot:', error) |
| 46 | + throw error |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +async function handleStart(ctx: Context) { |
| 51 | + if (!ctx.message) { |
| 52 | + return |
| 53 | + } |
| 54 | + |
| 55 | + // Not private chat? |
| 56 | + if (ctx.message.chat.type !== 'private') { |
| 57 | + await ctx.reply('Я пока не умею отвечать на групповые сообщения.') |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + // Find user |
| 62 | + const telegramUser = await db.telegram.findUserByTelegramIdAndBotId(ctx.message.from.id.toString(), telegram.wasabiBotId) |
| 63 | + if (!telegramUser) { |
| 64 | + // Request phone number from user |
| 65 | + await requestContactPhone(ctx) |
| 66 | + return |
| 67 | + } |
| 68 | + |
| 69 | + if (!telegramUser.user || !telegramUser.user.isActive) { |
| 70 | + await ctx.reply('Нет доступа. Используйте ранее полученный Ключ доступа.') |
| 71 | + return |
| 72 | + } |
| 73 | + |
| 74 | + await ctx.reply('Вы уже авторизованы.') |
| 75 | +} |
| 76 | + |
| 77 | +async function handleMessage(ctx: Context) { |
| 78 | + if (!ctx.message || !ctx.message.text) { |
| 79 | + return |
| 80 | + } |
| 81 | + |
| 82 | + const telegramUser = await db.telegram.findUserByTelegramIdAndBotId(ctx.message.from.id.toString(), telegram.wasabiBotId) |
| 83 | + if (!telegramUser?.user) { |
| 84 | + return |
| 85 | + } |
| 86 | + |
| 87 | + logger.log('message', telegramUser.user.id, ctx.message.from.id, ctx.message.text) |
| 88 | +} |
| 89 | + |
| 90 | +async function handleContact(ctx: Context) { |
| 91 | + if (!ctx.message?.contact) { |
| 92 | + return |
| 93 | + } |
| 94 | + |
| 95 | + // Not private chat? |
| 96 | + if (ctx.message.chat.type !== 'private') { |
| 97 | + await ctx.reply('Я пока не умею отвечать на групповые сообщения.') |
| 98 | + return |
| 99 | + } |
| 100 | + |
| 101 | + const botToken = await getBotToken(telegram.wasabiBotId) |
| 102 | + if (!botToken) { |
| 103 | + return null |
| 104 | + } |
| 105 | + |
| 106 | + const phone = ctx.message.contact.phone_number.replace(/\D/g, '') |
| 107 | + const user = await findOrCreateHubUser({ |
| 108 | + phone, |
| 109 | + user: { |
| 110 | + name: ctx.message.from.first_name, |
| 111 | + surname: ctx.message.from.last_name, |
| 112 | + }, |
| 113 | + ctx, |
| 114 | + botToken, |
| 115 | + }) |
| 116 | + |
| 117 | + const telegramUser = await db.telegram.findUserByTelegramIdAndBotId(ctx.message.from.id.toString(), telegram.wasabiBotId) |
| 118 | + if (!telegramUser?.id) { |
| 119 | + const accessKey = await generateAccessCode() |
| 120 | + |
| 121 | + const createdTelegramUser = await db.telegram.createUser({ |
| 122 | + telegramUserType: ctx.message.chat.type, |
| 123 | + telegramId: ctx.message.from.id.toString(), |
| 124 | + firstName: ctx.message.from.first_name, |
| 125 | + lastName: ctx.message.from.last_name, |
| 126 | + username: ctx.message.from.username, |
| 127 | + botId: telegram.wasabiBotId, |
| 128 | + accessKey, |
| 129 | + userId: user.id, |
| 130 | + }) |
| 131 | + |
| 132 | + logger.log('New Telegram user', createdTelegramUser) |
| 133 | + |
| 134 | + await ctx.setChatMenuButton({ |
| 135 | + chat_id: ctx.message.chat.id, |
| 136 | + menu_button: { |
| 137 | + type: 'web_app', |
| 138 | + text: 'Хаб', |
| 139 | + web_app: { |
| 140 | + url: 'https://t.me/wasabi_hub_bot/app', |
| 141 | + }, |
| 142 | + }, |
| 143 | + }) |
| 144 | + |
| 145 | + await ctx.reply(`🎉 Успех! Через этого бота вы можете открыть Хаб. Это место, в котором мы проводим события и делимся полезной информацией.`, { |
| 146 | + reply_markup: { |
| 147 | + remove_keyboard: true, |
| 148 | + }, |
| 149 | + }) |
| 150 | + return |
| 151 | + } |
| 152 | + |
| 153 | + await ctx.reply('Номер уже подтвержден.') |
| 154 | +} |
| 155 | + |
| 156 | +async function findOrCreateHubUser(data: { phone: string, user: { name: string, surname: string | undefined }, ctx: Context, botToken: string }): Promise<User> { |
| 157 | + const userInDB = await db.user.findByPhone(data.phone) |
| 158 | + if (!userInDB) { |
| 159 | + const id = createId() |
| 160 | + const avatarUrl = `https://avatar.nextorders.ru/${id}?emotion=7&gender=female` |
| 161 | + |
| 162 | + const createdUser = await db.user.create({ |
| 163 | + id, |
| 164 | + phone: data.phone, |
| 165 | + type: 'prospective_partner', |
| 166 | + name: data.user.name, |
| 167 | + surname: data.user.surname, |
| 168 | + avatarUrl, |
| 169 | + gender: 'female', |
| 170 | + caption: 'Новый пользователь', |
| 171 | + }) |
| 172 | + logger.log('New prospective partner', createdUser) |
| 173 | + |
| 174 | + return createdUser |
| 175 | + } |
| 176 | + |
| 177 | + return userInDB |
| 178 | +} |
| 179 | + |
| 180 | +export function useHubBot(): Bot { |
| 181 | + if (!bot) { |
| 182 | + throw new Error('Hub bot is not initialized. Call useCreateHubBot() first.') |
| 183 | + } |
| 184 | + |
| 185 | + return bot |
| 186 | +} |
0 commit comments