-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathindex.js
163 lines (142 loc) · 6.54 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
require("./global")
const P = require ('pino')
const { Boom } = require ('@hapi/boom')
const { default: makeWASocket, delay, DisconnectReason, fetchLatestBaileysVersion, makeInMemoryStore, useMultiFileAuthState, useSingleFileAuthState, jidNormalizedUser } = require ('@whiskeysockets/baileys')
const fs = require("fs")
const path = require("path")
const cron = require('node-cron')
const { Collection, Simple, Store } = require("./lib")
const Welcome = require("./lib/Welcome")
const config = JSON.parse(fs.readFileSync('./config.json'))
const { serialize, WAConnection } = Simple
const Commands = new Collection()
global.prefa = /^[#$+.?_&<>!/\\]/
Commands.prefix = prefa
const store = makeInMemoryStore({ logger: P().child({ level: 'silent', stream: 'store' }) })
store.readFromFile('./session/baileys_store.json')
setInterval(() => {
store.writeToFile('./session/baileys_store.json')
}, 10000)
global.api = (name, path = '/', query = {}, apikeyqueryname) => (name in config.APIs ? config.APIs[name] : name) + path + (query || apikeyqueryname ? '?' + new URLSearchParams(Object.entries({ ...query, ...(apikeyqueryname ? { [apikeyqueryname]: config.APIs.apikey } : {}) })) : '')
const readCommands = () => {
let dir = path.join(__dirname, "./commands")
let dirs = fs.readdirSync(dir)
let listCommand = {}
try {
dirs.forEach(async (res) => {
let groups = res.toLowerCase()
Commands.type = dirs.filter(v => v !== "_").map(v => v)
listCommand[groups] = []
let files = fs.readdirSync(`${dir}/${res}`).filter((file) => file.endsWith(".js"))
//console.log(files)
for (const file of files) {
const command = require(`${dir}/${res}/${file}`)
listCommand[groups].push(command)
Commands.set(command.name, command)
delay(100)
}
})
Commands.list = listCommand
} catch (e) {
console.error(e)
}
}
const connect = async () => {
await readCommands()
let { state, saveCreds } = await useMultiFileAuthState(path.resolve('./session'))
let { version, isLatest } = await fetchLatestBaileysVersion()
console.log(`using WA v${version.join('.')}, isLatest: ${isLatest}`)
let connOptions = {
version,
logger: P({ level: 'silent' }),
printQRInTerminal: true,
markOnlineOnConnect: false,
patchMessageBeforeSending: (message) => {
const requiresPatch = !!(
message.buttonsMessage
|| message.templateMessage
|| message.listMessage
);
if (requiresPatch) {
message = {
viewOnceMessage: {
message: {
messageContextInfo: {
deviceListMetadataVersion: 2,
deviceListMetadata: {},
},
...message,
},
},
};
}
return message;
},
auth: state,
syncFullHistory: true
}
const killua = new WAConnection(makeWASocket(connOptions))
//global.Store = Store.bind(killua)
killua.ev.on("creds.update", saveCreds)
killua.ev.on("connection.update", async(update) => {
if (update.connection == "open" && killua.type == "legacy") {
killua.user = {
id: killua.state.legacy.user.id,
jid: killua.state.legacy.user.id,
name: killua.state.legacy.user.name
}
}
const { lastDisconnect, connection } = update
if (connection) {
console.info(`Connection Status : ${connection}`)
}
if (connection == "close") {
let reason = new Boom(lastDisconnect?.error)?.output.statusCode
if (reason === DisconnectReason.badSession) { console.log(`Bad Session File, Please Delete Session and Scan Again`); killua.logout(); }
else if (reason === DisconnectReason.connectionClosed) { console.log("Connection closed, reconnecting...."); connect(); }
else if (reason === DisconnectReason.connectionLost) { console.log("Connection Lost from Server, reconnecting..."); connect(); }
else if (reason === DisconnectReason.connectionReplaced) { console.log("Connection Replaced, Another New Session Opened, Please Close Current Session First"); killua.logout(); }
else if (reason === DisconnectReason.loggedOut) { console.log(`Device Logged Out, Please Scan Again And Run.`); process.exit(); }
else if (reason === DisconnectReason.restartRequired) { console.log("Restart Required, Restarting..."); connect(); }
else if (reason === DisconnectReason.timedOut) { console.log("Connection TimedOut, Reconnecting..."); connect(); }
else killua.end(`Unknown DisconnectReason: ${reason}|${connection}`)
}
})
// Welcome
killua.ev.on("group-participants.update", async (m) => {
Welcome(killua, m)
})
killua.ev.on("messages.upsert", async (chatUpdate) => {
m = serialize(killua, chatUpdate.messages[0])
if (!m.message) return
if (m.key && m.key.remoteJid == "status@broadcast") return
if (m.key.id.startsWith("BAE5") && m.key.id.length == 16) return
if (config.options.autoRead) await killua.readMessages([m.key])
require("./killua")(killua, m, Commands, chatUpdate)
})
if (killua.user && killua.user?.id) killua.user.jid = jidNormalizedUser(killua.user?.id)
return killua
}
cron.schedule('0 0 * * *', () => {
var folder = './temp/'
fs.readdir(folder, (err, files) => {
if (err) throw err
for (const file of files) {
console.log(file + ' : File Deleted Successfully.')
fs.unlink(folder + file, function (err) {
if (err && err.code == 'ENOENT') {
console.info("File doesn't exist, won't remove it.");
} else if (err) {
console.error("Error occurred while trying to remove file");
} else {
console.info(`removed`);
}
});
}
})
console.log('Success Deleted temp Folder')
}, {
scheduled: true,
timezone: config.timezone
})
connect()