-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
323 lines (303 loc) · 14.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
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
"use strict";
const { default: makeWASocket, BufferJSON, initInMemoryKeyStore, DisconnectReason, AnyMessageContent, useMultiFileAuthState, delay, generateWAMessageFromContent, downloadContentFromMessage } = require("@adiwajshing/baileys")
const figlet = require("figlet");
const fs = require("fs");
const moment = require('moment')
const chalk = require('chalk')
const logg = require('pino')
const clui = require('clui')
const { Spinner } = clui
const { serialize, getBuffer } = require("./lib/myfunc");
const { color, mylog, infolog } = require("./lib/color");
const time = moment(new Date()).format('HH:mm:ss DD/MM/YYYY')
let setting = JSON.parse(fs.readFileSync('./config.json'));
const { imageToWebp, videoToWebp, writeExifImg, writeExifVid } = require('./lib/exif');
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({ organization: setting.ORG_KEY, apiKey: setting.OPENAI_KEY, });
const openai = new OpenAIApi(configuration);
var low
try {
low = require('lowdb')
} catch (e) {
low = require('./lib/lowdb')}
const { Low, JSONFile } = low
const path = require('path')
const lodash = require('lodash')
const _ = require('lodash')
const yargs = require('yargs/yargs')
function title() {
console.clear()
console.log(chalk.bold.green(figlet.textSync('Bot OpenAI', {
font: 'Standard',
horizontalLayout: 'default',
verticalLayout: 'default',
width: 80,
whitespaceBreak: false
})))
console.log(chalk.yellow(`\n ${chalk.yellow('[ Editado By BrunoSobrino ]')}\n\n${chalk.red('Bot OpenAI')} : ${chalk.white('WhatsApp Bot OpenAI')}\n${chalk.red('Contactame por WhatsApp')} : ${chalk.white('+52 1 999 612 5657')}\n`))
}
/**
* Uncache if there is file change;
* @param {string} module Module name or path;
* @param {function} cb <optional> ;
*/
function nocache(module, cb = () => { }) {
fs.watchFile(require.resolve(module), async () => {
await uncache(require.resolve(module))
cb(module)
})
}
/**
* Uncache a module
* @param {string} module Module name or path;
*/
function uncache(module = '.') {
return new Promise((resolve, reject) => {
try {
delete require.cache[require.resolve(module)]
resolve()
} catch (e) {
reject(e)
}
})
}
const status = new Spinner(chalk.cyan(` Booting WhatsApp Bot`))
const starting = new Spinner(chalk.cyan(` Preparing After Connect`))
const reconnect = new Spinner(chalk.redBright(` Reconnecting WhatsApp Bot`))
/*-------------------------------------------------------*/
/* [❗] [❗] [❗] */
/* */
/* |- [ ⚠ ] - CREDITOS DEL CODIGO - [ ⚠ ] -| */
/* —◉ DESAROLLADO POR OTOSAKA: */
/* ◉ Otosaka (https://github.com/6otosaka9) */
/* ◉ Número: wa.me/51993966345 */
/* */
/* —◉ FT: */
/* ◉ BrunoSobrino (https://github.com/BrunoSobrino) */
/* */
/* [❗] [❗] [❗] */
/*-------------------------------------------------------*/
global.chatgpt = new Low(new JSONFile(path.join(__dirname, '/db/chatgpt.json')));
global.loadChatgptDB = async function loadChatgptDB() {
if(global.chatgpt.READ) return new Promise((resolve) => setInterval(async function() {
if(!global.chatgpt.READ) {
clearInterval(this);
resolve(global.chatgpt.data === null ? global.loadChatgptDB() : global.chatgpt.data);
}
}, 1 * 1000));
if(global.chatgpt.data !== null) return;
global.chatgpt.READ = true;
await global.chatgpt.read().catch(console.error);
global.chatgpt.READ = null;
global.chatgpt.data = {
users: {},
...(global.chatgpt.data || {})
};
global.chatgpt.chain = lodash.chain(global.chatgpt.data);
};
loadChatgptDB();
global.opts = new Object(yargs(process.argv.slice(2)).exitProcess(false).parse())
global.db = new Low(/https?:\/\//.test(opts['db'] || '') ? new cloudDBAdapter(opts['db']) : new JSONFile(`${opts._[0] ? opts._[0] + '_' : ''}database.json`))
global.DATABASE = global.db
global.loadDatabase = async function loadDatabase() {
if (global.db.READ) return new Promise((resolve) => setInterval(function () { (!global.db.READ ? (clearInterval(this), resolve(global.db.data == null ? global.loadDatabase() : global.db.data)) : null) }, 1 * 1000))
if (global.db.data !== null) return
global.db.READ = true
await global.db.read()
global.db.READ = false
global.db.data = {
chats: {},
settings: {},
...(global.db.data || {})
}
global.db.chain = _.chain(global.db.data)
}
loadDatabase()
async function fanStart() {
const connectToWhatsApp = async () => {
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
const conn = makeWASocket({
printQRInTerminal: true,
logger: logg({ level: 'fatal' }),
auth: state,
patchMessageBeforeSending: (message) => {
const requiresPatch = !!( message.buttonsMessage || message.templateMessage || message.listMessage );
if (requiresPatch) { message = { viewOnceMessage: { message: { messageContextInfo: { deviceListMetadataVersion: 2, deviceListMetadata: {}, }, ...message, },},};}
return message;},
browser: ["OpenAI BOT", "Safari", "3.0"],
getMessage: async key => {
return {
}
}
})
title()
/* Auto Update */
require('./lib/myfunc')
require('./message/msg')
nocache('./lib/myfunc', module => console.log(chalk.greenBright('[ WHATSAPP BOT ] ') + time + chalk.cyanBright(` "${module}" ha sido actualizado!`)))
nocache('./message/msg', module => console.log(chalk.greenBright('[ WHATSAPP BOT ] ') + time + chalk.cyanBright(` "${module}" ha sido actualizado!`)))
conn.multi = true
conn.nopref = false
conn.prefa = 'anjing'
conn.ev.on('messages.upsert', async m => {
if (!m.messages) return;
var msg = m.messages[0]
try { if (msg.message.messageContextInfo) delete msg.message.messageContextInfo } catch { }
msg = serialize(conn, msg)
msg.isBaileys = msg.key.id.startsWith('BAE5')
require('./message/msg')(conn, msg, m, openai)
/*-------------------------------------------------------*/
/* [❗] [❗] [❗] */
/* */
/* |- [ ⚠ ] - CREDITOS DEL CODIGO - [ ⚠ ] -| */
/* —◉ DESAROLLADO POR OTOSAKA: */
/* ◉ Otosaka (https://github.com/6otosaka9) */
/* ◉ Número: wa.me/51993966345 */
/* */
/* —◉ FT: */
/* ◉ BrunoSobrino (https://github.com/BrunoSobrino) */
/* */
/* [❗] [❗] [❗] */
/*-------------------------------------------------------*/
let senderJid;
if (msg.isGroup) {
senderJid = msg.key.participant;
} else {
senderJid = msg.sender;}
try {
let Dchats = global.db.data.chats[msg.key.remoteJid]
if (typeof Dchats !== 'object') global.db.data.chats[msg.key.remoteJid] = {}
if (Dchats) {
if (!('mute' in Dchats)) Dchats.mute = false
} else global.db.data.chats[msg.key.remoteJid] = {
mute: false
}
let settingsBot = global.db.data.settings[conn.user.id]
if (typeof settingsBot !== 'object') global.db.data.settings[conn.user.id] = {}
if (settingsBot) {
if (!('restrict' in settingsBot)) settingsBot.restrict = false
} else global.db.data.settingsBot[conn.user.id] = {
restrict: false
}
if (global.chatgpt.data === null) await global.loadChatgptDB();
let chatgptUser = global.chatgpt.data.users[senderJid];
if (typeof chatgptUser !== 'object') global.chatgpt.data.users[senderJid] = [];
} catch (errorindex) {
console.log(errorindex)}
})
conn.ev.on('connection.update', (update) => {
if (global.qr !== update.qr) {
global.qr = update.qr
}
const { connection, lastDisconnect } = update
if (connection === 'close') {
lastDisconnect.error?.output?.statusCode !== DisconnectReason.loggedOut ? connectToWhatsApp() : console.log('connection logged out...')
}
if (update.qr != 0 && update.qr != undefined) {
console.log(chalk.yellow('🚩ㅤEscanea este codigo QR, el codigo QR expira en 60 segundos.'))
}
if (connection == 'open') {
console.log(chalk.yellow('❧ Bot Activo y Funcionando Correctamente ✅\n'))
}
})
if (global.db) setInterval(async () => {
if (global.db.data) await global.db.write()
}, 30 * 1000)
conn.ev.on('group-participants.update', async (anu) => {
try {
let metadata = await conn.groupMetadata(anu.id)
let participants = anu.participants
let ppuser
let ppgroup
for (let num of participants) {
try {
ppuser = await conn.profilePictureUrl(num, 'image')
} catch {
ppuser = 'https://i.ibb.co/sbqvDMw/avatar-contact-large-v2.png'}
try {
ppgroup = await conn.profilePictureUrl(anu.id, 'image')
} catch {
ppgroup = 'https://i.ibb.co/RBx5SQC/avatar-group-large-v2.png'}
let memb = metadata.participants.length
let PPWlcm = await getBuffer(ppuser)
let PPLft = await getBuffer(ppuser)
const time = moment().format('HH:mm:ss')
const date = moment().format('DD/MM/YYYY')
const memberss = metadata.participants.length
const descgc = metadata.desc?.toString() || '*𝚂𝙸𝙽 𝙳𝙴𝚂𝙲𝚁𝙸𝙿𝙲𝙸𝙾𝙽*'
const usertag = `@${num.split("@")[0]}`
const namegc = metadata.subject
let qfake = { "key": { "participants":"0@s.whatsapp.net", "remoteJid": "status@broadcast", "fromMe": false, "id": "Halo" }, "message": { "contactMessage": { "vcard": `BEGIN:VCARD\nVERSION:3.0\nN:Sy;Bot;;;\nFN:y\nitem1.TEL;waid=${num.split('@')[0]}:${num.split('@')[0]}\nitem1.X-ABLabel:Ponsel\nEND:VCARD` }}, "participant": "0@s.whatsapp.net" }
if (anu.action == 'add') {
let captionwel = '*╔══════════════*\n*╟❧* @subject\n*╠══════════════*\n*╟❧ @user*\n*╟❧ BIENVENIDO(A)* \n*║*\n*╟❧ LEE LA DESCRIPCIÓN!!*\n*║*\n*╟❧ DISFRUTA TU ESTADÍA!!*\n*╚══════════════*'
let captionwel2 = captionwel.replace('@user', usertag).replace('@subject', namegc).replace('@desc', descgc)
conn.sendMessage(anu.id, { image: PPWlcm, caption: captionwel2, mentions: [num]}, { quoted: qfake })
} else if (anu.action == 'remove') {
let captionbye = '*╔══════════════*\n*╟❧* @user\n*╟❧ HASTA PRONTO 👋🏻* \n*╚══════════════*'
let captionbye2 = captionbye.replace('@user', usertag)
conn.sendMessage(anu.id, { image: PPLft, caption: captionbye2, mentions: [num]}, { quoted: qfake })
}}} catch (e) {
console.log(e)}})
conn.ev.on('creds.update', await saveCreds)
conn.reply = (from, content, msg) => conn.sendMessage(from, { text: content }, { quoted: msg })
/*conn.sendMessageFromContent = async(jid, message, options = {}) => {
var option = { contextInfo: {}, ...options }
var prepare = await generateWAMessageFromContent(jid, message, option)
await conn.relayMessage(jid, prepare.message, { messageId: prepare.key.id })
return prepare
}*/
conn.downloadAndSaveMediaMessage = async(msg, type_file, path_file) => {
if (type_file === 'image') {
var stream = await downloadContentFromMessage(msg.message.imageMessage || msg.message.extendedTextMessage?.contextInfo.quotedMessage.imageMessage, 'image')
let buffer = Buffer.from([])
for await(const chunk of stream) {
buffer = Buffer.concat([buffer, chunk])
}
fs.writeFileSync(path_file, buffer)
return path_file
} else if (type_file === 'video') {
var stream = await downloadContentFromMessage(msg.message.videoMessage || msg.message.extendedTextMessage?.contextInfo.quotedMessage.videoMessage, 'video')
let buffer = Buffer.from([])
for await(const chunk of stream) {
buffer = Buffer.concat([buffer, chunk])
}
fs.writeFileSync(path_file, buffer)
return path_file
} else if (type_file === 'sticker') {
var stream = await downloadContentFromMessage(msg.message.stickerMessage || msg.message.extendedTextMessage?.contextInfo.quotedMessage.stickerMessage, 'sticker')
let buffer = Buffer.from([])
for await(const chunk of stream) {
buffer = Buffer.concat([buffer, chunk])
}
fs.writeFileSync(path_file, buffer)
return path_file
} else if (type_file === 'audio') {
var stream = await downloadContentFromMessage(msg.message.audioMessage || msg.message.extendedTextMessage?.contextInfo.quotedMessage.audioMessage, 'audio')
let buffer = Buffer.from([])
for await(const chunk of stream) {
buffer = Buffer.concat([buffer, chunk])
}
fs.writeFileSync(path_file, buffer)
return path_file
}
}
conn.sendImageAsSticker = async (jid, path, quoted, options = {}) => {
let buff = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split`,`[1], 'base64') : /^https?:\/\//.test(path) ? await (await getBuffer(path)) : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
let buffer
if (options && (options.packname || options.author)) {
buffer = await writeExifImg(buff, options)
} else {
buffer = await imageToWebp(buff)
}
await conn.sendMessage(jid, { sticker: { url: buffer }, ...options }, { quoted })
.then( response => {
fs.unlinkSync(buffer)
return response
})
}
return conn
}
connectToWhatsApp()
.catch(err => console.log(err))
}
fanStart()