darkvibe314 commited on
Commit
854a069
·
verified ·
1 Parent(s): 6eee21d

Update bot.js

Browse files
Files changed (1) hide show
  1. bot.js +124 -163
bot.js CHANGED
@@ -1,27 +1,16 @@
1
  // ============================================================
2
- // 🌐 NETWORK FIX FOR HUGGING FACE (Force IPv4)
3
- // ============================================================
4
- const dns = require('dns');
5
- dns.setDefaultResultOrder('ipv4first');
6
-
7
- // ============================================================
8
- // 🪄 HUGGING FACE KEEP-ALIVE TRICK
9
- // ============================================================
10
-
11
-
12
- // ... (the rest of your code stays exactly the same)
13
- // ============================================================
14
- // 🪄 HUGGING FACE KEEP-ALIVE TRICK
15
  // ============================================================
16
  const http = require('http');
17
  const server = http.createServer((req, res) => {
18
  res.writeHead(200, { 'Content-Type': 'text/plain' });
19
  res.end('Lecture Downloader Bot is alive and running on Hugging Face!');
20
  });
21
- server.listen(7860, () => console.log('🌐 Web server running on port 7860 (Hugging Face Requirement)'));
 
22
 
23
  // ============================================================
24
- // 🤖 BOT CODE
25
  // ============================================================
26
  const TelegramBot = require('node-telegram-bot-api');
27
  const axios = require('axios');
@@ -33,26 +22,11 @@ const FormData = require('form-data');
33
  // ============================================================
34
  // ⚙️ CONFIGURATION
35
  // ============================================================
36
- const TOKEN = '8548617432:AAHAe65kcsDv30c0YnG4nZasQT5dasBw9aU';
37
  const OWNER_USERNAME = 'silent000666';
38
-
39
- // Banner Image
40
  const BANNER_URL = 'https://img.freepik.com/free-vector/laptop-with-program-code-isometric-icon-software-development-programming-applications-dark-neon_39422-971.jpg';
41
-
42
- // Initialize
43
- // Initialize with strict IPv4 Network enforcement
44
- const bot = new TelegramBot(TOKEN, {
45
- polling: true,
46
- request: {
47
- agentOptions: {
48
- family: 4 // Strictly forces IPv4 at the socket level
49
- }
50
- }
51
- });
52
  const userState = {};
53
 
54
- console.log('🚀 GOFILE BOT STARTED...');
55
-
56
  // ============================================================
57
  // 📝 LOGGER
58
  // ============================================================
@@ -66,171 +40,158 @@ function log(message) {
66
  }
67
 
68
  // ============================================================
69
- // 🎮 HANDLERS
70
  // ============================================================
71
- bot.onText(/\/start/, async (msg) => {
72
- userState[msg.chat.id] = null;
73
- await bot.sendPhoto(msg.chat.id, BANNER_URL, {
74
- caption: `👋 *Welcome, ${msg.from.first_name}*\n\nI am your **Lecture Downloader**.\n\n🔹 **Modes:**\n• < 50MB: Direct Telegram File\n• > 50MB: High-Speed Gofile Link\n\n_Click below to start:_`,
75
- parse_mode: 'Markdown',
76
- reply_markup: {
77
- inline_keyboard: [
78
- [{ text: "🚀 Start Extraction", callback_data: "btn_extract" }]
79
- ]
80
- }
81
- });
82
- });
83
 
