const util = require('util') const crypto = require('crypto') const EventEmitter = require('events') const fs = require('fs') const db = require('../include/db') const { Api, TelegramClient } = require('telegram') const { StringSession } = require('telegram/sessions') const { NewMessage } = require('telegram/events') const { Button } = require('telegram/tl/custom/button') const { CustomFile } = require('telegram/client/uploads') const session = new StringSession(process.env.BOT_SID || '') let client function registerUser (telegramId) { db .prepare(`insert or ignore into users (telegram_id) values (:telegram_id)`) .safeIntegers(true) .run({ telegram_id: telegramId }) return db .prepare(`select id from users where telegram_id = :telegram_id`) .safeIntegers(true) .pluck(true) .get({ telegram_id: telegramId }) } function updateUser (userId, data) { const info = db .prepare(` update users set firstname = :firstname, lastname = :lastname, username = :username, access_hash = :access_hash, language_code = :language_code where id = :user_id `) .safeIntegers(true) .run({ user_id: userId, firstname: data.firstName, lastname: data.lastName, username: data.username, access_hash: data.accessHash.value, language_code: data.langCode }) return info.changes == 1 } async function updateUserPhoto (userId, data) { const photoId = data.photo?.photoId?.value if (!photoId) return const tgUserId = db .prepare(`select telegram_id from users where id = :user_id and coalesce(photo_id, 0) <> :photo_id`) .safeIntegers(true) .pluck(true) .get({user_id: userId, photo_id: photoId }) if (!tgUserId) return const photo = await client.invoke(new Api.photos.GetUserPhotos({ userId: new Api.PeerUser({ userId: tgUserId }), maxId: photoId, offset: -1, limit: 1, })); const file = await client.downloadFile(new Api.InputPhotoFileLocation({ id: photoId, accessHash: photo.photos[0]?.accessHash, fileReference: Buffer.from('random'), thumbSize: 'a', }, {})) db .prepare(`update users set photo_id = :photo_id, photo = :photo where id = :user_id`) .safeIntegers(true) .run({ user_id: userId, photo_id: photoId, photo: file.toString('base64') }) } async function registerChat (telegramId, isChannel) { db .prepare(`insert or ignore into chats (telegram_id, is_channel) values (:telegram_id, :is_channel)`) .safeIntegers(true) .run({ telegram_id: telegramId, is_channel: +isChannel }) const row = db .prepare(`select id, name from chats where telegram_id = :telegram_id`) .safeIntegers(true) .get({telegram_id: telegramId}) if (!row?.name) { const entity = isChannel ? { channelId: telegramId } : { chatId: telegramId } const chat = await client.getEntity(isChannel ? new Api.PeerChannel(entity) : new Api.PeerChat(entity)) db .prepare(`update chats set name = :name where id = :chat_id`) .run({ chat_id: row.id, name: chat.title }) } return row.id } async function attachChat(chatId, isChannel, projectId) { const info = db .prepare(`update chats set project_id = :project_id where id = :chat_id and coalesce(project_id, 1) = 1`) .run({ chat_id: chatId, project_id: projectId }) if (info.changes == 1) { const inputPeer = isChannel ? new Api.InputPeerChannel({ channelId: tgChatId }) : new Api.InputPeerChat({ chatId: tgChatId }) const query = `select (select name from customers where id = p.customer_id) || ' >> ' || p.name from projects p where id = :project_id` const message = db .prepare(query) .pluck(true) .get({project_id: projectId}) if (message) await client.sendMessage(inputPeer, {message}) } return info.changes == 1 } async function onChatAttach (tgChatId, isChannel) { const projectId = db .prepare(`select project_id from chats where telegram_id = :telegram_id`) .safeIntegers(true) .pluck(true) .get({ telegram_id: tgChatId }) const entity = isChannel ? { channelId: tgChatId } : { chatId: tgChatId } const inputPeer = await client.getEntity( isChannel ? new Api.InputPeerChannel(entity) : new Api.InputPeerChat(entity) ) const resultBtn = await client.sendMessage(inputPeer, { message: 'ReadyOrNot', buttons: client.buildReplyMarkup([[Button.url('Открыть проект', 'https://t.me/ready_or_not_2025_bot/userapp?startapp=user_' + projectId)]]) }) await client.invoke(new Api.messages.UpdatePinnedMessage({ peer: inputPeer, id: resultBtn.id, unpin: false })) //fs.appendFileSync('./1.log', '\n>' + tgChatId + ':' + isChannel + '<\n') } async function reloadChatUsers(chatId, onlyReset) { db .prepare(`delete from chat_users where chat_id = :chat_id`) .run({ chat_id: chatId }) if (onlyReset) return const chat = db .prepare(`select telegram_id, is_channel, access_hash from chats where id = :chat_id`) .get({ chat_id: chatId}) if (!chat) return const tgChatId = chat.telegram_id const isChannel = chat.is_channel let accessHash = chat.access_hash db .prepare(`update chats set access_hash = :access_hash where id = :chat_id`) .safeIntegers(true) .run({ chat_id: chatId, access_hash: accessHash, }) const result = isChannel ? await client.invoke(new Api.channels.GetParticipants({ channel: new Api.PeerChannel({ channelId: tgChatId }), filter: new Api.ChannelParticipantsRecent(), limit: 999999, offset: 0 })) : await client.invoke(new Api.messages.GetFullChat({ chatId: tgChatId, })) const users = result.users.filter(user => !user.bot) for (const user of users) { const userId = registerUser(user.id.value, user) if (updateUser(userId, user)) { await updateUserPhoto (userId, user) const query = `insert or ignore into chat_users (chat_id, user_id) values (:chat_id, :user_id)` db.prepare(query).run({ chat_id: chatId, user_id: userId }) } } } async function registerUpload(data) { if (!data.projectId || !data.media) return false const uploadChat = db .prepare(` select id, telegram_id, project_id, is_channel, access_hash from chats where id = (select upload_chat_id from customers where id = (select customer_id from projects where id = :project_id limit 1) limit 1) limit 1 `) .safeIntegers(true) .get({project_id: data.projectId}) if (!uploadChat || !uploadChat.telegram_id || uploadChat.id == data.originchatId) return false const tgUploadChatId = uploadChat.telegram_id const peer = uploadChat.is_channel ? new Api.PeerChannel({ channelId: tgUploadChatId }) : new Api.PeerChat({ chatlId: tgUploadChatId }) let resultId = 0 try { const result = await client.invoke(new Api.messages.SendMedia({ peer, media: data.media, message: data.caption || '', background: true, silent: true })) const update = result.updates.find(u => (u.className == 'UpdateNewMessage' || u.className == 'UpdateNewChannelMessage') && u.message.className == 'Message' && (u.message.peerId.channelId?.value == tgUploadChatId || u.message.peerId.chatId?.value == tgUploadChatId) && u.message.media) const udoc = update?.message?.media?.document if (udoc) { resultId = db .prepare(` insert into documents (project_id, origin_chat_id, origin_message_id, chat_id, message_id, file_id, access_hash, filename, mime, caption, size, published_by, parent_type, parent_id) values (:project_id, :origin_chat_id, :origin_message_id, :chat_id, :message_id, :file_id, :access_hash, :filename, :mime, :caption, :size, :published_by, :parent_type, :parent_id) returning id `) .safeIntegers(true) .pluck(true) .get({ project_id: data.projectId, origin_chat_id: data.originchatId, origin_message_id: data.originMessageId, chat_id: uploadChat.id, message_id: update.message.id, file_id: udoc.id.value, filename: udoc.attributes.find(attr => attr.className == 'DocumentAttributeFilename')?.fileName, access_hash: udoc.accessHash.value, mime: udoc.mimeType, caption: data.caption, size: udoc.size.value, published_by: data.publishedBy, parent_type: data.parentType, parent_id: data.parentId }) } } catch (err) { fs.appendFileSync('./1.log', '\n\nERR:' + err.message + ':' + JSON.stringify (err.stack)+'\n\n') console.error('Message.registerUpload: ' + err.message) } return resultId } async function onNewServiceMessage (msg, isChannel) { const action = msg.action || {} const tgChatId = isChannel ? msg.peerId?.channelId?.value : msg.peerId?.chatId?.value const chatId = await registerChat(tgChatId, isChannel) // Ghat rename if (action.className == 'MessageActionChatEditTitle') { const info = db .prepare(` update chats set name = :name, is_channel = :is_channel, last_update_time = :last_update_time where telegram_id = :telegram_id `) .safeIntegers(true) .run({ name: action.title, is_channel: +isChannel, last_update_time: Math.floor (Date.now() / 1000), telegram_id: tgChatId }) } // Chat to Channel if (action.className == 'MessageActionChatMigrateTo') { const info = db .prepare(` update chats set telegram_id = :new_telegram_id, name = :name, is_channel = 1, last_update_time = :last_update_time where telegram_id = :old_telegram_id `) .safeIntegers(true) .run({ name: action.title, last_update_time: Date.now() / 1000, old_telegram_id: tgChatId, new_telegram_id: action.channelId.value }) } // User/s un/register if (action.className == 'MessageActionChatAddUser' || action.className == 'MessageActionChatDeleteUser' || action.className == 'MessageActionChannelAddUser' || action.className == 'MessageActionChannelDeleteUser' ) { const tgUserIds = [action.user, action.users, action.userId].flat().filter(Boolean).map(e => BigInt(e.value)) const isAdd = action.className == 'MessageActionChatAddUser' || action.className == 'MessageActionChannelAddUser' if (tgUserIds.indexOf(bot.id) == -1) { // Add/remove non-bot users for (const tgUserId of tgUserIds) { const userId = registerUser(tgUserId) if (isAdd) { try { const user = await client.getEntity(new Api.PeerUser({ userId: tgUserId })) updateUser(userId, user) await updateUserPhoto (userId, user) } catch (err) { console.error(msg.className + ', ' + userId + ': ' + err.message) } } const query = isAdd ? `insert or ignore into chat_users (chat_id, user_id) values (:chat_id, :user_id)` : `delete from chat_users where chat_id = :chat_id and user_id = :user_id` db.prepare(query).run({ chat_id: chatId, user_id: userId }) } } } } async function onNewMessage (msg, isChannel) { const tgChatId = isChannel ? msg.peerId?.channelId?.value : msg.peerId?.chatId?.value const chatId = await registerChat(tgChatId, isChannel) // Document is detected if (msg.media?.document) { const doc = msg.media.document const projectId = db .prepare(`select project_id from chats where telegram_id = :telegram_id`) .safeIntegers(true) .pluck(true) .get({telegram_id: tgChatId}) const media = new Api.InputMediaDocument({ id: new Api.InputDocument({ id: doc.id.value, accessHash: doc.accessHash.value, fileReference: doc.fileReference }) }) await registerUpload({ projectId, media, caption: msg.message, originchatId: chatId, originMessageId: msg.id, parentType: 0, publishedBy: registerUser (msg.fromId?.userId?.value) }) } if (msg.message?.startsWith('KEY-')) { let projectName = db .prepare(` select name from projects where id in ( select project_id from chats where id = :chat_id union select id from projects where upload_chat_id = :chat_id) `) .pluck(true) .get({ chat_id: chatId }) if (projectName) return await bot.sendMessage(chatId, 'Группа уже используется на проекте ' + projectName) const [_, time64, key] = msg.message.substr(3).split('-') const now = Math.floor(Date.now() / 1000) const time = Buffer.from(time64, 'base64') if (now - 3600 >= time && time >= now) return await bot.sendMessage(chatId, 'Время действия ключа для привязки истекло') const projectId = db .prepare(`select id from projects where generate_key(id, :time) = :key`) .pluck(true) .get({ key: msg.message.trim(), time }) if (projectId) { await attachChat(chatId, isChannel, projectId) await onChatAttach(tgChatId, isChannel) } } if (msg.message?.startsWith('/start')) { // Called by https://t.me/ready_or_not_2025_bot?startgroup= if (/start@ready_or_not_2025_bot (-|)([\d]+)$/g.test(msg.message)) { const tgUserId = msg.fromId?.userId?.value const param = +msg.message.split(' ')[1] // Set upload group for customer if (param < 0) { const customerId = -param db .prepare(` update customers set upload_chat_id = :chat_id where id = :customer_id and telegram_user_id = :telegram_user_id `) .safeIntegers(true) .run({ chat_id: chatId, customer_id: customerId, telegram_user_id: tgUserId }) } // Add group to project if (param > 0) { const projectId = param const customerId = db .prepare(`select customer_id from projects where id = :project_id`) .pluck(true) .get({project_id: projectId}) db .prepare(` update chats set project_id = :project_id where id = :chat_id and exists( select 1 from customers where id = :customer_id and telegram_user_id = :telegram_user_id) `) .safeIntegers(true) .run({ project_id: projectId, chat_id: chatId, customer_id: customerId, telegram_user_id: tgUserId }) await reloadChatUsers(chatId, false) await onChatAttach(tgChatId, isChannel) } } } } async function onNewUserMessage (msg) { if (msg.message == '/start' && msg.peerId?.className == 'PeerUser') { const tgUserId = msg.peerId?.userId?.value const userId = registerUser(tgUserId) try { const user = await client.getEntity(new Api.PeerUser({ userId: tgUserId })) updateUser(userId, user) await updateUserPhoto (userId, user) const appButton = new Api.KeyboardButtonWebView({ text: "Open Mini-App", // Текст на кнопке url: "https://h5sj0gpz-3000.euw.devtunnels.ms/", // URL вашего Mini-App (HTTPS!) }); const inputPeer = new Api.InputPeerUser({userId: tgUserId, accessHash: user.accessHash.value}) const resultBtn = await client.sendMessage(inputPeer, { message: 'Сообщение от бота', buttons: client.buildReplyMarkup([ [Button.url('Админка', 'https://t.me/ready_or_not_2025_bot/userapp?startapp=admin')], [Button.url('Пользователь', 'https://t.me/ready_or_not_2025_bot/userapp?startapp=user')], [appButton] ]) }) } catch (err) { console.error(msg.className + ', ' + userId + ': ' + err.message) } } } async function onUpdatePaticipant (update, isChannel) { const tgChatId = isChannel ? update.channelId?.value : update.chatlId?.value if (!tgChatId || update.userId?.value != bot.id) return const chatId = await registerChat (tgChatId, isChannel) const isBan = update.prevParticipant && !update.newParticipant const isAdd = (!update.prevParticipant || update.prevParticipant?.className == 'ChannelParticipantBanned') && update.newParticipant if (isBan || isAdd) await reloadChatUsers(chatId, isBan) if (isBan) { db .prepare(`update chats set project_id = null where id = :chat_id`) .run({chat_id: chatId}) } const botCanBan = update.newParticipant?.adminRights?.banUsers || 0 db .prepare(`update chats set bot_can_ban = :bot_can_ban where id = :chat_id`) .run({chat_id: chatId, bot_can_ban: +botCanBan}) } class Bot extends EventEmitter { async start (apiId, apiHash, botAuthToken) { this.id = BigInt(botAuthToken.split(':')[0]) client = new TelegramClient(session, apiId, apiHash, {}) client.addEventHandler(async (update) => { if (update.className == 'UpdateConnectionState') return if (update.className == 'UpdateNewMessage' || update.className == 'UpdateNewChannelMessage') { const msg = update?.message const isChannel = update.className == 'UpdateNewChannelMessage' if (!msg) return const result = msg.peerId?.className == 'PeerUser' ? await onNewUserMessage(msg) : msg.className == 'MessageService' ? await onNewServiceMessage(msg, isChannel) : await onNewMessage(msg, isChannel) } if (update.className == 'UpdateChatParticipant' || update.className == 'UpdateChannelParticipant') await onUpdatePaticipant(update, update.className == 'UpdateChannelParticipant') }) await client.start({botAuthToken}) console.log('BOT_SID: ', session.save()) } async uploadDocument(projectId, fileName, mime, data, parentType, parentId, publishedBy) { const file = await client.uploadFile({ file: new CustomFile(fileName, data.length, '', data), workers: 1 }) const media = new Api.InputMediaUploadedDocument({ file, mimeType: mime, attributes: [new Api.DocumentAttributeFilename({ fileName })] }) return await registerUpload({ projectId, media, parentType, parentId, publishedBy }) } async downloadDocument(projectId, documentId) { const document = db .prepare(` select file_id, access_hash, '' thumbSize, filename, mime from documents where id = :document_id and project_id = :project_id `) .safeIntegers(true) .get({project_id: projectId, document_id: documentId}) if (!document) return false const result = await client.downloadFile(new Api.InputDocumentFileLocation({ id: document.file_id, accessHash: document.access_hash, fileReference: Buffer.from(document.filename), thumbSize: '' }, {})) return { filename: document.filename, mime: document.mime, size: result.length, data: result } } async reloadChatUsers(chatId, onlyReset) { return reloadChatUsers(chatId, onlyReset) } async sendMessage (chatId, message) { const chat = db .prepare(`select telegram_id, is_channel from chats where id = :chat_id`) .get({ chat_id: chatId}) if (!chat) return const entity = chat.is_channel ? { channelId: chat.telegram_id } : { chatId: chat.telegram_id } const inputPeer = await client.getEntity( chat.is_channel ? new Api.InputPeerChannel(entity) : new Api.InputPeerChat(entity) ) await client.sendMessage(inputPeer, {message}) const delay = ms => new Promise(resolve => setTimeout(resolve, ms)) await delay(1000) } async leaveChat (chatId) { const chat = db .prepare(`select telegram_id, is_channel from chats where id = :chat_id`) .get({ chat_id: chatId}) if (!chat) return if (chat.is_channel) { const inputPeer = await client.getEntity(new Api.InputPeerChannel({ channelId: chat.telegram_id })) await client.invoke(new Api.channels.LeaveChannel({ channel: inputPeer })) } else { await client.invoke(new Api.messages.DeleteChatUser({ chatId: chat.telegram_id, userId: this.id })) } } } const bot = new Bot() module.exports = bot