Spaces:
Configuration error
Configuration error
File size: 4,034 Bytes
03b405b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | 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 };
|