-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
288 lines (252 loc) · 12.2 KB
/
index.js
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
const { default: makeWASocket, useMultiFileAuthState, DisconnectReason } = require("@whiskeysockets/baileys");
const pino = require("pino");
const { Boom } = require("@hapi/boom");
// Helper function to format and simplify messages
function smsg(SHYZUKI, mek) {
if (!mek) return mek;
const mtype = Object.keys(mek.message)[0];
mek.id = mek.key.id;
mek.isBaileys = mek.key.id.startsWith("BAE5") && mek.key.id.length === 16;
mek.chat = mek.key.remoteJid;
mek.fromMe = mek.key.fromMe;
mek.isGroup = mek.chat.endsWith("@g.us");
mek.sender = mek.fromMe
? SHYZUKI.user.id
: mek.isGroup
? mek.key.participant
: mek.key.remoteJid;
mek.mtype = mtype;
mek.text =
mek.message.conversation ||
mek.message[mtype]?.caption ||
mek.message[mtype]?.text ||
"";
mek.mentionedJid = mek.message[mtype]?.contextInfo?.mentionedJid || [];
return mek;
}
// Helper function to extract message content
function extractMessageContent(message) {
const msg = message.message;
if (!msg) return "No content";
if (msg.conversation) return msg.conversation;
if (msg.imageMessage) return `[Image: ${msg.imageMessage.caption || "No caption"}]`;
if (msg.videoMessage) return `[Video: ${msg.videoMessage.caption || "No caption"}]`;
if (msg.documentMessage) return `[Document: ${msg.documentMessage.fileName || "Unnamed"}]`;
if (msg.audioMessage) return `[Audio Message]`;
if (msg.stickerMessage) return `[Sticker Message]`;
if (msg.extendedTextMessage) return msg.extendedTextMessage.text;
if (msg.buttonsResponseMessage) return `[Button Response: ${msg.buttonsResponseMessage.selectedButtonId}]`;
if (msg.listResponseMessage) return `[List Response: ${msg.listResponseMessage.singleSelectReply.selectedRowId}]`;
if (msg.templateButtonReplyMessage)
return `[Template Button Reply: ${msg.templateButtonReplyMessage.selectedId}]`;
return "Unsupported message type";
}
// Main function to start the bot
async function startSHYZUKI() {
const { state, saveCreds } = await useMultiFileAuthState("auth_info");
const SHYZUKI = makeWASocket({
logger: pino({ level: "fatal" }),
auth: state,
printQRInTerminal: true,
browser: ["SHYZUKI ", "Safari", "3.0"],
});
// Handle connection updates
SHYZUKI.ev.on("connection.update", (update) => {
const { connection, lastDisconnect } = update;
if (connection === "close") {
const shouldReconnect =
lastDisconnect?.error instanceof Boom &&
lastDisconnect.error.output?.statusCode !== DisconnectReason.loggedOut;
console.log(`Connection closed. Should reconnect: ${shouldReconnect}`);
if (shouldReconnect) {
startSHYZUKI();
} else {
console.log("Logged out. Restart the script to reconnect.");
}
} else if (connection === "open") {
console.log("Connected to WhatsApp!");
}
});
// Save authentication state
SHYZUKI.ev.on("creds.update", saveCreds);
// Listen for incoming messages and log their metadata
SHYZUKI.ev.on("messages.upsert", async (chatUpdate) => {
try {
const messages = chatUpdate.messages;
messages.forEach((message) => {
// Extract metadata
const msgId = message.key.id; // Message ID
const from = message.key.remoteJid; // Sender or group ID
const to = message.key.participant || "N/A"; // Message participant (for groups)
const isFromMe = message.key.fromMe; // Is this sent by the bot?
const content = extractMessageContent(message); // Extract content
const timestamp = message.messageTimestamp || "Unknown"; // Timestamp
// Log the message details
console.log("======================================");
console.log(`Message ID: ${msgId}`);
console.log(`From: ${from}`);
console.log(`To: ${to}`);
console.log(`Is from me: ${isFromMe}`);
console.log(`Content: ${content}`);
console.log(`Timestamp: ${new Date(timestamp * 1000).toLocaleString()}`);
console.log("======================================");
});
} catch (err) {
console.error("Error handling message:", err);
}
});
// Command handling (Example: u2g command)
// Global bot status variable
let botStatus = true; // true = bot is ON, false = bot is OFF
SHYZUKI.ev.on("messages.upsert", async (chatUpdate) => {
try {
const mek = chatUpdate.messages[0];
if (!mek.message) return;
mek.message =
Object.keys(mek.message)[0] === "ephemeralMessage"
? mek.message.ephemeralMessage.message
: mek.message;
if (mek.key && mek.key.remoteJid === "status@broadcast") return;
const m = smsg(SHYZUKI, mek);
const body =
m.mtype === "conversation"
? m.message.conversation : m.message[m.mtype]?.caption || m.message[m.mtype]?.text || "";
const command = body.trim().split(" ")[0].toLowerCase();
const args = body.trim().split(" ").slice(1);
const text = args.join(" ");
const participants = m.isGroup
? await SHYZUKI.groupMetadata(m.chat).then((metadata) => metadata.participants)
: [];
const mentions = m.isGroup ? participants.map((a) => a.id) : [];
console.log(`Received command: ${command}`); // Debugging
// Bot status handling
if (!botStatus && command !== "on") {
console.log("Bot is turned off. Ignoring command...");
return;
}
// Command handling
switch (command) {
case "on":
if (botStatus) {
await SHYZUKI.sendMessage(m.chat, { text: "Bot is already ON!" });
} else {
botStatus = true;
await SHYZUKI.sendMessage(m.chat, { text: "Bot is now ON!" });
}
break;
case "help":
const commandList = [
"*🤖 Available Commands:*\n",
"*on* - Turn the bot ON",
"*off* - Turn the bot OFF",
"*alive* - Check if bot is running",
"*u2g* - Upload files to groups from URL",
" Usage: u2g [URL]\n Supports: Images, Videos, Audio, PDF, RAR files",
"*help* - Show this help message"
].join("\n");
await SHYZUKI.sendMessage(m.chat, {
text: commandList,
mentions: mentions
});
break;
case "off":
if (!botStatus) {
await SHYZUKI.sendMessage(m.chat, { text: "Bot is already OFF!" });
} else {
botStatus = false;
await SHYZUKI.sendMessage(m.chat, { text: "Bot is now OFF!" });
}
break;
case "alive":
await SHYZUKI.sendMessage(m.chat, {
text: "*Yeahh. I'm Alive 😇*",
mentions: mentions,
});
break;
case "u2g":
if (!text) {
return SHYZUKI.sendMessage(
m.chat,
{ text: "Please provide a valid URL link." },
{ quoted: m }
);
}
const urls = text.trim().split("\n");
const groupIds = process.env.GROUP_IDS.split(","); // Read from environment variable
try {
// Loop through each URL provided in the text
for (const url of urls) {
const decodedUrl = decodeURIComponent(url.trim());
const fileName = decodedUrl.split("/").pop();
// Detect MIME type dynamically
const mime = require("mime-types");
const mimeType = mime.lookup(fileName); // e.g., 'image/jpeg', 'video/mp4', etc.
// Iterate through all group IDs
for (const groupId of groupIds) {
if (mimeType.startsWith("image")) {
// Send image
await SHYZUKI.sendMessage(groupId, {
image: { url: decodedUrl },
caption: `Uploaded File: ${fileName}`,
});
} else if (mimeType.startsWith("video/x-matroska,")) {
// Send video
await SHYZUKI.sendMessage(groupId, {
video: { url: decodedUrl },
caption: `Uploaded File: ${fileName}`,
});
} else if (mimeType.startsWith("video")) {
// Send video
await SHYZUKI.sendMessage(groupId, {
video: { url: decodedUrl },
caption: `Uploaded File: ${fileName}`,
});
} else if (mimeType.startsWith("audio")) {
// Send audio
await SHYZUKI.sendMessage(groupId, {
audio: { url: decodedUrl },
mimetype: mimeType, // Provide MIME type explicitly
});
} else if (mimeType === "application/pdf") {
// Send PDF document
await SHYZUKI.sendMessage(groupId, {
document: { url: decodedUrl },
fileName: fileName,
mimetype: mimeType,
});
} else if (mimeType === "application/vnd.rar") {
// Send RAR file (added MIME type for .rar)
await SHYZUKI.sendMessage(groupId, {
document: { url: decodedUrl },
fileName: fileName,
mimetype: mimeType,
});
} else {
// Unsupported type
await SHYZUKI.sendMessage(groupId, {
text: `Unsupported file type: ${mimeType || "Unknown"}`,
});
}
}
// Confirm upload success for each file
await SHYZUKI.sendMessage(m.chat, {
text: `File successfully uploaded : ${fileName}`,
});
}
} catch (err) {
console.error("Error uploading file:", err);
await SHYZUKI.sendMessage(m.chat, {
text: "Failed to upload the file. Please check the URL and try again.",
});
}
break;
}
} catch (err) {
console.error("Error handling message:", err);
}
});
}
// Start the bot
startSHYZUKI().catch((err) => {
console.error("Failed to start:", err);
});