From e4151d33cded4cfa6f1ceabc8558e1678f2a0f53 Mon Sep 17 00:00:00 2001 From: BochilGaming <79433517+BochilGaming@users.noreply.github.com> Date: Sun, 11 Dec 2022 08:06:01 +0700 Subject: [PATCH] Fixed a bug --- handler.js | 2 +- lib/connection.js | 53 +++++++------ lib/simple.js | 2 +- lib/store.js | 153 ++----------------------------------- plugins/jadibot-jadibot.js | 75 ------------------ plugins/sticker-sticker.js | 2 +- 6 files changed, 37 insertions(+), 250 deletions(-) delete mode 100644 plugins/jadibot-jadibot.js diff --git a/handler.js b/handler.js index 55a3bfd2e..7a7a023df 100644 --- a/handler.js +++ b/handler.js @@ -12,7 +12,7 @@ import db, { loadDatabase } from './lib/database.js' import Queque from './lib/queque.js' /** @type {import('@adiwajshing/baileys')} */ -const { getContentType, proto } = (await import('@adiwajshing/baileys')).default +const { getContentType } = (await import('@adiwajshing/baileys')).default const isNumber = x => typeof x === 'number' && !isNaN(x) /** diff --git a/lib/connection.js b/lib/connection.js index 6972af263..85fb55617 100644 --- a/lib/connection.js +++ b/lib/connection.js @@ -14,6 +14,7 @@ import P from 'pino' const { DisconnectReason, default: makeWASocket, + useMultiFileAuthState // useSingleFileAuthState } = (await import('@adiwajshing/baileys')).default @@ -27,7 +28,7 @@ let [ ] = await Promise.all([ Helper.checkFileExists(authFolder + '/creds.json'), Helper.checkFileExists(authFile), - storeSystem.useMultiFileAuthState(authFolder) + useMultiFileAuthState(authFolder) ]) const store = storeSystem.makeInMemoryStore() @@ -38,7 +39,7 @@ if (Helper.opts['singleauth'] || Helper.opts['singleauthstate']) { console.debug('- singleauth -', 'creds.json not found', 'compiling singleauth to multiauth...') await single2multi(authFile, authFolder, authState) console.debug('- singleauth -', 'compiled successfully') - authState = await storeSystem.useMultiFileAuthState(authFolder) + authState = await useMultiFileAuthState(authFolder) } else if (!isAuthSingleFileExist) console.error('- singleauth -', 'singleauth file not found') } @@ -63,7 +64,7 @@ const connectionOptions = { * participantsUpdate?: typeof import('../handler').participantsUpdate; * groupsUpdate?: typeof import('../handler').groupsUpdate; * onDelete?:typeof import('../handler').deleteUpdate; - * connectionUpdate?: typeof connectionUpdate; + * connectionUpdate?: (update: import('@adiwajshing/baileys').BaileysEventMap['connection.update']) => any; * credsUpdate?: () => void * }} EventHandlers * @typedef {Required['logger']} Logger @@ -73,6 +74,14 @@ const connectionOptions = { * msgqueque?: import('./queque').default; * logger?: Logger * }} Socket + * @typedef {{ + * handler?: Promise | typeof import('../handler'); + * isChild?: boolean; + * connectionOptions?: Partial; + * logger?: Logger; + * store: typeof store; + * authState: Awaited> + * }} StartOptions */ @@ -80,18 +89,15 @@ const connectionOptions = { let conns = new Map(); /** * @param {Socket?} oldSocket - * @param {{ - * handler?: typeof import('../handler'); - * isChild?: boolean; - * connectionOptions?: Partial; - * store: typeof store - * }} opts + * @param {StartOptions} opts */ -async function start(oldSocket = null, opts = { store }) { +async function start(oldSocket = null, opts = { store, logger, authState }) { /** @type {Socket} */ let conn = makeWASocket({ ...connectionOptions, ...opts.connectionOptions, + logger: opts.logger, + auth: opts.authState.state, getMessage: async (key) => ( opts.store.loadMessage(/** @type {string} */(key.remoteJid), key.id) || opts.store.loadMessage(/** @type {string} */(key.id)) || {} @@ -121,12 +127,9 @@ let OldHandler = null /** * @param {Socket} conn * @param {boolean} restartConnection - * @param {{ - * handler?: Promise | typeof import('../handler'); - * isChild?: boolean - * }} opts + * @param {StartOptions} opts */ -async function reload(conn, restartConnection, opts = {}) { +async function reload(conn, restartConnection, opts = { store, authState }) { if (!opts.handler) opts.handler = importFile(Helper.__filename(path.resolve('./handler.js'))).catch(console.error) if (opts.handler instanceof Promise) opts.handler = await opts.handler; if (!opts.handler && OldHandler) opts.handler = OldHandler @@ -137,7 +140,7 @@ async function reload(conn, restartConnection, opts = {}) { try { conn.ws.close() } catch { } // @ts-ignore conn.ev.removeAllListeners() - Object.assign(conn, await start(conn) || {}) + Object.assign(conn, await start(conn, opts) || {}) } // Assign message like welcome, bye, etc.. to the connection @@ -157,9 +160,8 @@ async function reload(conn, restartConnection, opts = {}) { conn.groupsUpdate = /** @type {typeof import('../handler')} */(opts.handler).groupsUpdate.bind(conn) conn.onDelete = /** @type {typeof import('../handler')} */(opts.handler).deleteUpdate.bind(conn) } - if (!opts.isChild) conn.connectionUpdate = connectionUpdate.bind(conn) - conn.credsUpdate = authState.saveCreds.bind(conn) - // conn.credsUpdate = authState.saveState.bind(conn) + if (!opts.isChild) conn.connectionUpdate = connectionUpdate.bind(conn, opts) + conn.credsUpdate = opts.authState.saveCreds.bind(conn) /** @typedef {Required} Event */ conn.ev.on('messages.upsert', /** @type {Event} */(conn).handler) @@ -176,16 +178,17 @@ async function reload(conn, restartConnection, opts = {}) { /** * @this {Socket} + * @param {StartOptions} opts * @param {import('@adiwajshing/baileys').BaileysEventMap['connection.update']} update */ -async function connectionUpdate(update) { - console.log(update) +async function connectionUpdate(opts, update) { + opts.logger?.info(update) const { connection, lastDisconnect, isNewLogin } = update - if (isNewLogin) this.isInit = true + // if (isNewLogin) this.isInit = true // @ts-ignore const code = lastDisconnect?.error?.output?.statusCode || lastDisconnect?.error?.output?.payload?.statusCode if (code && code !== DisconnectReason.loggedOut && this?.ws.readyState !== ws.CONNECTING) { - console.log(await reload(this, true).catch(console.error)) + console.log(await reload(this, true, opts).catch(console.error)) global.timestamp.connect = new Date } if (connection == 'open') console.log('- opened connection -') @@ -215,8 +218,8 @@ function getMessageConfig() { } } -const conn = start(null, { store }).catch(console.error) - +const conn = start(null, { store, logger, authState }) + .catch(console.error) export default { start, diff --git a/lib/simple.js b/lib/simple.js index 53eb6cfe1..9c61f4c2d 100644 --- a/lib/simple.js +++ b/lib/simple.js @@ -60,7 +60,7 @@ export function HelperConnection(conn, { store, logger }) { trace: logger.trace?.bind(logger) }, enumerable: true, - writable: false + writable: true }, getFile: { /** diff --git a/lib/store.js b/lib/store.js index c0fa609aa..f3487bea5 100644 --- a/lib/store.js +++ b/lib/store.js @@ -1,6 +1,9 @@ // @ts-check -import { readFileSync, writeFileSync, existsSync, promises } from 'fs' -import { join } from 'path' +import { + readFileSync, + writeFileSync, + existsSync +} from 'fs' /** @type {typeof import('@adiwajshing/baileys')} */ // @ts-ignore const { @@ -12,8 +15,6 @@ const { WAMessageStubType, updateMessageWithReceipt, updateMessageWithReaction, - // @ts-ignore - useMultiFileAuthState: baileysMultiFileAuthState } = (await import('@adiwajshing/baileys')).default const TIME_TO_DATA_STALE = 5 * 60 * 1000 @@ -384,151 +385,9 @@ function JSONreplacer(key, value) { const fixFileName = (file) => file?.replace(/\//g, '__')?.replace(/:/g, '-') -/** - * @typedef {typeof baileysMultiFileAuthState} MultiFileAuthStateStore - */ -/** @type {MultiFileAuthStateStore} */ -const useMultiFileAuthState = baileysMultiFileAuthState || - /** - * Re implement useMultiFileAuthState if baileysMultiFileAuthState is undefined - * @type {MultiFileAuthStateStore} - */ - async function useMultiFileAuthState(folder) { - - const writeData = (data, file) => { - return promises.writeFile(join(folder, fixFileName(file)), JSON.stringify(data, JSONreplacer)) - } - - const readData = async (file) => { - try { - const data = await promises.readFile(join(folder, fixFileName(file)), { encoding: 'utf-8' }) - return JSON.parse(data, BufferJSON.reviver) - } catch (error) { - return null - } - } - - const removeData = async (file) => { - try { - await promises.unlink(fixFileName(file)) - } catch { - - } - } - - const folderInfo = await promises.stat(folder).catch(() => { }) - if (folderInfo) { - if (!folderInfo.isDirectory()) { - throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`) - } - } else { - await promises.mkdir(folder, { recursive: true }) - } - - const creds = await readData('creds.json') || initAuthCreds() - - return { - state: { - creds, - keys: { - // @ts-ignore - get: async (type, ids) => { - const data = {} - await Promise.all( - ids.map( - async id => { - let value = await readData(`${type}-${id}.json`) - if (type === 'app-state-sync-key') { - value = proto.AppStateSyncKeyData.fromObject(value) - } - - data[id] = value - } - ) - ) - - return data - }, - set: async (data) => { - const tasks = [] - for (const category in data) { - for (const id in data[category]) { - const value = data[category][id] - const file = `${category}-${id}.json` - tasks.push(value ? writeData(value, file) : removeData(file)) - } - } - - await Promise.all(tasks) - } - } - }, - saveCreds: () => { - return writeData(creds, 'creds.json') - } - } - } - -const KEY_MAP = { - 'pre-key': 'preKeys', - 'session': 'sessions', - 'sender-key': 'senderKeys', - 'app-state-sync-key': 'appStateSyncKeys', - 'app-state-sync-version': 'appStateVersions', - 'sender-key-memory': 'senderKeyMemory' -} - -/** - * - * @returns {ReturnType} - */ -const useMemoryAuthState = function useMemoryAuthState() { - const creds = initAuthCreds() - const keys = {} - - const saveCreds = () => undefined - return { - state: { - creds, - keys: { - get: (type, ids) => { - const key = KEY_MAP[type] - return ids.reduce( - (dict, id) => { - // @ts-ignore - let value = keys[key]?.[id] - if (value) { - if (type === 'app-state-sync-key') { - value = proto.AppStateSyncKeyData.fromObject(value) - } - - dict[id] = value - } - - return dict - }, {} - ) - }, - set: (data) => { - for (const _key in data) { - const key = KEY_MAP[_key] - keys[key] = keys[key] || {} - Object.assign(keys[key], data[_key]) - } - } - } - }, - // @ts-ignore - saveCreds - } -} export default { makeInMemoryStore, - useMultiFileAuthState, - useMemoryAuthState, fixFileName, - JSONreplacer, - - KEY_MAP + JSONreplacer } diff --git a/plugins/jadibot-jadibot.js b/plugins/jadibot-jadibot.js deleted file mode 100644 index e619831f0..000000000 --- a/plugins/jadibot-jadibot.js +++ /dev/null @@ -1,75 +0,0 @@ -// TODO: fix jadibot - -import Connection from '../lib/connection.js' -import Store from '../lib/store.js' -import qrcode from 'qrcode' -import ws from 'ws' - -const { DisconnectReason } = await import('@adiwajshing/baileys') - -let handler = async (m, { conn: _conn, args, usedPrefix, command, isOwner }) => { - /** @type {import('../lib/connection').Socket} */ - let parent = args[0] && args[0] == 'plz' ? _conn : await Connection.conn - if (!((args[0] && args[0] == 'plz') || (await Connection.conn).user.jid == _conn.user.jid)) { - throw 'Tidak bisa membuat bot didalam bot!\n\nhttps://wa.me/' + (await Connection.conn).user.jid.split`@`[0] + '?text=.jadibot' - } - - const id = Connection.conns.size - const auth = Store.useMemoryAuthState() - const store = Store.makeInMemoryStore() - const conn = await Connection.start(null, { - isChild: true, - connectionOptions: { auth: auth.state }, - store - }) - const logout = async () => { - await parent.sendMessage(conn.user?.jid || m.chat, { text: 'Koneksi terputus...' }) - try { conn.ws.close() } catch { } - Connection.conns.delete(id) - } - let lastQr, shouldSendLogin, errorCount = 0 - conn.ev.on('connection.update', async ({ qr, isNewLogin, lastDisconnect }) => { - if (shouldSendLogin && conn.user) { - await parent.sendMessage(conn.user.jid, { text: 'Berhasil tersambung dengan WhatsApp - mu.\n*NOTE: Ini cuma numpang*\n' + JSON.stringify(conn.user, null, 2) }, { quoted: m }) - } - if (qr) { - if (lastQr) lastQr.delete() - lastQr = await parent.sendFile(m.chat, await qrcode.toDataURL(qr, { scale: 8 }), 'qrcode.png', ` -Scan QR ini untuk jadi bot sementara -1. Klik titik tiga di pojok kanan atas -2. Ketuk perangkat tertaut -3. Scan QR ini - -QR akan Expired ! -`.trim(), m) - } - if (isNewLogin) - shouldSendLogin = true - - if (lastDisconnect) { - const code = lastDisconnect?.error?.output?.statusCode || lastDisconnect?.error?.output?.payload?.statusCode - if (code && code !== DisconnectReason.loggedOut && conn?.ws.readyState !== ws.CONNECTING) { - console.log(await Connection.reload(conn, true, { isChild: true }).catch(console.error)) - } else if (code == DisconnectReason.loggedOut) - logout() - errorCount++; - } - - if (errorCount > 5) - logout() - - }) - - Connection.conns.set(id, conn) -} - - -handler.help = ['jadibot'] -handler.tags = ['jadibot'] - -handler.command = /^jadibot$/i - -handler.disabled = true -handler.limit = true - -export default handler \ No newline at end of file diff --git a/plugins/sticker-sticker.js b/plugins/sticker-sticker.js index 59433f387..9410d3484 100644 --- a/plugins/sticker-sticker.js +++ b/plugins/sticker-sticker.js @@ -12,13 +12,13 @@ let handler = async (m, { conn, args, usedPrefix, command }) => { if (/video/g.test(mime)) if ((q.msg || q).seconds > 11) return m.reply('Maksimal 10 detik!') let img = await q.download?.() if (!img) throw `balas gambar/video/stiker dengan perintah ${usedPrefix + command}` - let out try { stiker = await sticker(img, false, global.packname, global.author) } catch (e) { console.error(e) } finally { if (!stiker) { + let out if (/webp/g.test(mime)) out = await webp2png(img) else if (/video/g.test(mime)) out = await uploadFile(img) if (!out || typeof out !== 'string') out = await uploadImage(img)