84
- bot.on('callback_query', async (q) => {
85
- const chatId = q.message.chat.id;
86
- bot.answerCallbackQuery(q.id);
87
-
88
- if (q.data === 'btn_extract') {
89
- userState[chatId] = 'WAITING_URL';
90
- await bot.sendMessage(chatId, "🔗 *Send the Lecture Link now.*", {
91
- reply_markup: { inline_keyboard: [[{ text: "❌ Cancel", callback_data: "btn_cancel" }]] }
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  });
93
- }
94
- else if (q.data === 'btn_cancel') {
95
- userState[chatId] = null;
96
- bot.deleteMessage(chatId, q.message.message_id);
97
- }
98
- });
99
-
100
- bot.on('message', async (msg) => {
101
- const chatId = msg.chat.id;
102
- const text = msg.text;
103
 
104
- if (!text || text.startsWith('/') || userState[chatId] !== 'WAITING_URL') return;
 
 
105
 
106
- userState[chatId] = null;
107
- if (!text.startsWith('http')) return bot.sendMessage(chatId, "⚠️ Invalid Link.");
 
 
 
 
 
 
 
 
 
108
 
109
- // RESET LOG
110
- fs.writeFileSync(LOG_FILE, `--- NEW PROCESS STARTED ---\n`);
111
- log(`User sent link: ${text}`);
112
 
113
- const processMsg = await bot.sendMessage(chatId, "🕵️‍♂️ *Starting Process...*\n_Analyzing..._", { parse_mode: 'Markdown' });
114
 
115
- try {
116
- // --- STEP 1: ANALYZE URL ---
117
- log("STEP 1: Analyzing URL...");
118
- let streamUrl = text;
119
- let cookieString = "";
120
- let userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)';
121
 
122
- try {
123
- const res = await axios.get(text, { headers: { 'User-Agent': userAgent }, timeout: 15000 });
124
-
125
- if (res.headers['set-cookie']) {
126
- cookieString = res.headers['set-cookie'].map(c => c.split(';')[0]).join('; ');
127
- }
128
 
129
- // Regex Check
130
- const match = res.data.match(/src:\s*'(\/Stream\/Index\/[^']+)'/);
131
- if (match) {
132
- streamUrl = `https://vss-v2-app.techsol360.com${match[1]}`;
133
- log(`✅ Found HIDDEN Stream URL`);
134
- }
135
- } catch (e) {
136
- log(`⚠️ Scrape Error: ${e.message} (Using original link)`);
137
- }
138
 
139
- // --- STEP 2: DOWNLOAD ---
140
- log("STEP 2: Starting FFmpeg Download...");
141
- await bot.editMessageText(`⬇️ *Downloading...*\n_Please wait..._`, { chat_id: chatId, message_id: processMsg.message_id, parse_mode: 'Markdown' });
142
-
143
- const timestamp = Date.now();
144
- const filePath = path.join(__dirname, `Lecture_${timestamp}.mp4`);
145
-
146
- const cmd = `ffmpeg -user_agent "${userAgent}" -headers "Cookie: ${cookieString}" -i "${streamUrl}" -c copy -bsf:a aac_adtstoasc "${filePath}" -y`;
147
-
148
- exec(cmd, { maxBuffer: 1024 * 1024 * 50 }, async (err, stdout, stderr) => {
149
- if (err) {
150
- log(`❌ FFmpeg Error: ${err.message}`);
151
- await sendErrorLog(chatId, processMsg.message_id);
152
- return;
 
 
 
 
153
  }
154
 
155
- if (!fs.existsSync(filePath)) {
156
- log("❌ File missing after download.");
157
- await sendErrorLog(chatId, processMsg.message_id);
158
- return;
159
- }
160
 
161
- const stats = fs.statSync(filePath);
162
- const sizeMB = stats.size / (1024 * 1024);
163
- log(`✅ Download Success. Size: ${sizeMB.toFixed(2)} MB`);
164
-
165
- // --- STEP 3: UPLOAD ---
166
- if (sizeMB < 49) {
167
- log("STEP 3: Uploading to Telegram (Small File)...");
168
- await bot.editMessageText(`📤 *Uploading to Telegram...*`, { chat_id: chatId, message_id: processMsg.message_id, parse_mode: 'Markdown' });
169
-
170
- try {
171
- await bot.sendDocument(chatId, filePath, { caption: `📦 ${sizeMB.toFixed(2)} MB` });
172
- log("Telegram Upload Success.");
173
- } catch (tgErr) {
174
- log(`Telegram Error: ${tgErr.message}`);
175
  }
176
- } else {
177
- log("STEP 3: Uploading to Gofile (Large File)...");
178
- await bot.editMessageText(`🚀 *Uploading to Gofile Cloud...*`, { chat_id: chatId, message_id: processMsg.message_id, parse_mode: 'Markdown' });
179
-
180
- try {
181
- const link = await uploadToGofile(filePath);
182
- log(`✅ Gofile Success: ${link}`);
183
-
184
- await bot.sendMessage(chatId, `✅ *Done!*\n\n🔗 [Download Link](${link})\n📦 Size: ${sizeMB.toFixed(2)} MB`, { parse_mode: 'Markdown', disable_web_page_preview: true });
185
- } catch (cloudErr) {
186
- log(`❌ Gofile Failed: ${cloudErr.message}`);
187
- await sendErrorLog(chatId, processMsg.message_id);
188
  }
189
- }
190
 
191
- // Cleanup
192
- if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
193
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
- } catch (error) {
196
- log(`❌ CRITICAL: ${error.message}`);
197
- await sendErrorLog(chatId, processMsg.message_id);
198
- }
199
- });
200
 
