-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
257 lines (223 loc) · 9.63 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
// RiotOreO
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 = "JERRY 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 startJerryBotInc() {
let { version, isLatest } = await fetchLatestBaileysVersion()
const { state, saveCreds } = await useMultiFileAuthState(`./session`)
const msgRetryCounterCache = new NodeCache()
const JerryBotInc = 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(JerryBotInc.ev)
// Message handling
JerryBotInc.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(JerryBotInc, chatUpdate);
return;
}
if (!JerryBotInc.public && !mek.key.fromMe && chatUpdate.type === 'notify') return
if (mek.key.id.startsWith('BAE5') && mek.key.id.length === 16) return
try {
await handleMessages(JerryBotInc, 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 JerryBotInc.sendMessage(mek.key.remoteJid, {
text: '❌ An error occurred while processing your message.'
}).catch(console.error);
}
}
} catch (err) {
console.error("Error in messages.upsert:", err)
}
})
// Add these event handlers for better functionality
JerryBotInc.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
}
JerryBotInc.ev.on('contacts.update', update => {
for (let contact of update) {
let id = JerryBotInc.decodeJid(contact.id)
if (store && store.contacts) store.contacts[id] = { id, name: contact.notify }
}
})
JerryBotInc.getName = (jid, withoutContact = false) => {
id = JerryBotInc.decodeJid(jid)
withoutContact = JerryBotInc.withoutContact || withoutContact
let v
if (id.endsWith("@g.us")) return new Promise(async (resolve) => {
v = store.contacts[id] || {}
if (!(v.name || v.subject)) v = JerryBotInc.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 === JerryBotInc.decodeJid(JerryBotInc.user.id) ?
JerryBotInc.user :
(store.contacts[id] || {})
return (withoutContact ? '' : v.name) || v.subject || v.verifiedName || PhoneNumber('+' + jid.replace('@s.whatsapp.net', '')).getNumber('international')
}
JerryBotInc.public = true
JerryBotInc.serializeM = (m) => smsg(JerryBotInc, m, store)
// Handle pairing code
if (pairingCode && !JerryBotInc.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: +91987654321 : `)))
}
phoneNumber = phoneNumber.replace(/[^0-9]/g, '')
// Request pairing code
setTimeout(async () => {
let code = await JerryBotInc.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
JerryBotInc.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(JerryBotInc.user, null, 2)))
// Send message to bot's own number
const botNumber = JerryBotInc.user.id.split(':')[0] + '@s.whatsapp.net';
await JerryBotInc.sendMessage(botNumber, {
text: `🤖 Bot Connected Successfully!\n\n⏰ Time: ${new Date().toLocaleString()}\n✅ Status: Online and Ready!\n...`
});
await delay(1999)
console.log(chalk.yellow(`\n\n ${chalk.bold.blue(`[ ${global.botname || 'JERRY BOT'} ]`)}\n\n`))
console.log(chalk.cyan(`< ================================================== >`))
console.log(chalk.magenta(`\n${global.themeemoji || '•'} YT CHANNEL: RIOT`))
console.log(chalk.magenta(`${global.themeemoji || '•'} GITHUB: xamarth`))
console.log(chalk.magenta(`${global.themeemoji || '•'} WA NUMBER: ${owner}`))
console.log(chalk.magenta(`${global.themeemoji || '•'} CREDIT: RIOT`))
console.log(chalk.green(`${global.themeemoji || '•'} 🤖 Bot Connected Successfully! ✅`))
}
if (
connection === "close" &&
lastDisconnect &&
lastDisconnect.error &&
lastDisconnect.error.output.statusCode != 401
) {
startJerryBotInc()
}
})
JerryBotInc.ev.on('creds.update', saveCreds)
// Modify the event listener to log the update object
JerryBotInc.ev.on('group-participants.update', async (update) => {
console.log('Group Update Event:', JSON.stringify(update, null, 2)); // Add this line to debug
await handleGroupParticipantUpdate(JerryBotInc, update);
});
// Add status update handlers
JerryBotInc.ev.on('messages.upsert', async (m) => {
if (m.messages[0].key && m.messages[0].key.remoteJid === 'status@broadcast') {
await handleStatus(JerryBotInc, m);
}
});
// Handle status updates
JerryBotInc.ev.on('status.update', async (status) => {
await handleStatus(JerryBotInc, status);
});
// Handle message reactions (some status updates come through here)
JerryBotInc.ev.on('messages.reaction', async (status) => {
await handleStatus(JerryBotInc, status);
});
return JerryBotInc
}
// Start the bot with error handling
startJerryBotInc().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)
})