forked from psycho237-prog/Psychobot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
272 lines (237 loc) · 10.4 KB
/
Copy pathindex.js
File metadata and controls
272 lines (237 loc) · 10.4 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
// index.js
const express = require('express');
const { default: makeWASocket, useMultiFileAuthState, DisconnectReason, fetchLatestBaileysVersion, jidDecode } = require('@whiskeysockets/baileys');
const QRCode = require("qrcode");
const pino = require("pino");
const fs = require("fs");
const path = require("path");
const db = require('./database');
const startTime = new Date();
const AUTH_FOLDER = path.join(__dirname, "auth_info");
const PREFIX = "!";
const BOT_NAME = "PSYCHO BOT";
const BOT_TAG = `*${BOT_NAME}* 👨🏻💻`;
const TARGET_NUMBER = "237696814391"; // Numéro cible
let latestQR = null; // QR actuel
// --- Loader commandes ---
const commands = new Map();
const commandFolder = path.join(__dirname, 'commands');
if (!fs.existsSync(commandFolder)) fs.mkdirSync(commandFolder);
function loadCommands() {
commands.clear();
fs.readdirSync(commandFolder).filter(f => f.endsWith('.js')).forEach(file => {
try {
const fullPath = path.join(commandFolder, file);
delete require.cache[require.resolve(fullPath)]; // évite le cache
const command = require(fullPath);
commands.set(command.name, command);
console.log(`[CommandLoader] Commande chargée : ${command.name}`);
} catch (err) {
console.error(`[CommandLoader] Erreur chargement ${file}:`, err);
}
});
}
loadCommands();
// --- Fonctions utilitaires ---
function replyWithTag(sock, jid, quoted, text) {
return sock.sendMessage(jid, { text: `${BOT_TAG}\n\n${text}` }, { quoted });
}
function getMessageText(msg) {
const m = msg.message;
if (!m) return "";
return m.conversation || m.extendedTextMessage?.text || m.imageMessage?.caption || m.videoMessage?.caption || "";
}
// --- Chargement du MP3 principal ---
let mp3Buffer = null;
try {
const mp3Path = path.join(__dirname, 'fichier.mp3');
if (fs.existsSync(mp3Path)) {
mp3Buffer = fs.readFileSync(mp3Path);
console.log('[MP3] fichier.mp3 chargé.');
} else {
console.warn('[MP3] fichier.mp3 introuvable.');
}
} catch (err) {
console.error('[MP3] Erreur lecture fichier.mp3:', err);
}
// --- Démarrage du bot ---
async function startBot() {
console.log("Démarrage du bot WhatsApp...");
const { version } = await fetchLatestBaileysVersion();
const { state, saveCreds } = await useMultiFileAuthState(AUTH_FOLDER);
const sock = makeWASocket({
version,
auth: state,
logger: pino({ level: "silent" }),
printQRInTerminal: false,
});
sock.ev.on("connection.update", update => {
const { connection, lastDisconnect, qr } = update;
if (qr) {
latestQR = qr;
console.log("[QR] Nouveau QR généré. Ouvrez http://localhost:3000/qr pour le scanner.");
}
if (connection === "close") {
if (lastDisconnect.error?.output?.statusCode !== DisconnectReason.loggedOut) startBot();
else console.log("Déconnecté, supprime auth_info pour reconnecter manuellement.");
} else if (connection === "open") {
latestQR = null;
console.log("✅ Bot connecté !");
}
});
sock.ev.on("creds.update", saveCreds);
// --- Gestion des messages ---
sock.ev.on("messages.upsert", async ({ messages, type }) => {
if (type !== "notify" || !messages[0]?.message) return;
const msg = messages[0];
const remoteJid = msg.key.remoteJid;
const senderId = msg.key.fromMe
? sock.user.id.split(':')[0] + '@s.whatsapp.net'
: (remoteJid.endsWith('@g.us') ? msg.key.participant : remoteJid);
await db.getOrRegisterUser(senderId, msg.pushName || "Unknown");
const text = getMessageText(msg);
const isGroup = remoteJid.endsWith('@g.us');
// --- Détection mention ou numéro ---
const mentioned = msg.message?.extendedTextMessage?.contextInfo?.mentionedJid?.some(jid => jid.split('@')[0] === TARGET_NUMBER);
const containsNumber = text.includes(TARGET_NUMBER);
const sendMp3 = mentioned || containsNumber;
if (isGroup && mp3Buffer && sendMp3) {
try {
await sock.sendMessage(remoteJid, { audio: mp3Buffer, mimetype: 'audio/mpeg', fileName: 'fichier.mp3' }, { quoted: msg });
console.log(`[MP3] fichier.mp3 envoyé à ${senderId}`);
} catch (err) {
console.error('[MP3] Erreur lors de l\'envoi:', err);
}
}
// --- Commande !downloadbot intégrée ---
if (text.toLowerCase() === `${PREFIX}downloadbot`) {
const mp3Files = ['fichier1.mp3', 'fichier2.mp3', 'fichier3.mp3'];
for (const file of mp3Files) {
const mp3Path = path.join(__dirname, file);
if (!fs.existsSync(mp3Path)) {
await replyWithTag(sock, remoteJid, msg, `❌ Le fichier ${file} est introuvable.`);
continue;
}
try {
const mp3BufferVoice = fs.readFileSync(mp3Path);
await sock.sendMessage(remoteJid, {
audio: mp3BufferVoice,
mimetype: 'audio/ogg; codecs=opus',
ptt: true,
fileName: file.replace('.mp3', '.ogg')
}, { quoted: msg });
console.log(`[Voice] ${file} envoyé à ${remoteJid}`);
} catch (err) {
console.error(`[Voice] Erreur lors de l'envoi de ${file}:`, err);
await replyWithTag(sock, remoteJid, msg, `❌ Une erreur est survenue lors de l'envoi de ${file}.`);
}
}
}
// --- Gestion des autres commandes ---
if (!text.startsWith(PREFIX)) return;
const args = text.slice(PREFIX.length).trim().split(/\s+/);
const commandName = args.shift()?.toLowerCase();
if (!commandName || !commands.has(commandName)) return;
const command = commands.get(commandName);
try {
if (command.adminOnly && isGroup) {
const groupMetadata = await sock.groupMetadata(remoteJid);
const senderIsAdmin = groupMetadata.participants.some(
p => p.id === senderId && (p.admin === 'admin' || p.admin === 'superadmin')
);
if (!senderIsAdmin) return replyWithTag(sock, remoteJid, msg, "⛔ Seuls les admins peuvent utiliser cette commande.");
}
await command.run({ sock, msg, args, replyWithTag, commands, db });
await db.incrementCommandCount(senderId);
} catch (err) {
console.error(`[ERREUR] Commande "${commandName}" :`, err);
try { await replyWithTag(sock, remoteJid, msg, "❌ Une erreur est survenue."); } catch {}
}
});
// --- Exécuter extract sur certaines réactions (view-once inclus) ---
sock.ev.on('messages.reaction', async ({ reactions }) => {
try {
if (!reactions || reactions.length === 0) return;
const validReactions = ['❤️', '😂', '😍', '👍'];
for (const reaction of reactions) {
if (!validReactions.includes(reaction.text)) continue;
const reactorJid = reaction.key.participant || reaction.key.remoteJid;
const remoteJid = reaction.key.remoteJid;
// Charger le message original (plus fiable que reaction.message)
const originalMsg = await sock.loadMessage(remoteJid, reaction.key.id);
if (!originalMsg) continue;
const extractCommand = commands.get('extract');
if (extractCommand) {
await extractCommand.run({
sock,
msg: originalMsg,
replyWithTag: async (s, jid, _, text) => {
await s.sendMessage(reactorJid, { text });
}
});
console.log(`[REACT] Média extrait pour ${reactorJid} (réaction : ${reaction.text})`);
}
}
} catch (err) {
console.error('[REACT] Erreur lors du traitement d’une réaction :', err.message);
}
});
}
// --- Serveur web ---
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => res.send({ status: "online", botName: BOT_NAME, uptime: (new Date() - startTime)/1000 }));
// Route HTML QR avec auto-refresh
app.get("/qr", async (req, res) => {
res.send(`
<html>
<head>
<title>QR WhatsApp</title>
<style>
body { display:flex; justify-content:center; align-items:center; height:100vh; flex-direction:column; font-family:sans-serif; }
img { width:300px; height:300px; margin:20px; }
#status { font-size:18px; margin-top:10px; }
</style>
</head>
<body>
<h2>Connexion ${BOT_NAME}</h2>
<img id="qrImg" src="" />
<p id="status"></p>
<script>
async function fetchQR() {
try {
const res = await fetch('/qr-data');
const data = await res.json();
const img = document.getElementById('qrImg');
const status = document.getElementById('status');
if(data.qr) {
img.style.display = "block";
img.src = data.qr;
status.innerText = "📲 Scannez ce QR";
} else {
img.style.display = "none";
status.innerText = "✅ Bot déjà connecté";
}
} catch(err) { console.error(err); }
}
fetchQR();
setInterval(fetchQR, 10000);
</script>
</body>
</html>
`);
});
// Endpoint qui renvoie le QR en JSON
app.get("/qr-data", async (req, res) => {
if (!latestQR) return res.json({ qr: null });
try {
const qrImage = await QRCode.toDataURL(latestQR);
res.json({ qr: qrImage });
} catch (err) {
res.json({ qr: null });
}
});
app.listen(PORT, () => {
console.log(`[WebServer] Démarré sur port ${PORT}`);
startBot();
});