201
  // ============================================================
202
  // 📤 GOFILE UPLOAD
203
  // ============================================================
204
  async function uploadToGofile(filePath) {
205
  log("Initiating Gofile Upload...");
206
-
207
  const form = new FormData();
208
  form.append('file', fs.createReadStream(filePath));
209
-
210
  const res = await axios.post('https://upload.gofile.io/uploadfile', form, {
211
- headers: {
212
- ...form.getHeaders(),
213
- 'User-Agent': 'Mozilla/5.0'
214
- },
215
- maxContentLength: Infinity,
216
- maxBodyLength: Infinity
217
  });
218
-
219
- if (res.data.status === 'ok') {
220
- return res.data.data.downloadPage;
221
- } else {
222
- throw new Error(`Gofile API Status: ${res.data.status}`);
223
- }
224
  }
225
 
226
  // ============================================================
227
  // 🚨 ERROR REPORTER
228
  // ============================================================
229
- async function sendErrorLog(chatId, msgId) {
230
- await bot.editMessageText("❌ *Process Failed.* Sending logs...", { chat_id: chatId, message_id: msgId, parse_mode: 'Markdown' });
231
  try {
232
- await bot.sendDocument(chatId, LOG_FILE, {
233
- caption: "📜 *Error Log*\nOpen this file to see details."
234
- });
235
  } catch (e) { console.error(e); }
236
  }
 
1
  // ============================================================
2
+ // 🪄 HUGGING FACE KEEP-ALIVE TRICK (Explicit 0.0.0.0 bind)
 
 
 
 
 
 
 
 
 
 
 
 
3
  // ============================================================
4
  const http = require('http');
5
  const server = http.createServer((req, res) => {
6
  res.writeHead(200, { 'Content-Type': 'text/plain' });
7
  res.end('Lecture Downloader Bot is alive and running on Hugging Face!');
8
  });
9
+ // Explicitly binding to 0.0.0.0 is critical for Hugging Face network routing
10
+ server.listen(7860, '0.0.0.0', () => console.log('🌐 Web server running on 0.0.0.0:7860'));
11
 
12
  // ============================================================
13
+ // 🤖 BOT LIBRARIES
14
  // ============================================================
15
  const TelegramBot = require('node-telegram-bot-api');
16
  const axios = require('axios');
 
22
  // ============================================================
23
  // ⚙️ CONFIGURATION
24
  // ============================================================
25
+ const TOKEN = '8476068831:AAG9mEiMYhlIOEBYSy2P11V88NePwrJh06w';
26
  const OWNER_USERNAME = 'silent000666';
 
 
27
  const BANNER_URL = 'https://img.freepik.com/free-vector/laptop-with-program-code-isometric-icon-software-development-programming-applications-dark-neon_39422-971.jpg';
 
 
 
 
 
 
 
 
 
 
 
28
  const userState = {};
29
 
 
 
30
  // ============================================================
31
  // 📝 LOGGER
32
  // ============================================================
 
40
  }
41
 
42
  // ============================================================
43
+ // 🚀 DELAYED BOOT SEQUENCE (The Network Fix)
44
  // ============================================================
