From 7a758802fe0af699bfcdb31698e2328239d12e10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=BF=D0=BE=D1=88=D0=B5=D0=BB=20=D0=BD=D0=B0=D1=85=D1=83?= =?UTF-8?q?=D0=B9?= Date: Fri, 22 Aug 2025 20:45:56 +0000 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20telegram-userbot.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- telegram-userbot.js | 184 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 telegram-userbot.js diff --git a/telegram-userbot.js b/telegram-userbot.js new file mode 100644 index 0000000..10fcb6c --- /dev/null +++ b/telegram-userbot.js @@ -0,0 +1,184 @@ +import { TelegramClient } from "telegram" +import { StringSession } from "telegram/sessions/index.js" +import { NewMessage } from "telegram/events/index.js" +import fs from "fs" +import path from "path" +import { fileURLToPath } from "url" +import readline from "readline" + +const __filename = fileURLToPath(import.meta.url) +const __dirname = path.dirname(__filename) + +const apiId = "YOUR_API_ID" +const apiHash = "YOUR_API_HASH" +const phoneNumber = "YOUR_PHONE_NUMBER" + +const sessionFile = path.join(__dirname, "session.txt") +let stringSession = "" + +if (fs.existsSync(sessionFile)) { + stringSession = fs.readFileSync(sessionFile, "utf8") +} + +const client = new TelegramClient(new StringSession(stringSession), apiId, apiHash, { + connectionRetries: 5, +}) + +const commands = new Map() +const startTime = Date.now() + +async function loadCommands() { + const modulesDir = path.join(__dirname, "modules") + + if (!fs.existsSync(modulesDir)) { + console.log("Папка modules не найдена. Создаю...") + fs.mkdirSync(modulesDir, { recursive: true }) + return + } + + const files = fs.readdirSync(modulesDir).filter((file) => file.endsWith(".js")) + + for (const file of files) { + try { + const modulePath = path.join(modulesDir, file) + delete require.cache[require.resolve(modulePath)] + + const module = await import(`file://${modulePath}?t=${Date.now()}`) + const command = module.default + + if (command && command.name && command.execute) { + commands.set(command.name, command) + console.log(`Загружен модуль: ${file}`) + } + } catch (error) { + console.log(`Ошибка загрузки модуля ${file}: ${error.message}`) + } + } + + console.log(`Загружено команд: ${commands.size}`) + + if (commands.size === 0) { + console.log("Команды не найдены. Убедитесь, что файлы команд находятся в папке modules/") + } +} + +async function reloadCommand(commandName) { + const modulePath = path.join(__dirname, "modules", `${commandName}.js`) + + if (!fs.existsSync(modulePath)) { + return false + } + + try { + delete require.cache[require.resolve(modulePath)] + const module = await import(`file://${modulePath}?t=${Date.now()}`) + const command = module.default + + if (command && command.name && command.execute) { + commands.set(command.name, command) + return true + } + } catch (error) { + console.log(`Ошибка перезагрузки модуля ${commandName}: ${error.message}`) + } + + return false +} + +client.addEventHandler(async (event) => { + try { + const message = event.message + if (!message || !message.text) return + + const sender = await message.getSender() + if (!sender || sender.id.toString() !== (await client.getMe()).id.toString()) return + + const text = message.text.trim() + if (!text.startsWith("!") && !text.startsWith(".")) return + + const args = text.slice(1).split(" ") + const commandName = args.shift().toLowerCase() + + if (commandName === "lm" || commandName === "loadmod") { + if (args.length === 0) { + await client.sendMessage(message.chatId, { + message: "Использование: .lm <название_модуля>\nПример: .lm ping", + }) + return + } + + const moduleName = args[0] + const success = await reloadCommand(moduleName) + + if (success) { + await client.sendMessage(message.chatId, { + message: `Модуль ${moduleName} успешно загружен/перезагружен`, + }) + } else { + await client.sendMessage(message.chatId, { + message: `Ошибка загрузки модуля ${moduleName}. Проверьте, что файл ${moduleName}.js существует в папке modules/`, + }) + } + return + } + + const command = commands.get(commandName) + if (!command) return + + await command.execute(client, message, args, { startTime }) + } catch (error) { + console.log("Ошибка обработки сообщения:", error) + } +}, new NewMessage({})) + +async function start() { + console.log("Запуск Telegram UserBot...") + + try { + await client.start({ + phoneNumber: async () => phoneNumber, + password: async () => { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }) + return new Promise((resolve) => { + rl.question("Введите пароль двухфакторной аутентификации: ", (answer) => { + rl.close() + resolve(answer) + }) + }) + }, + phoneCode: async () => { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }) + return new Promise((resolve) => { + rl.question("Введите код из Telegram: ", (answer) => { + rl.close() + resolve(answer) + }) + }) + }, + onError: (err) => console.log("Ошибка авторизации:", err), + }) + + const session = client.session.save() + fs.writeFileSync(sessionFile, session) + console.log("Сессия сохранена") + + await loadCommands() + + console.log("UserBot запущен и готов к работе!") + console.log("Доступные команды:") + commands.forEach((command, name) => { + console.log(`!${name} - ${command.description || "Нет описания"}`) + }) + console.log("Отправьте !help в любой чат для получения справки") + } catch (error) { + console.log("Ошибка запуска:", error) + } +} + +start()