forked from Prince-Mendiratta/BotsApp
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAthena.ts
221 lines (201 loc) · 9.43 KB
/
Athena.ts
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
import { Boom } from '@hapi/boom'
import P, { Logger } from 'pino'
import makeWASocket, { DisconnectReason, fetchLatestBaileysVersion, makeInMemoryStore, WASocket, proto, Contact } from '@whiskeysockets/baileys'
import MessageRetryMap from '@whiskeysockets/baileys';
// @ts-ignore
import useRemoteFileAuthState from './core/dbAuth.cjs';
import fs from 'fs'
import { join } from 'path'
import {config} from './config.js'
import { banner } from './lib/banner.js'
import chalk from 'chalk'
import Greetings from './database/greeting'
import STRINGS from "./lib/db.js"
import Blacklist from './database/blacklist.js'
import clearance from './core/clearance.js'
import { start } from 'repl'
import format from 'string-format';
import resolve from './core/helper.js'
import { Sequelize } from 'sequelize/types'
import Command from './sidekick/command.js'
import Athena from './sidekick/sidekick.js'
import Client from './sidekick/client.js'
import { MessageType } from './sidekick/message-type.js'
type MessageRetryMap = Record<string, number>;
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const sequelize: Sequelize = config.DATABASE;
const GENERAL: any = STRINGS.general;
const msgRetryCounterMap: MessageRetryMap = {};
const logger: Logger = P({ timestamp: () => `,"time":"${new Date().toJSON()}"` }).child({})
logger.level = 'fatal'
// the store maintains the data of the WA connection in memory
// can be written out to a file & read from it
const store = makeInMemoryStore({ logger })
store?.readFromFile('./session.data.json')
// save every 10s
setInterval(() => {
store?.writeToFile('./session.data.json')
}, 10_000);
(async (): Promise<void> => {
console.log(banner);
let commandHandler: Map<string, Command> = new Map();
console.log(chalk.yellowBright.bold("[INFO] Installing Plugins... Please wait."));
let moduleFiles: string[] = fs.readdirSync(join(__dirname, 'modules')).filter((file) => file.endsWith('.js'))
for (let file of moduleFiles) {
try {
const command: Command = (await import(join(__dirname, 'modules', `${file}`))).default;
console.log(
chalk.magentaBright("[INFO] Successfully imported module"),
chalk.cyanBright.bold(`${file}`)
)
commandHandler.set(command.name, command);
} catch (error) {
console.log(
chalk.blueBright.bold("[INFO] Could not import module"),
chalk.redBright.bold(`${file}`)
)
console.log(`[ERROR] `, error);
continue;
}
}
console.log(chalk.green.bold("[INFO] Plugins Installed Successfully. The bot is ready to use."));
console.log(chalk.yellowBright.bold("[INFO] Connecting to Database."));
try {
await sequelize.authenticate();
console.log(chalk.greenBright.bold('[INFO] Connection has been established successfully.'));
} catch (error) {
console.error('[ERROR] Unable to connect to the database:', error);
}
console.log(chalk.yellowBright.bold("[INFO] Syncing Database..."));
await sequelize.sync();
console.log(chalk.greenBright.bold("[INFO] All models were synchronized successfully."));
let firstInit: boolean = true;
const startSock = async () => {
// @ts-ignore
const { state, saveCreds } = await useRemoteFileAuthState.useRemoteFileAuthState();
const { version, isLatest } = await fetchLatestBaileysVersion();
//@ts-ignore
const sock: WASocket = makeWASocket.default({
version,
logger,
printQRInTerminal: true,
auth: state,
browser: ["Athena", "Chrome", "4.0.0"],
msgRetryCounterMap,
// implement to handle retries
getMessage: async key => {
if (store) {
const msg = await store.loadMessage(key.remoteJid!, key.id!)
return msg?.message || undefined
}
return {
conversation: '-pls ignore-'
}
}
});
store?.bind(sock.ev);
let client: Client = new Client(sock, store);
sock.ev.process(
async (events) => {
if (events['connection.update']) {
const update = events['connection.update'];
const { connection, lastDisconnect } = update;
if (connection === 'close') {
if ((lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut) {
startSock()
} else {
console.log(chalk.redBright('Connection closed. You are logged out. Delete the Athena.db and session.data.json files to rescan the code.'));
process.exit(0);
}
} else if (connection === 'connecting') {
console.log(chalk.yellowBright("[INFO] Connecting to WhatsApp..."));
} else if (connection === 'open') {
console.log(chalk.greenBright.bold("[INFO] Connected! Welcome to Athena"));
}
}
if (events['creds.update']) {
await saveCreds()
}
if (events['contacts.upsert']) {
const contacts: Contact[] = events['contacts.upsert'];
const contactsUpdate = (newContacts: Contact[]) => {
for (const contact of newContacts) {
if (store.contacts[contact.id]) {
Object.assign(store.contacts[contact.id], contact);
} else {
store.contacts[contact.id] = contact;
}
}
return;
};
contactsUpdate(contacts);
}
if (events['contacts.update']) {
const contacts: Partial<Contact>[] = events['contacts.update'];
const contactsUpdate = (newContacts) => {
for (const contact of newContacts) {
if (store.contacts[contact.id]) {
Object.assign(store.contacts[contact.id], contact);
} else {
store.contacts[contact.id] = contact;
}
}
return;
};
contactsUpdate(contacts);
}
if (events['messages.upsert']) {
const upsert = events['messages.upsert'];
// console.log(JSON.stringify(upsert, undefined, 2))
if (upsert.type !== 'notify') {
return;
}
for(const msg of upsert.messages){
let chat: proto.IWebMessageInfo = msg;
let Athena: Athena = await resolve(chat, sock);
// console.log(Athena);
if (Athena.isCmd) {
let isBlacklist: boolean = await Blacklist.getBlacklistUser(Athena.sender, Athena.chatId);
const cleared: boolean = await clearance(Athena, client, isBlacklist);
if (!cleared) {
return;
}
const reactionMessage = {
react: {
text: "🪄",
key: chat.key,
}
}
await sock.sendMessage(chat.key.remoteJid, reactionMessage);
console.log(chalk.redBright.bold(`[INFO] ${Athena.commandName} command executed.`));
const command = commandHandler.get(Athena.commandName);
var args = Athena.body.trim().split(/\s+/).slice(1);
if (!command) {
client.sendMessage(Athena.chatId, "```Woops, invalid command! Use``` *.help* ```to display the command list.```", MessageType.text);
return;
} else if (command && Athena.commandName == "help") {
try {
command.handle(client, chat, Athena, args, commandHandler);
return;
} catch (err) {
console.log(chalk.red("[ERROR] ", err));
return;
}
}
try {
await command.handle(client, chat, Athena, args).catch(err => console.log("[ERROR] " + err));
} catch (err) {
console.log(chalk.red("[ERROR] ", err));
}
}
}
}
}
);
return sock;
}
startSock();
})().catch(err => console.log('[MAINERROR] : %s', chalk.redBright.bold(err)));