45
+ console.log("⏳ Waiting 5 seconds for Hugging Face DNS to stabilize...");
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ setTimeout(() => {
48
+ console.log("🚀 Network Ready! Booting Telegram Bot...");
49
+
50
+ const bot = new TelegramBot(TOKEN, { polling: true });
51
+
52
+ // Stop errors from crashing the bot
53
+ bot.on("polling_error", (err) => log(`[Polling Error] ${err.message}`));
54
+
55
+ // ============================================================
56
+ // 🎮 HANDLERS
57
+ // ============================================================
58
+ bot.onText(/\/start/, async (msg) => {
59
+ userState[msg.chat.id] = null;
60
+ await bot.sendPhoto(msg.chat.id, BANNER_URL, {
61
+ caption: `👋 *Welcome, ${msg.from.first_name}*\n\nI am your **Lecture Downloader**.\n\n🔹 **Modes:**\n• < 50MB: Direct Telegram File\n• > 50MB: High-Speed Gofile Link\n\n_Click below to start:_`,
62
+ parse_mode: 'Markdown',
63
+ reply_markup: {
64
+ inline_keyboard: [
65
+ [{ text: "🚀 Start Extraction", callback_data: "btn_extract" }]
66
+ ]
67
+ }
68
  });
69
+ });
 
 
 
 
 
 
 
 
 
70
 
71
+ bot.on('callback_query', async (q) => {
72
+ const chatId = q.message.chat.id;
73
+ bot.answerCallbackQuery(q.id);
74
 
75
+ if (q.data === 'btn_extract') {
76
+ userState[chatId] = 'WAITING_URL';
77
+ await bot.sendMessage(chatId, "🔗 *Send the Lecture Link now.*", {
78
+ reply_markup: { inline_keyboard: [[{ text: "❌ Cancel", callback_data: "btn_cancel" }]] }
79
+ });
80
+ }
81
+ else if (q.data === 'btn_cancel') {
82
+ userState[chatId] = null;
83
+ bot.deleteMessage(chatId, q.message.message_id);
84
+ }
85
+ });
86
 
87
+ bot.on('message', async (msg) => {
88
+ const chatId = msg.chat.id;
89
+ const text = msg.text;
90
 
91
+ if (!text || text.startsWith('/') || userState[chatId] !== 'WAITING_URL') return;
92
 
93
+ userState[chatId] = null;
94
+ if (!text.startsWith('http')) return bot.sendMessage(chatId, "⚠️ Invalid Link.");
 
 
 
 
95
 
96
+ fs.writeFileSync(LOG_FILE, `--- NEW PROCESS STARTED ---\n`);
97
+ log(`User sent link: ${text}`);
 
 
 
 
98
 
99
+ const processMsg = await bot.sendMessage(chatId, "🕵️‍♂️ *Starting Process...*\n_Analyzing..._", { parse_mode: 'Markdown' });
 
 
 
 
 
 
 
 
100
 
101
+ try {
102
+ log("STEP 1: Analyzing URL...");
103
+ let streamUrl = text;
104
+ let cookieString = "";
105
+ let userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)';
106
+
107
+ try {
108
+ const res = await axios.get(text, { headers: { 'User-Agent': userAgent }, timeout: 15000 });
109
+ if (res.headers['set-cookie']) {
110
+ cookieString = res.headers['set-cookie'].map(c => c.split(';')[0]).join('; ');
111
+ }
112
+ const match = res.data.match(/src:\s*'(\/Stream\/Index\/[^']+)'/);
113
+ if (match) {
114
+ streamUrl = `https://vss-v2-app.techsol360.com${match[1]}`;
115
+ log(`✅ Found HIDDEN Stream URL`);
116
+ }
117
+ } catch (e) {
118
+ log(`⚠️ Scrape Error: ${e.message} (Using original link)`);
119
  }
120
 
121
+ log("STEP 2: Starting FFmpeg Download...");
122
+ await bot.editMessageText(`⬇️ *Downloading...*\n_Please wait..._`, { chat_id: chatId, message_id: processMsg.message_id, parse_mode: 'Markdown' });
 
 
 
123
 
124
+ const timestamp = Date.now();
125
+ const filePath = path.join(__dirname, `Lecture_${timestamp}.mp4`);
126
+
127
+ const cmd = `ffmpeg -user_agent "${userAgent}" -headers "Cookie: ${cookieString}" -i "${streamUrl}" -c copy -bsf:a aac_adtstoasc "${filePath}" -y`;
128
+
129
+ exec(cmd, { maxBuffer: 1024 * 1024 * 50 }, async (err, stdout, stderr) => {
130
+ if (err) {
131
+ log(` FFmpeg Error: ${err.message}`);
132
+ await sendErrorLog(chatId, processMsg.message_id, bot);
133
+ return;
 
 
 
 
134
  }
135
+ if (!fs.existsSync(filePath)) {
136
+ log(" File missing after download.");
137
+ await sendErrorLog(chatId, processMsg.message_id, bot);
138
+ return;
 
 
 
 
 
 
 
 
139
  }
 
140
 
141
+ const stats = fs.statSync(filePath);
142
+ const sizeMB = stats.size / (1024 * 1024);
143
+ log(`✅ Download Success. Size: ${sizeMB.toFixed(2)} MB`);
144
+
145
+ if (sizeMB < 49) {
146
+ log("STEP 3: Uploading to Telegram...");
147
+ await bot.editMessageText(`📤 *Uploading to Telegram...*`, { chat_id: chatId, message_id: processMsg.message_id, parse_mode: 'Markdown' });
148
+ try {
149
+ await bot.sendDocument(chatId, filePath, { caption: `📦 ${sizeMB.toFixed(2)} MB` });
150
+ log("Telegram Upload Success.");
151
+ } catch (tgErr) { log(`Telegram Error: ${tgErr.message}`); }
152
+ } else {
153
+ log("STEP 3: Uploading to Gofile...");
154
+ await bot.editMessageText(`🚀 *Uploading to Gofile Cloud...*`, { chat_id: chatId, message_id: processMsg.message_id, parse_mode: 'Markdown' });
155
+ try {
156
+ const link = await uploadToGofile(filePath);
157
+ log(`✅ Gofile Success: ${link}`);
158
+ await bot.sendMessage(chatId, `✅ *Done!*\n\n🔗 [Download Link](${link})\n📦 Size: ${sizeMB.toFixed(2)} MB`, { parse_mode: 'Markdown', disable_web_page_preview: true });
159
+ } catch (cloudErr) {
160
+ log(`❌ Gofile Failed: ${cloudErr.message}`);
161
+ await sendErrorLog(chatId, processMsg.message_id, bot);
162
+ }
163
+ }
164
+ if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
165
+ });
166
+ } catch (error) {
167
+ log(`❌ CRITICAL: ${error.message}`);
168
+ await sendErrorLog(chatId, processMsg.message_id, bot);
169
+ }
170
+ });
171
 
