-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathhisoka.js
267 lines (230 loc) · 8.26 KB
/
hisoka.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
import 'dotenv/config';
import makeWASocket, {
delay,
useMultiFileAuthState,
fetchLatestBaileysVersion,
makeInMemoryStore,
jidNormalizedUser,
DisconnectReason,
Browsers,
makeCacheableSignalKeyStore,
} from 'baileys';
import pino from 'pino';
import { Boom } from '@hapi/boom';
import fs from 'fs';
import os from 'os';
import { exec } from 'child_process';
import treeKill from './lib/tree-kill.js';
import serialize, { Client } from './lib/serialize.js';
import { formatSize, parseFileSize, sendTelegram } from './lib/function.js';
const logger = pino({ timestamp: () => `,"time":"${new Date().toJSON()}"` }).child({ class: 'hisoka' });
logger.level = 'fatal';
const usePairingCode = process.env.PAIRING_NUMBER;
const store = makeInMemoryStore({ logger });
if (process.env.WRITE_STORE === 'true') store.readFromFile(`./${process.env.SESSION_NAME}/store.json`);
// check available file
const pathContacts = `./${process.env.SESSION_NAME}/contacts.json`;
const pathMetadata = `./${process.env.SESSION_NAME}/groupMetadata.json`;
const startSock = async () => {
const { state, saveCreds } = await useMultiFileAuthState(`./${process.env.SESSION_NAME}`);
const { version, isLatest } = await fetchLatestBaileysVersion();
console.log(`using WA v${version.join('.')}, isLatest: ${isLatest}`);
/**
* @type {import('baileys').WASocket}
*/
const hisoka = makeWASocket.default({
version,
logger,
printQRInTerminal: !usePairingCode,
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, logger),
},
browser: Browsers.ubuntu('Chrome'),
markOnlineOnConnect: false,
generateHighQualityLinkPreview: true,
syncFullHistory: true,
retryRequestDelayMs: 10,
transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 10 },
defaultQueryTimeoutMs: undefined,
maxMsgRetryCount: 15,
appStateMacVerification: {
patch: true,
snapshot: true,
},
getMessage: async key => {
const jid = jidNormalizedUser(key.remoteJid);
const msg = await store.loadMessage(jid, key.id);
return msg?.message || '';
},
shouldSyncHistoryMessage: msg => {
console.log(`\x1b[32mMemuat Chat [${msg.progress}%]\x1b[39m`);
return !!msg.syncType;
},
});
store.bind(hisoka.ev);
await Client({ hisoka, store });
// login dengan pairing
if (usePairingCode && !hisoka.authState.creds.registered) {
try {
let phoneNumber = usePairingCode.replace(/[^0-9]/g, '');
await delay(3000);
let code = await hisoka.requestPairingCode(phoneNumber);
console.log(`\x1b[32m${code?.match(/.{1,4}/g)?.join('-') || code}\x1b[39m`);
} catch {
console.error('Gagal mendapatkan kode pairing');
process.exit(1);
}
}
// ngewei info, restart or close
hisoka.ev.on('connection.update', async update => {
const { lastDisconnect, connection } = update;
if (connection) {
console.info(`Connection Status : ${connection}`);
}
if (connection === 'close') {
let reason = new Boom(lastDisconnect?.error)?.output.statusCode;
switch (reason) {
case DisconnectReason.multideviceMismatch:
case DisconnectReason.loggedOut:
case 403:
console.error(lastDisconnect.error?.message);
await hisoka.logout();
fs.rmSync(`./${process.env.SESSION_NAME}`, { recursive: true, force: true });
exec('npm run stop:pm2', err => {
if (err) return treeKill(process.pid);
});
break;
default:
console.error(lastDisconnect.error?.message);
await startSock();
}
}
if (connection === 'open') {
hisoka.sendMessage(jidNormalizedUser(hisoka.user.id), { text: `${hisoka.user?.name} has Connected...` });
}
});
// write session kang
hisoka.ev.on('creds.update', saveCreds);
// contacts
if (fs.existsSync(pathContacts)) {
store.contacts = JSON.parse(fs.readFileSync(pathContacts, 'utf-8'));
} else {
fs.writeFileSync(pathContacts, JSON.stringify({}));
}
// group metadata
if (fs.existsSync(pathMetadata)) {
store.groupMetadata = JSON.parse(fs.readFileSync(pathMetadata, 'utf-8'));
} else {
fs.writeFileSync(pathMetadata, JSON.stringify({}));
}
// add contacts update to store
hisoka.ev.on('contacts.update', update => {
for (let contact of update) {
let id = jidNormalizedUser(contact.id);
if (store && store.contacts) store.contacts[id] = { ...(store.contacts?.[id] || {}), ...(contact || {}) };
}
});
// add contacts upsert to store
hisoka.ev.on('contacts.upsert', update => {
for (let contact of update) {
let id = jidNormalizedUser(contact.id);
if (store && store.contacts) store.contacts[id] = { ...(contact || {}), isContact: true };
}
});
// nambah perubahan grup ke store
hisoka.ev.on('groups.update', updates => {
for (const update of updates) {
const id = update.id;
if (store.groupMetadata[id]) {
store.groupMetadata[id] = { ...(store.groupMetadata[id] || {}), ...(update || {}) };
}
}
});
// merubah status member
hisoka.ev.on('group-participants.update', ({ id, participants, action }) => {
const metadata = store.groupMetadata[id];
if (metadata) {
switch (action) {
case 'add':
case 'revoked_membership_requests':
metadata.participants.push(...participants.map(id => ({ id: jidNormalizedUser(id), admin: null })));
break;
case 'demote':
case 'promote':
for (const participant of metadata.participants) {
let id = jidNormalizedUser(participant.id);
if (participants.includes(id)) {
participant.admin = action === 'promote' ? 'admin' : null;
}
}
break;
case 'remove':
metadata.participants = metadata.participants.filter(p => !participants.includes(jidNormalizedUser(p.id)));
break;
}
}
});
// bagian pepmbaca status ono ng kene
hisoka.ev.on('messages.upsert', async ({ messages }) => {
if (!messages[0].message) return;
let m = await serialize(hisoka, messages[0], store);
// nambah semua metadata ke store
if (store.groupMetadata && Object.keys(store.groupMetadata).length === 0) store.groupMetadata = await hisoka.groupFetchAllParticipating();
// untuk membaca pesan status
if (m.key && !m.key.fromMe && m.key.remoteJid === 'status@broadcast') {
if (m.type === 'protocolMessage' && m.message.protocolMessage.type === 0) return;
await hisoka.readMessages([m.key]);
let id = m.key.participant;
let name = hisoka.getName(id);
// react status
const emojis = process.env.REACT_STATUS.split(',')
.map(e => e.trim())
.filter(Boolean);
if (emojis.length) {
await hisoka.sendMessage(
'status@broadcast',
{
react: { key: m.key, text: emojis[Math.floor(Math.random() * emojis.length)] },
},
{
statusJidList: [jidNormalizedUser(hisoka.user.id), jidNormalizedUser(id)],
}
);
}
if (process.env.TELEGRAM_TOKEN && process.env.ID_TELEGRAM) {
if (m.isMedia) {
let media = await hisoka.downloadMediaMessage(m);
let caption = `Dari : https://wa.me/${id.split('@')[0]} (${name})${m.body ? `\n\n${m.body}` : ''}`;
await sendTelegram(process.env.ID_TELEGRAM, media, { type: /audio/.test(m.msg.mimetype) ? 'document' : '', caption });
} else await sendTelegram(process.env.ID_TELEGRAM, `Dari : https://wa.me/${id.split('@')[0]} (${name})\n\n${m.body}`);
}
}
// status self apa publik
if (process.env.SELF === 'true' && !m.isOwner) return;
// kanggo kes
await (await import(`./message.js?v=${Date.now()}`)).default(hisoka, store, m);
});
setInterval(async () => {
// write contacts and metadata
if (store.groupMetadata) fs.writeFileSync(pathMetadata, JSON.stringify(store.groupMetadata));
if (store.contacts) fs.writeFileSync(pathContacts, JSON.stringify(store.contacts));
// write store
if (process.env.WRITE_STORE === 'true') store.writeToFile(`./${process.env.SESSION_NAME}/store.json`);
// untuk auto restart ketika RAM sisa 300MB
const memoryUsage = os.totalmem() - os.freemem();
if (memoryUsage > os.totalmem() - parseFileSize(process.env.AUTO_RESTART, false)) {
await hisoka.sendMessage(
jidNormalizedUser(hisoka.user.id),
{ text: `penggunaan RAM mencapai *${formatSize(memoryUsage)}* waktunya merestart...` },
{ ephemeralExpiration: 24 * 60 * 60 * 1000 }
);
exec('npm run restart:pm2', err => {
if (err) return process.send('reset');
});
}
}, 10 * 1000); // tiap 10 detik
process.on('uncaughtException', console.error);
process.on('unhandledRejection', console.error);
};
startSock();