-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
428 lines (380 loc) · 11.7 KB
/
Copy pathmain.js
File metadata and controls
428 lines (380 loc) · 11.7 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import "./config.js";
import fs from "fs";
import path from "path";
import chalk from "chalk";
import { Telegraf, Markup } from "telegraf";
import { fileURLToPath, pathToFileURL } from "url";
// Database (lowdb lite bundled in lib/lowdb)
import { Low, JSONFile } from "./lib/lowdb/index.js";
// Core handler and helpers
import * as Core from "./handler.js";
import attachSimpleHelpers from "./lib/simple.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// ---- Basic guards
if (!global.token || String(global.token).trim().length === 0) {
console.error("\u274c Missing bot token. Set global.token in config.js");
process.exit(1);
}
// Normalize ownerid/premid to arrays of strings
const normalizeIds = (v) =>
Array.isArray(v)
? v.map((x) => String(x))
: String(v || "")
.split(/[\s,]+/)
.map((x) => x.trim())
.filter(Boolean);
global.ownerid = normalizeIds(global.ownerid);
global.premid = normalizeIds(global.premid);
global.prefix = Array.isArray(global.prefix)
? global.prefix
: ["/", ".", "#", "!"];
global.opts = global.opts || {};
// ---- Database setup
const dbFile = path.join(__dirname, "database.json");
const adapter = new JSONFile(dbFile);
const db = new Low(adapter);
global.db = db;
const defaultDB = {
users: {},
chats: {},
stats: {},
msgs: {},
sticker: {},
};
let dbLoadedOnce = false;
let dbSaving = false;
let dbDirty = false;
async function loadDatabase() {
await db.read();
if (!db.data) db.data = JSON.parse(JSON.stringify(defaultDB));
// Fill defaults (non-destructive)
for (const k of Object.keys(defaultDB))
db.data[k] = db.data[k] || JSON.parse(JSON.stringify(defaultDB[k]));
dbLoadedOnce = true;
}
async function saveDatabase() {
if (!dbLoadedOnce) return;
if (dbSaving) {
dbDirty = true;
return;
}
dbSaving = true;
try {
await db.write();
} finally {
dbSaving = false;
if (dbDirty) {
dbDirty = false;
setImmediate(saveDatabase);
}
}
}
global.loadDatabase = loadDatabase;
// Periodic autosave
setInterval(() => saveDatabase().catch(() => {}), 15_000);
// ---- Plugins loader
const pluginsDir = path.join(__dirname, "plugins");
global.plugins = {};
// ---- Bot setup
const bot = new Telegraf(global.token);
// Use bot instance as conn so .on() is available for simple.js middleware
const conn = bot;
conn.botInfo = null;
// Attach friendly helpers to conn (adds sendMessage/sendFile/reply/etc and a message middleware)
attachSimpleHelpers(conn);
async function safeAnswerCb(ctx) {
if (!ctx?.callbackQuery) return;
if (ctx._answeredCb) return;
ctx._answeredCb = true;
try {
await ctx.answerCbQuery();
} catch {}
}
// getName helper cache enhancer (will fallback to simple.js default until cache fills)
const nameCache = new Map();
async function refreshBotInfo() {
try {
conn.botInfo = await bot.telegram.getMe();
// Enhance getName with async lookup once (cache lazily)
conn.getName = (id) => {
const key = String(id);
if (nameCache.has(key)) return nameCache.get(key);
(async () => {
try {
// getChat works for users/groups
const chat = await bot.telegram.getChat(id);
const name =
chat.first_name || chat.title || chat.username || String(id);
nameCache.set(key, name);
} catch {
nameCache.set(key, String(id));
}
})();
return key;
};
} catch (e) {
console.error("Failed to fetch bot info:", e.message);
}
}
// Build message object compatible with handler.js and plugins
async function buildMessage(ctx) {
const msg =
ctx.message ||
ctx.editedMessage ||
ctx.channelPost ||
ctx.editedChannelPost ||
{};
const chat = ctx.chat || msg.chat || {};
const from = ctx.from || msg.from || {};
const replyToMessage = msg.reply_to_message || null;
const cbData = ctx.callbackQuery?.data;
const text = msg.text || msg.caption || cbData || "";
const isGroup = chat.type === "group" || chat.type === "supergroup";
const chatId = chat.id;
const senderId = from.id;
let isBotAdmin = false;
let isAdmin = false;
if (isGroup) {
try {
const admins = await bot.telegram.getChatAdministrators(chatId);
m.participants = admins.map((a) => a.user.id);
} catch {}
}
if (isGroup && chatId && conn.botInfo?.id) {
try {
const botMember = await bot.telegram.getChatMember(chatId, conn.botInfo.id);
isBotAdmin = ["administrator", "creator"].includes(botMember.status);
} catch {}
try {
const userMember = await bot.telegram.getChatMember(chatId, senderId);
isAdmin = ["administrator", "creator"].includes(userMember.status);
} catch {}
}
// Return object m yang lengkap
return {
id: msg.message_id,
chat: chatId,
sender: senderId,
name: from.first_name || from.username || "Unknown",
text,
isCallback: Boolean(ctx.callbackQuery),
callbackData: cbData,
isGroup,
isAdmin,
isBotAdmin,
fromMe: false,
isSimulated: false,
callbackQuery: ctx.callbackQuery || null,
participants: [],
quoted: replyToMessage ? {
id: replyToMessage.message_id,
sender: replyToMessage.from?.id,
name: replyToMessage.from?.first_name || replyToMessage.from?.username || "Unknown",
text: replyToMessage.text || replyToMessage.caption || "",
msg: replyToMessage,
mimetype: replyToMessage.photo ? 'image/jpeg' :
replyToMessage.video ? 'video/mp4' :
replyToMessage.document ? replyToMessage.document.mime_type :
replyToMessage.sticker ? 'image/webp' :
replyToMessage.audio ? 'audio/mpeg' :
replyToMessage.voice ? 'audio/ogg' : null,
download: async () => {
const fileId = replyToMessage.photo?.[replyToMessage.photo.length - 1]?.file_id ||
replyToMessage.video?.file_id ||
replyToMessage.document?.file_id ||
replyToMessage.sticker?.file_id ||
replyToMessage.audio?.file_id ||
replyToMessage.voice?.file_id;
if (!fileId) throw new Error('No media found');
const fileLink = await ctx.telegram.getFileLink(fileId);
const response = await fetch(fileLink.href);
const buffer = await response.arrayBuffer();
return Buffer.from(buffer);
}
} : null,
msg: msg,
mimetype: msg.photo ? 'image/jpeg' :
msg.video ? 'video/mp4' :
msg.document ? msg.document.mime_type :
msg.sticker ? 'image/webp' :
msg.audio ? 'audio/mpeg' :
msg.voice ? 'audio/ogg' : null,
download: async () => {
const fileId = msg.photo?.[msg.photo.length - 1]?.file_id ||
msg.video?.file_id ||
msg.document?.file_id ||
msg.sticker?.file_id ||
msg.audio?.file_id ||
msg.voice?.file_id;
if (!fileId) throw new Error('No media found');
const fileLink = await ctx.telegram.getFileLink(fileId);
const response = await fetch(fileLink.href);
const buffer = await response.arrayBuffer();
return Buffer.from(buffer);
},
fakeObj: ctx.update,
reply: (txt, quoted) =>
conn.sendMessage(
chatId,
{ text: txt },
{ quoted: quoted || { message_id: msg.message_id } },
),
};
}
// participants (admins list as best-effort)
// Participant updates (join/leave, bot status)
bot.on("my_chat_member", async (ctx) => {
try {
await Core.participantsUpdate.call(conn, ctx);
} catch (e) {
console.error(e);
}
});
bot.on("chat_member", async (ctx) => {
try {
await Core.participantsUpdate.call(conn, ctx);
} catch (e) {
console.error(e);
}
});
// ================= LOAD PLUGINS =================
async function loadPlugins() {
const list = fs.readdirSync(pluginsDir).filter((f) => f.endsWith(".js"));
const newMap = {};
for (const file of list) {
try {
const full = path.join(pluginsDir, file);
const fileUrl = pathToFileURL(full).href + `?v=${Date.now()}`;
const mod = await import(fileUrl);
newMap[file] = mod.default || mod;
} catch (e) {
console.error(`Failed loading plugin ${file}:`, e.message);
}
}
global.plugins = newMap;
console.log(
chalk.green(`✅ Loaded ${Object.keys(global.plugins).length} plugins`),
);
}
// ================= BUILD MENU MAP =================
function buildMenuMap() {
const map = {};
for (const plugin of Object.values(global.plugins || {})) {
if (!plugin.tags || !plugin.help) continue;
plugin.tags.forEach((tag) => {
if (!map[tag]) map[tag] = [];
plugin.help.forEach((cmd) => {
if (!map[tag].includes(cmd)) {
map[tag].push(cmd);
}
});
});
}
return map;
}
// CALLBACK MENU CATEGORY
bot.action(/menu:(.+)/, async (ctx) => {
const key = ctx.match[1];
const menuMap = buildMenuMap();
// BACK
if (key === "back") {
return ctx.editMessageCaption(` 📜 *SUB MENU*`, {
parse_mode: "Markdown",
...Markup.inlineKeyboard(
chunk(
Object.keys(menuMap).map((cat) =>
Markup.button.callback(`📂 ${cat.toUpperCase()}`, `menu:${cat}`),
),
2,
),
),
});
}
const list = menuMap[key];
if (!list) {
return ctx.answerCbQuery("Menu tidak ditemukan");
}
let text = `╭─『 *MENU ${key.toUpperCase()}* 』\n`;
list.forEach((cmd) => {
text += `│ • /${cmd}\n`;
});
text += `╰──────────────࿐`;
await ctx.answerCbQuery();
return ctx.editMessageCaption(text, {
parse_mode: "Markdown",
...Markup.inlineKeyboard([
[Markup.button.callback("⬅ Back", "menu:back")],
]),
});
});
// ================= MESSAGE FALLBACK =================
bot.on("message", async (ctx) => {
try {
await loadDatabase();
const m = await buildMessage(ctx);
await Core.handler.call(conn, m);
saveDatabase().catch(() => {});
} catch (e) {
console.error("Message error:", e);
}
});
// ================= CALLBACK FALLBACK =================
bot.on("callback_query", async (ctx, next) => {
const data = ctx.callbackQuery?.data;
// BIAR MENU DITANGANI bot.action
if (data && data.startsWith("menu:")) {
return next();
}
try {
await safeAnswerCb(ctx);
await loadDatabase();
const m = await buildMessage(ctx);
await Core.handler.call(conn, m);
saveDatabase().catch(() => {});
} catch (e) {
console.error("Callback error:", e);
}
});
// ================= BOOT =================
(async () => {
try {
await loadPlugins();
// hot reload
fs.watch(pluginsDir, { persistent: false }, async (_, file) => {
if (file?.endsWith(".js")) {
try {
await loadPlugins();
} catch {}
}
});
await bot.launch();
console.log(chalk.cyan("🤖 Bot is running"));
} catch (e) {
console.error("❌ Failed to launch bot:", e);
process.exit(1);
}
})();
process.once("SIGINT", () => bot.stop("SIGINT"));
process.once("SIGTERM", () => bot.stop("SIGTERM"));
// ================= UTIL =================
function chunk(arr, size) {
const res = [];
for (let i = 0; i < arr.length; i += size) {
res.push(arr.slice(i, i + size));
}
return res;
}
// Hot-reload support
fs.watchFile(__filename, () => {
fs.unwatchFile(__filename);
console.log(chalk.redBright("Update main.js"));
});
// Parent IPC helpers
process.on("message", (msg) => {
if (msg === "uptime") {
try {
process.send && process.send(process.uptime());
} catch {}
}
});