185 lines
5.6 KiB
JavaScript
185 lines
5.6 KiB
JavaScript
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()
|