-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathindex.js
206 lines (192 loc) · 8.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
'use strict';
const { default: makeWASocket, useMultiFileAuthState, fetchLatestBaileysVersion, makeInMemoryStore, getContentType, jidNormalizedUser, generateForwardMessageContent, downloadContentFromMessage, jidDecode } = require('@whiskeysockets/baileys');
const { Sequelize, DataTypes } = require('sequelize');
const { list, uninstall } = require('./helpers/database/commands');
const { parseJson } = require('./helpers/utils');
const { database } = require('./helpers/database.js');
const { SESSION, ADMINS, MODE, PREFIX, ONLINE, PLATFORM, DEBUG } = require('./config');
const Greetings = require('./helpers/database/greetings');
const axios = require('axios');
const pino = require('pino');
const colors = require('colors');
const qrcode = require('qrcode-terminal');
const fs = require('fs');
if (PLATFORM == 'koyeb') {
require('http')
.createServer(async (req, res) => {})
.listen(process.env?.PORT || 8080, () => true);
}
const Users = database.define('Users', {
name: {
primaryKey: true,
unique: false,
type: DataTypes.STRING,
allowNull: false
},
id: {
type: DataTypes.TEXT,
allowNull: false
}
});
async function Connect() {
try {
let store = makeInMemoryStore({
logger: pino().child({ level: 'silent', stream: 'store' })
});
if (SESSION !== false && !fs.existsSync('./session/creds.json')) {
try {
let auth = Buffer.from(SESSION, 'base64').toString();
fs.writeFileSync(__dirname + '/session/creds.json', auth);
console.log('[ - ] Creating session file...');
} catch (e) {
console.error(e)
throw new Error('[ ! ] Please provide a valid SESSION');
}
}
// let { version, isLatest } = await fetchLatestBaileysVersion();
let { state, saveCreds } = await useMultiFileAuthState('./session');
let sock = makeWASocket({
logger: pino({ level: DEBUG === true ? 'debug' : 'silent' }),
printQRInTerminal: false,
markOnlineOnConnect: false,
browser: ['Ubuntu', 'Chrome', '20.0.04'],
auth: state,
version: [2, 3000, 1015901307],
patchMessageBeforeSending: (message) => {
let requiresPatch = !!(message.buttonsMessage || message.listMessage || message.templateMessage)
if (requiresPatch) {
message = {
viewOnceMessage: {
message: {
messageContextInfo: {
deviceListMetadata: {},
deviceListMetadataVersion: 2,
},
...message,
},
},
}
}
return message
},
getMessage: async (key) => {
let jid = jidNormalizedUser(key.remoteJid)
let msg = await store.loadMessage(jid, key.id)
return msg?.message || ""
}
});
store.bind(sock.ev);
sock.ev.on('connection.update', async (update) => {
const { connection } = update;
if (connection === 'close') {
console.log(colors.red('[ ! ] Connection Closed: Reconnecting...'));
await Connect();
} else if (connection === 'open') {
console.log(colors.green('[ + ] Connected!'));
}
});
let extCommands = await list();
extCommands.forEach(async (cmd) => {
if (!fs.existsSync('./commands/' + cmd.name + '.js')) {
try {
let content = await parseJson(cmd.url);
fs.writeFileSync('./commands/' + cmd.name + '.js', content);
require('./commands/' + cmd.name);
} catch (e) {
console.log('[ ! ] ' + cmd.name + ' command crashed.');
console.error(e);
try {
fs.unlinkSync('./commands/' + cmd.name + '.js');
} catch {}
await uninstall(cmd.name);
console.log('[ + ] ' + cmd.name + ' command has been removed!');
}
}
});
if (extCommands.length > 0) {
console.log('[ + ] Loaded external commands.');
}
sock.ev.on('group-participants.update', async (info) => {
let gc = await sock.groupMetadata(info.id);
let subject = gc.title, size = gc.size, owner = gc.owner;
if (info.action == 'add') {
let wtext = await Greetings.getMessage('welcome', info.id);
if (wtext !== false) await sock.sendMessage(info.id, {
text: wtext.replace(/{subject}/g, subject).replace(/{version}/g, require('./package.json').version).replace(/{size}/g, size).replace(/{user}/g, '@'+info.participants[0].split('@')[0]).replace(/{owner}/g, '@'+owner.split('@')[0]),
mentions: [owner, ...info.participants]
});
} else if (info.action == 'remove') {
let gtext = await Greetings.getMessage('goodbye', info.id);
if (gtext !== false) await sock.sendMessage(info.id, {
text: gtext.replace(/{subject}/g, subject).replace(/{version}/g, require('./package.json').version).replace(/{size}/g, size).replace(/{user}/g, '@'+info.participants[0].split('@')[0]).replace(/{owner}/g, '@'+owner.split('@')[0]),
mentions: [owner, ...info.participants]
});
}
});
sock.ev.on('messages.upsert', async (msg) => {
msg = msg.messages[0];
if (!msg.message) return;
msg = await require('./helpers/message')(msg, sock, store);
if (msg.chat === 'status@broadcast') return;
if (ONLINE !== true) await sock.sendPresenceUpdate('unavailable', msg.chat);
try {
if (allCommands(msg.command) || msg.isPrivate) {
let user = await Users.findAll({ where: { id: msg.isPrivate ? msg.chat : msg.sender } });
if (user.length < 1) {
await Users.create({ name: msg.pushName, id: msg.isPrivate ? msg.chat : msg.sender });
} else {
await Users[0]?.update({ name: msg.pushName });
}
}
} catch {}
let admins = ADMINS !== false ? (ADMINS?.includes(',') ? ADMINS?.split(',').map(admin => admin.trim() + '@s.whatsapp.net') : [ADMINS?.trim() + '@s.whatsapp.net']) : [];
allCommands().forEach(async (command) => {
if (command.event) await command.event(sock, msg, msg.text);
try {
if ((MODE === 'private' && (msg.fromMe || admins.includes(msg.sender))) ||
(MODE === 'public' && (!command.private || (msg.fromMe || admins.includes(msg.sender))))) {
let text = msg.text?.replace(PREFIX + command.command, '').trim();
if (msg.text.startsWith(PREFIX + command.command)) {
await command.func(sock, msg, text);
}
}
} catch (e) {
console.log(e);
await sock.sendMessage(sock.user.id, {
text: '*ERROR OCCURRED*\n\n_An error occurred while using ' + msg.command + ' command._\n_Please open an issue at https://github.com/TOXIC-DEVIL/Leon/issues for an instant support._\n\n*Error:*\n*' + e.message + '*'
});
}
});
});
sock.ev.on('presence.update', () => {});
sock.ev.on('contacts.upsert', async (contact) => store.bind(contact));
sock.ev.on('creds.update', saveCreds);
} catch (e) {
console.log(e.stack);
Connect();
}
}
function allCommands(command) {
let commands = [];
fs.readdirSync('./commands').forEach(file => {
if (file.endsWith('.js')) {
let command = require('./commands/' + file);
if (command.event) {
commands.push({ command: command.command, info: command.info, private: command.private, func: command.func, event: command.event });
} else {
commands.push({ command: command.command, info: command.info, private: command.private, func: command.func });
}
}
});
if (command) {
return commands.includes(command);
} else {
return commands;
}
}
Connect();
module.exports = {
Users,
Connect,
allCommands
};