Spaces:
Configuration error
Configuration error
Download src/bot/bot.js from UUUZCX/video-optimizer-bot: direct link, hf CLI and curl.
- Browser
- Download file 4.03 kB
-
https://huggingface.co/spaces/UUUZCX/video-optimizer-bot/resolve/main/src/bot/bot.js
- Command line
-
hf download hf://spaces/UUUZCX/video-optimizer-bot/src/bot/bot.js
-
curl -L -o bot.js https://huggingface.co/spaces/UUUZCX/video-optimizer-bot/resolve/main/src/bot/bot.js
4.03 kB
| const { Bot } = require("grammy"); | |
| const { config } = require("../config/env"); | |
| const { getDb } = require("../config/db"); | |
| const { getMessages } = require("./messages"); | |
| const { registerCommands } = require("./commands"); | |
| const { registerHandlers } = require("./handlers"); | |
| const { updateJob, getJob } = require("../queue/jobs"); | |
| const { createLogger } = require("../monitoring/logger"); | |
| const logger = createLogger("BotCore"); | |
| // Database-backed user session middleware | |
| async function userSessionMiddleware(ctx, next) { | |
| if (!ctx.from) return next(); | |
| const db = getDb(); | |
| const userId = ctx.from.id; | |
| const username = ctx.from.username || null; | |
| let user = db.prepare("SELECT * FROM users WHERE id = ?").get(userId); | |
| if (!user) { | |
| try { | |
| db.prepare(` | |
| INSERT INTO users (id, username, language, mode, banned, created_at) | |
| VALUES (?, ?, ?, ?, 0, ?) | |
| `).run(userId, username, "ar", "auto", Date.now()); | |
| user = { | |
| id: userId, | |
| username, | |
| language: "ar", | |
| mode: "auto", | |
| banned: 0, | |
| rate_limit_tokens: 5.0, | |
| last_request_time: 0, | |
| requests_count: 0 | |
| }; | |
| } catch (e) { | |
| logger.error(`Failed to register user ${userId}: ${e.message}`); | |
| } | |
| } | |
| if (user && user.banned) { | |
| const isAr = user.language === "ar"; | |
| return ctx.reply(isAr ? "🔒 تم حظر حسابك من استخدام البوت!" : "🔒 Your account has been banned from using this bot."); | |
| } | |
| // Bind settings to state | |
| ctx.state = ctx.state || {}; | |
| ctx.state.user = user || { id: userId, language: "ar", mode: "auto" }; | |
| ctx.state.settings = { | |
| language: ctx.state.user.language, | |
| mode: ctx.state.user.mode | |
| }; | |
| // Bind translations helper | |
| ctx.state.messages = getMessages(ctx.state.user.language); | |
| return next(); | |
| } | |
| function createBot(queueRef) { | |
| if (!config.telegram.token) { | |
| logger.error("TELEGRAM_BOT_TOKEN is missing! Bot cannot start."); | |
| throw new Error("TELEGRAM_BOT_TOKEN is missing"); | |
| } | |
| const bot = new Bot(config.telegram.token); | |
| bot.catch((error) => { | |
| logger.error("Telegram bot error caught:", error.error); | |
| }); | |
| // Apply user sessions middleware | |
| bot.use(userSessionMiddleware); | |
| // Register commands and handlers | |
| registerCommands(bot, queueRef); | |
| registerHandlers(bot, queueRef); | |
| return bot; | |
| } | |
| function createProgressUpdater(bot) { | |
| const last = new Map(); | |
| return async function updateProgress(jobId, progress, stage, message) { | |
| const job = getJob(jobId); | |
| if (!job || !job.telegram_message_id) return; | |
| const now = Date.now(); | |
| const previous = last.get(jobId) || 0; | |
| // Throttle progress updates (max once per 2.5s) to avoid Telegram API rate limits, | |
| // except when progress is complete (100%) or starting (0%). | |
| if (now - previous < 2500 && progress > 0 && progress < 100) return; | |
| last.set(jobId, now); | |
| updateJob(jobId, { progress, stage, status: stage }); | |
| // Fetch user language settings for localized progress status | |
| const db = getDb(); | |
| const userRow = db.prepare("SELECT language FROM users WHERE id = ?").get(job.user_id); | |
| const lang = userRow ? userRow.language : "ar"; | |
| const msgs = getMessages(lang); | |
| let progressText = ""; | |
| if (stage === "downloading") { | |
| progressText = msgs.downloading + `\n🔄 [${progress}%]`; | |
| } else if (stage === "compressing") { | |
| progressText = msgs.compressing | |
| .replace("{mode}", job.mode.toUpperCase()) | |
| .replace("{progress}", String(progress)); | |
| } else if (stage === "uploading") { | |
| progressText = msgs.uploading; | |
| } else { | |
| progressText = `⚙️ *Status:* ${stage.toUpperCase()}\n📊 *Progress:* ${progress}%`; | |
| } | |
| await bot.api.editMessageText(job.chat_id, job.telegram_message_id, progressText, { | |
| parse_mode: "Markdown" | |
| }).catch((err) => { | |
| logger.debug(`Could not update progress message: ${err.message}`); | |
| }); | |
| }; | |
| } | |
| module.exports = { createBot, createProgressUpdater }; | |