-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathindex.js
285 lines (252 loc) · 10.9 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
/**
* Knight Bot - A WhatsApp Bot
* Copyright (c) 2024 Professor
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the MIT License.
*
* Credits:
* - Baileys Library by @adiwajshing
* - Pair Code implementation inspired by TechGod143 & DGXEON
*/
require('./settings')
const { Boom } = require('@hapi/boom')
const fs = require('fs')
const chalk = require('chalk')
const FileType = require('file-type')
const path = require('path')
const axios = require('axios')
const { handleMessages, handleGroupParticipantUpdate, handleStatus } = require('./main');
const PhoneNumber = require('awesome-phonenumber')
const { imageToWebp, videoToWebp, writeExifImg, writeExifVid } = require('./lib/exif')
const { smsg, isUrl, generateMessageTag, getBuffer, getSizeMedia, fetch, await, sleep, reSize } = require('./lib/myfunc')
const {
default: makeWASocket,
useMultiFileAuthState,
DisconnectReason,
fetchLatestBaileysVersion,
generateForwardMessageContent,
prepareWAMessageMedia,
generateWAMessageFromContent,
generateMessageID,
downloadContentFromMessage,
makeInMemoryStore,
jidDecode,
proto,
jidNormalizedUser,
makeCacheableSignalKeyStore,
delay
} = require("@whiskeysockets/baileys")
const NodeCache = require("node-cache")
const pino = require("pino")
const readline = require("readline")
const { parsePhoneNumber } = require("libphonenumber-js")
const { PHONENUMBER_MCC } = require('@whiskeysockets/baileys/lib/Utils/generics')
const { rmSync, existsSync } = require('fs')
const { join } = require('path')
const store = makeInMemoryStore({
logger: pino().child({
level: 'silent',
stream: 'store'
})
})
let phoneNumber = "911234567890"
let owner = JSON.parse(fs.readFileSync('./database/owner.json'))
global.botname = "KNIGHT BOT"
global.themeemoji = "•"
const pairingCode = !!phoneNumber || process.argv.includes("--pairing-code")
const useMobile = process.argv.includes("--mobile")
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
const question = (text) => new Promise((resolve) => rl.question(text, resolve))
async function startXeonBotInc() {
let { version, isLatest } = await fetchLatestBaileysVersion()
const { state, saveCreds } = await useMultiFileAuthState(`./session`)
const msgRetryCounterCache = new NodeCache()
const XeonBotInc = makeWASocket({
version,
logger: pino({ level: 'silent' }),
printQRInTerminal: !pairingCode,
browser: ["Ubuntu", "Chrome", "20.0.04"],
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, pino({ level: "fatal" }).child({ level: "fatal" })),
},
markOnlineOnConnect: true,
generateHighQualityLinkPreview: true,
getMessage: async (key) => {
let jid = jidNormalizedUser(key.remoteJid)
let msg = await store.loadMessage(jid, key.id)
return msg?.message || ""
},
msgRetryCounterCache,
defaultQueryTimeoutMs: undefined,
})
store.bind(XeonBotInc.ev)
// Message handling
XeonBotInc.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') {
await handleStatus(XeonBotInc, chatUpdate);
return;
}
if (!XeonBotInc.public && !mek.key.fromMe && chatUpdate.type === 'notify') return
if (mek.key.id.startsWith('BAE5') && mek.key.id.length === 16) return
try {
await handleMessages(XeonBotInc, chatUpdate, true)
} catch (err) {
console.error("Error in handleMessages:", err)
// Only try to send error message if we have a valid chatId
if (mek.key && mek.key.remoteJid) {
await XeonBotInc.sendMessage(mek.key.remoteJid, {
text: '❌ An error occurred while processing your message.',
contextInfo: {
forwardingScore: 999,
isForwarded: true,
forwardedNewsletterMessageInfo: {
newsletterJid: '120363161513685998@newsletter',
newsletterName: 'KnightBot MD',
serverMessageId: -1
}
}
}).catch(console.error);
}
}
} catch (err) {
console.error("Error in messages.upsert:", err)
}
})
// Add these event handlers for better functionality
XeonBotInc.decodeJid = (jid) => {
if (!jid) return jid
if (/:\d+@/gi.test(jid)) {
let decode = jidDecode(jid) || {}
return decode.user && decode.server && decode.user + '@' + decode.server || jid
} else return jid
}
XeonBotInc.ev.on('contacts.update', update => {
for (let contact of update) {
let id = XeonBotInc.decodeJid(contact.id)
if (store && store.contacts) store.contacts[id] = { id, name: contact.notify }
}
})
XeonBotInc.getName = (jid, withoutContact = false) => {
id = XeonBotInc.decodeJid(jid)
withoutContact = XeonBotInc.withoutContact || withoutContact
let v
if (id.endsWith("@g.us")) return new Promise(async (resolve) => {
v = store.contacts[id] || {}
if (!(v.name || v.subject)) v = XeonBotInc.groupMetadata(id) || {}
resolve(v.name || v.subject || PhoneNumber('+' + id.replace('@s.whatsapp.net', '')).getNumber('international'))
})
else v = id === '0@s.whatsapp.net' ? {
id,
name: 'WhatsApp'
} : id === XeonBotInc.decodeJid(XeonBotInc.user.id) ?
XeonBotInc.user :
(store.contacts[id] || {})
return (withoutContact ? '' : v.name) || v.subject || v.verifiedName || PhoneNumber('+' + jid.replace('@s.whatsapp.net', '')).getNumber('international')
}
XeonBotInc.public = true
XeonBotInc.serializeM = (m) => smsg(XeonBotInc, m, store)
// Handle pairing code
if (pairingCode && !XeonBotInc.authState.creds.registered) {
if (useMobile) throw new Error('Cannot use pairing code with mobile api')
let phoneNumber
if (!!global.phoneNumber) {
phoneNumber = global.phoneNumber
} else {
phoneNumber = await question(chalk.bgBlack(chalk.greenBright(`Please type your WhatsApp number 😍\nFor example: +917023951514 : `)))
}
phoneNumber = phoneNumber.replace(/[^0-9]/g, '')
// Request pairing code
setTimeout(async () => {
let code = await XeonBotInc.requestPairingCode(phoneNumber)
code = code?.match(/.{1,4}/g)?.join("-") || code
console.log(chalk.black(chalk.bgGreen(`Your Pairing Code : `)), chalk.black(chalk.white(code)))
}, 3000)
}
// Connection handling
XeonBotInc.ev.on('connection.update', async (s) => {
const { connection, lastDisconnect } = s
if (connection == "open") {
console.log(chalk.magenta(` `))
console.log(chalk.yellow(`🌿Connected to => ` + JSON.stringify(XeonBotInc.user, null, 2)))
// Send message to bot's own number
const botNumber = XeonBotInc.user.id.split(':')[0] + '@s.whatsapp.net';
await XeonBotInc.sendMessage(botNumber, {
text: `🤖 Bot Connected Successfully!\n\n⏰ Time: ${new Date().toLocaleString()}\n✅ Status: Online and Ready!
\n Give a Star ⭐ to our bot:\n https://github.com/mruniquehacker/KnightBot-MD\n ✅Make sure to join below channel`,
contextInfo: {
forwardingScore: 999,
isForwarded: true,
forwardedNewsletterMessageInfo: {
newsletterJid: '120363161513685998@newsletter',
newsletterName: 'KnightBot MD',
serverMessageId: -1
}
}
});
await delay(1999)
console.log(chalk.yellow(`\n\n ${chalk.bold.blue(`[ ${global.botname || 'KNIGHT BOT'} ]`)}\n\n`))
console.log(chalk.cyan(`< ================================================== >`))
console.log(chalk.magenta(`\n${global.themeemoji || '•'} YT CHANNEL: MR UNIQUE HACKER`))
console.log(chalk.magenta(`${global.themeemoji || '•'} GITHUB: mrunqiuehacker`))
console.log(chalk.magenta(`${global.themeemoji || '•'} WA NUMBER: ${owner}`))
console.log(chalk.magenta(`${global.themeemoji || '•'} CREDIT: MR UNIQUE HACKER`))
console.log(chalk.green(`${global.themeemoji || '•'} 🤖 Bot Connected Successfully! ✅`))
}
if (
connection === "close" &&
lastDisconnect &&
lastDisconnect.error &&
lastDisconnect.error.output.statusCode != 401
) {
startXeonBotInc()
}
})
XeonBotInc.ev.on('creds.update', saveCreds)
// Modify the event listener to log the update object
XeonBotInc.ev.on('group-participants.update', async (update) => {
console.log('Group Update Event:', JSON.stringify(update, null, 2)); // Add this line to debug
await handleGroupParticipantUpdate(XeonBotInc, update);
});
// Add status update handlers
XeonBotInc.ev.on('messages.upsert', async (m) => {
if (m.messages[0].key && m.messages[0].key.remoteJid === 'status@broadcast') {
await handleStatus(XeonBotInc, m);
}
});
// Handle status updates
XeonBotInc.ev.on('status.update', async (status) => {
await handleStatus(XeonBotInc, status);
});
// Handle message reactions (some status updates come through here)
XeonBotInc.ev.on('messages.reaction', async (status) => {
await handleStatus(XeonBotInc, status);
});
return XeonBotInc
}
// Start the bot with error handling
startXeonBotInc().catch(error => {
console.error('Fatal error:', error)
process.exit(1)
})
// Better error handling
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err)
// Don't exit immediately to allow reconnection
})
process.on('unhandledRejection', (err) => {
console.error('Unhandled Rejection:', err)
// Don't exit immediately to allow reconnection
})
let file = require.resolve(__filename)
fs.watchFile(file, () => {
fs.unwatchFile(file)
console.log(chalk.redBright(`Update ${__filename}`))
delete require.cache[file]
require(file)
})