172
+ }, 5000); // <-- This is the 5-second Magic Delay!
 
 
 
 
173
 
174
  // ============================================================
175
  // 📤 GOFILE UPLOAD
176
  // ============================================================
177
  async function uploadToGofile(filePath) {
178
  log("Initiating Gofile Upload...");
 
179
  const form = new FormData();
180
  form.append('file', fs.createReadStream(filePath));
 
181
  const res = await axios.post('https://upload.gofile.io/uploadfile', form, {
182
+ headers: { ...form.getHeaders(), 'User-Agent': 'Mozilla/5.0' },
183
+ maxContentLength: Infinity, maxBodyLength: Infinity
 
 
 
 
184
  });
185
+ if (res.data.status === 'ok') return res.data.data.downloadPage;
186
+ else throw new Error(`Gofile API Status: ${res.data.status}`);
 
 
 
 
187
  }
188
 
189
  // ============================================================
190
  // 🚨 ERROR REPORTER
191
  // ============================================================
192
+ async function sendErrorLog(chatId, msgId, botInstance) {
193
+ await botInstance.editMessageText("❌ *Process Failed.* Sending logs...", { chat_id: chatId, message_id: msgId, parse_mode: 'Markdown' });
194
  try {
195
+ await botInstance.sendDocument(chatId, LOG_FILE, { caption: "📜 *Error Log*\nOpen this file to see details." });
 
 
196
  } catch (e) { console.error(e); }
197
  }