-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
589 lines (515 loc) · 22.2 KB
/
Copy pathbot.js
File metadata and controls
589 lines (515 loc) · 22.2 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
// ════════════════════════════════════════════════════════════════════
// 🤖 VibeBot — Main Bot Entry Point (AI-Powered Edition)
// ════════════════════════════════════════════════════════════════════
// Start the bot: node bot.js
// ════════════════════════════════════════════════════════════════════
require("dotenv").config();
const {
Client,
GatewayIntentBits,
EmbedBuilder,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
PermissionFlagsBits,
ActivityType,
} = require("discord.js");
const config = require("./config");
const nodemailer = require("nodemailer");
const { GoogleGenAI } = require("@google/genai");
// ── Gemini AI Setup ────────────────────────────────
let ai = null;
if (process.env.GEMINI_API_KEY) {
ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
console.log("🧠 Gemini AI: ENABLED");
} else {
console.log("🧠 Gemini AI: DISABLED (set GEMINI_API_KEY in .env)");
}
// ── Email Transporter Setup ────────────────────────
let emailTransporter = null;
if (process.env.EMAIL_USER && process.env.EMAIL_PASS && process.env.EMAIL_USER !== "your.email@gmail.com") {
emailTransporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
console.log("📧 Email notifications: ENABLED");
} else {
console.log("📧 Email notifications: DISABLED (configure EMAIL_USER & EMAIL_PASS in .env)");
}
// ── Per-Server Email Recipients ────────────────────
const serverEmailMap = {
// FourFold Research
"1431530303872307212": [
"md.zarif.latif@g.bracu.ac.bd",
"sidratul.muntaha1@g.bracu.ac.bd",
"puja.banik@g.bracu.ac.bd",
"kazi.tasfin.mahmud@g.bracu.ac.bd",
],
// Second Brain
"1427249292392792126": [
"rafintasfin1@gmail.com",
"kazi.tasfin.mahmud@g.bracu.ac.bd",
"tasfinmahmud1@gmail.com",
],
// Alpha & Beta
"1463548222109913203": [],
};
// ── Helper: Send Email to Recipients ───────────────
async function sendEmailNotification({ category, title, message, serverName, channelName, guildId }) {
if (!emailTransporter) return false;
const recipients = serverEmailMap[guildId] || [];
if (recipients.length === 0) return false;
const categoryColors = {
announcement: "#7c3aed",
insight: "#f59e0b",
info: "#3b82f6",
reminder: "#ef4444",
};
const categoryEmojis = {
announcement: "\ud83d\udce2",
insight: "\ud83d\udca1",
info: "\u2139\ufe0f",
reminder: "\ud83d\udd14",
};
const color = categoryColors[category] || "#7c3aed";
const emoji = categoryEmojis[category] || "\ud83d\udce2";
const catLabel = category.charAt(0).toUpperCase() + category.slice(1);
const htmlEmail = `
<div style="font-family: 'Segoe UI', Arial, sans-serif; max-width: 600px; margin: 0 auto; background: #1a1a2e; border-radius: 12px; overflow: hidden;">
<div style="background: ${color}; padding: 20px 24px;">
<h1 style="color: white; margin: 0; font-size: 22px;">${emoji} ${title}</h1>
<p style="color: rgba(255,255,255,0.8); margin: 4px 0 0; font-size: 13px;">From ${serverName} • #${channelName}</p>
</div>
<div style="padding: 24px; color: #e2e8f0;">
<p style="font-size: 15px; line-height: 1.6; white-space: pre-wrap;">${message}</p>
</div>
<div style="padding: 16px 24px; background: #16213e; text-align: center;">
<p style="color: #64748b; font-size: 12px; margin: 0;">Sent by ${config.botName} 🤖 • ${catLabel} Notification</p>
</div>
</div>
`;
try {
await emailTransporter.sendMail({
from: `"${config.botName} 🤖" <${process.env.EMAIL_USER}>`,
to: recipients.join(", "),
subject: `${emoji} [${serverName}] ${catLabel}: ${title}`,
html: htmlEmail,
});
console.log(`📧 Email sent to ${recipients.length} recipient(s) for ${serverName}`);
return true;
} catch (error) {
console.error("📧 Email error:", error.message);
return false;
}
}
// ── Create Client ──────────────────────────────────
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
ws: {
large_threshold: 50,
},
rest: {
timeout: 60000,
},
});
// ── Helper: Random Pick ────────────────────────────
const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
// ── Helper: Create Styled Embed ────────────────────
function makeEmbed({ title, description, color, fields, footer, image, thumbnail }) {
const embed = new EmbedBuilder()
.setColor(color || config.botColor)
.setTimestamp();
if (title) embed.setTitle(title);
if (description) embed.setDescription(description);
if (fields) embed.addFields(fields);
if (image) embed.setImage(image);
if (thumbnail) embed.setThumbnail(thumbnail);
if (footer) embed.setFooter({ text: footer });
else embed.setFooter({ text: `${config.botName} ✨ | FourFold Research` });
return embed;
}
// ── Helper: Generate AI Reply ──────────────────────
let lastAICallTime = 0;
const AI_COOLDOWN_MS = 1000; // 1 second cooldown (Google AI Pro = higher rate limits)
async function generateAIReply(username, messageContent, hasAttachments) {
if (!ai) return null;
// Rate limit: wait at least 1 second between API calls
const now = Date.now();
if (now - lastAICallTime < AI_COOLDOWN_MS) {
return null; // Skip if too fast, fallback message will be used
}
lastAICallTime = now;
try {
let prompt = `${config.aiSystemPrompt}
Discord display name: ${username}
Message: "${messageContent}"
${hasAttachments ? "তারা একটি ফাইল/ছবি/ডকুমেন্ট আপলোড করেছেন।" : ""}
Reply in Bengali. Start with "মাননীয় সদস্য, ${username}," then 1-2 sentences.`;
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: prompt,
});
return response.text || null;
} catch (error) {
console.error("🧠 Gemini AI error:", error.message?.substring(0, 100) || error.message);
return null;
}
}
// ════════════════════════════════════════════════════
// 📡 EVENT: Ready
// ════════════════════════════════════════════════════
client.once("ready", () => {
console.log("=== BOT READY ===");
console.log("Bot: " + config.botName + " is ONLINE (appearing offline)");
console.log("Tag: " + client.user.tag);
console.log("Servers: " + client.guilds.cache.size);
console.log("=================");
// Set bot to invisible (appears offline to everyone)
client.user.setPresence({
status: "invisible",
activities: [],
});
});
// ── Error Handlers ────────────────────────────────
client.on("error", (err) => console.error("Client error:", err.message));
client.on("warn", (msg) => console.warn("Client warn:", msg));
client.on("disconnect", () => console.log("Bot disconnected! Reconnecting..."));
client.on("reconnecting", () => console.log("Bot reconnecting..."));
// ════════════════════════════════════════════════════
// 👋 EVENT: Member Join (Welcome)
// ════════════════════════════════════════════════════
client.on("guildMemberAdd", async (member) => {
// Find a general/welcome channel
const channel =
member.guild.systemChannel ||
member.guild.channels.cache.find(
(ch) =>
ch.name.includes("general") ||
ch.name.includes("welcome") ||
ch.name.includes("chat")
);
if (!channel) return;
const welcomeMsg = pick(config.welcomeMessages).replace(
"{user}",
`<@${member.id}>`
);
const embed = makeEmbed({
title: "🎉 New Member Alert!",
description: welcomeMsg,
color: config.accentColors.success,
thumbnail: member.user.displayAvatarURL({ dynamic: true, size: 256 }),
fields: [
{
name: "📊 Member Count",
value: `You're member #${member.guild.memberCount}!`,
inline: true,
},
{
name: "📅 Account Created",
value: `<t:${Math.floor(member.user.createdTimestamp / 1000)}:R>`,
inline: true,
},
],
footer: "Welcome aboard! 🚀",
});
channel.send({ embeds: [embed] });
});
// ════════════════════════════════════════════════════
// 💬 EVENT: Message (AI-Powered FourFold Research Bot)
// ════════════════════════════════════════════════════
client.on("messageCreate", async (message) => {
if (message.author.bot) return;
const isAIServer = message.guild && config.aiEnabledServers.includes(message.guild.id);
// ═══════════════════════════════════════════════
// 🏛️ AI-ENABLED SERVERS — Bengali Reply Behavior
// ═══════════════════════════════════════════════
if (isAIServer) {
// Skip channels under ignored categories (FourFold Research: Stuff-Thesis & Specialization)
const channelCategory = message.channel.parentId;
if (channelCategory && config.ignoredCategories.includes(channelCategory)) {
return; // Do nothing in these categories
}
const username = message.member?.displayName || message.author.displayName || message.author.username;
// ── 1. File Upload → Thank in Bengali + ❤️ React ──
if (message.attachments.size > 0) {
try {
await message.react("❤️");
} catch (e) { /* ignore */ }
// Generate AI thank-you reply for file uploads
const aiReply = await generateAIReply(username, message.content || "(uploaded a file)", true);
if (aiReply) {
await message.reply(aiReply);
} else {
await message.reply(`মাননীয় সদস্য, ${username}, আপনাকে অসংখ্য ধন্যবাদ! আপনার এই অবদান আমাদের জন্য অত্যন্ত মূল্যবান। 🙏📄`);
}
return;
}
// ── 2. @Mention → Bengali Notification ──
const mentionedUsers = message.mentions.users.filter((u) => u.id !== message.author.id && !u.bot);
if (mentionedUsers.size > 0) {
const mentionNames = mentionedUsers.map((u) => {
const member = message.guild.members.cache.get(u.id);
return member?.displayName || u.displayName || u.username;
});
const nameList = mentionNames.join(", ");
const aiReply = await generateAIReply(username, `আমি ${nameList} কে মেনশন করেছি আমার মেসেজে: "${message.content}"`, false);
if (aiReply) {
await message.reply(aiReply);
} else {
await message.reply(`মাননীয় সদস্য, ${nameList} কে জানানো হবে। ধৈর্য ধরুন, ধৈর্যই সফলতার চাবিকাঠি। ⏳🕊️`);
}
return;
}
// ── 3. All Other Messages → AI Reply ──
const content = message.content.trim();
if (content.length > 0) {
const aiReply = await generateAIReply(username, content, false);
if (aiReply) {
await message.reply(aiReply);
}
// If AI fails, stay silent rather than spamming
}
return; // Don't process FourFold messages further
}
// ═══════════════════════════════════════════════
// 🌐 OTHER SERVERS — Minimal behavior (no spam)
// ═══════════════════════════════════════════════
// Just react with a random emoji occasionally (~10%)
if (Math.random() < 0.10) {
try {
const emojis = ["👍", "✨", "💜", "🔥", "👀", "🫡"];
await message.react(pick(emojis));
} catch (e) { /* ignore */ }
}
});
// ════════════════════════════════════════════════════
// ⚡ EVENT: Slash Command Interactions
// ════════════════════════════════════════════════════
client.on("interactionCreate", async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const { commandName, options } = interaction;
try {
switch (commandName) {
// ── /announce ──────────────────────────────────
case "announce": {
// Owner only
if (interaction.user.id !== interaction.guild.ownerId) {
return interaction.reply({
content: "❌ Only the **server owner** can use this command!",
ephemeral: true,
});
}
const title = options.getString("title");
const message = options.getString("message");
const channel = options.getChannel("channel") || interaction.channel;
const color = options.getString("color");
const image = options.getString("image");
const embed = makeEmbed({
title: `📢 ${title}`,
description: message,
color: color ? parseInt(color.replace("#", ""), 16) : config.accentColors.announcement,
image: image || null,
footer: `Announced by ${interaction.user.username} 📣`,
});
await channel.send({ embeds: [embed] });
await interaction.reply({
content: `✅ Announcement posted in ${channel}!`,
ephemeral: true,
});
break;
}
// ── /schedule ──────────────────────────────────
case "schedule": {
if (interaction.user.id !== interaction.guild.ownerId) {
return interaction.reply({
content: "❌ Only the **server owner** can use this command!",
ephemeral: true,
});
}
const title = options.getString("title");
const message = options.getString("message");
const minutes = options.getInteger("minutes");
const channel = options.getChannel("channel") || interaction.channel;
await interaction.reply({
content: `⏰ Announcement **"${title}"** scheduled for **${minutes} minute(s)** from now in ${channel}!`,
ephemeral: true,
});
setTimeout(async () => {
const embed = makeEmbed({
title: `📢 ${title}`,
description: message,
color: config.accentColors.announcement,
footer: `Scheduled announcement by ${interaction.user.username} 📣`,
});
await channel.send({ embeds: [embed] });
}, minutes * 60 * 1000);
break;
}
// ── /post (Proxy Message) ───────────────────────
case "post": {
if (interaction.user.id !== interaction.guild.ownerId) {
return interaction.reply({
content: "❌ Only the **server owner** can use this command!",
ephemeral: true,
});
}
const category = options.getString("category");
const message = options.getString("message");
const title = options.getString("title");
const channel = options.getChannel("channel") || interaction.channel;
const pingEveryone = options.getBoolean("ping_everyone") || false;
// Category styles
const categoryStyles = {
announcement: {
emoji: "📢",
label: "Announcement",
color: config.accentColors.announcement,
},
insight: {
emoji: "💡",
label: "Insight",
color: 0xf59e0b,
},
info: {
emoji: "ℹ️",
label: "Info",
color: config.accentColors.info,
},
reminder: {
emoji: "🔔",
label: "Reminder",
color: 0xef4444,
},
};
const style = categoryStyles[category];
const embedTitle = title
? `${style.emoji} ${title}`
: `${style.emoji} ${style.label}`;
const embed = makeEmbed({
title: embedTitle,
description: message,
color: style.color,
footer: `${style.label} • via ${config.botName}`,
});
const sendPayload = { embeds: [embed] };
if (pingEveryone) {
sendPayload.content = "@everyone";
}
await channel.send(sendPayload);
// Reply FIRST (Discord has a 3-second timeout)
await interaction.reply({
content: `✅ **${style.label}** posted in ${channel}! ✉️ Sending emails...`,
ephemeral: true,
});
// Send email in background (don't block the reply)
sendEmailNotification({
category,
title: title || style.label,
message,
serverName: interaction.guild.name,
channelName: channel.name,
guildId: interaction.guild.id,
});
break;
}
// ── /remind (Deadline Reminder) ─────────────────
case "remind": {
if (interaction.user.id !== interaction.guild.ownerId) {
return interaction.reply({
content: "❌ Only the **server owner** can use this command!",
ephemeral: true,
});
}
const title = options.getString("title");
const message = options.getString("message");
const minutes = options.getInteger("minutes");
const channel = options.getChannel("channel") || interaction.channel;
const fireTime = new Date(Date.now() + minutes * 60 * 1000);
const fireTimestamp = Math.floor(fireTime.getTime() / 1000);
await interaction.reply({
content: `✅ Reminder **"${title}"** scheduled!\n⏰ Fires: <t:${fireTimestamp}:R> in ${channel}\n👥 Will ping @everyone`,
ephemeral: true,
});
setTimeout(async () => {
const embed = makeEmbed({
title: `🚨 REMINDER: ${title}`,
description:
`${message}\n\n` +
`⏰ **This is your scheduled reminder!**\n` +
`📅 Deadline alert — please take action now!`,
color: 0xef4444,
footer: `Reminder set by ${interaction.user.username} ⏰`,
});
await channel.send({
content: "@everyone 🔔 **DEADLINE REMINDER**",
embeds: [embed],
});
}, minutes * 60 * 1000);
break;
}
// ── /ping ──────────────────────────────────
case "ping": {
const sent = await interaction.reply({ content: '🏓 Pinging...', fetchReply: true });
const latency = sent.createdTimestamp - interaction.createdTimestamp;
await interaction.editReply(`🏓 Pong! Latency: \`${latency}ms\` | API: \`${Math.round(client.ws.ping)}ms\``);
break;
}
default:
await interaction.reply({
content: "Unknown command! 🤔",
ephemeral: true,
});
}
} catch (error) {
console.error(`❌ Error handling /${commandName}:`, error);
const reply = {
content: "⚠️ Something went wrong! Please try again.",
ephemeral: true,
};
if (interaction.replied || interaction.deferred) {
await interaction.followUp(reply);
} else {
await interaction.reply(reply);
}
}
});
// ── Health Check Server (for Render/Cloud hosting) ──
// IMPORTANT: Start this FIRST so Render marks service as "live" before Discord login
const http = require("http");
const PORT = process.env.PORT || 10000;
http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("VibeBot is alive!");
}).listen(PORT, () => {
console.log(`Health check server running on port ${PORT}`);
// ── Login to Discord AFTER port is bound ──
const token = process.env.DISCORD_TOKEN;
if (!token) {
console.error("FATAL: DISCORD_TOKEN is not set!");
return;
}
console.log(`Token length: ${token.length} chars, starts with: ${token.substring(0, 10)}...`);
console.log("Attempting Discord login...");
// Add a timeout — if login takes >30s, something is wrong
const loginTimeout = setTimeout(() => {
console.error("WARNING: Discord login is taking >30 seconds. WebSocket may be blocked.");
console.error("Token first 20 chars:", token.substring(0, 20));
}, 30000);
client.login(token)
.then(() => {
clearTimeout(loginTimeout);
console.log("Discord login successful!");
})
.catch((err) => {
clearTimeout(loginTimeout);
console.error("Discord login FAILED:", err.message);
});
});