testingba / handler.js
Ikygantengbangetanjay's picture
Upload folder using huggingface_hub
5fb4b36 verified
Raw History Blame Contribute Delete
23.8 kB
const simple = require('./lib/simple')
const util = require('util')
const { color } = require('./lib/color')
const moment = require("moment-timezone")
const fetch = require("node-fetch")
const isNumber = x => typeof x === 'number' && !isNaN(x)
const delay = ms => isNumber(ms) && new Promise(resolve => setTimeout(resolve, ms))
module.exports = {
async handler(chatUpdate) {
if (global.db.data == null) await loadDatabase()
this.msgqueque = this.msgqueque || []
// console.log(chatUpdate)
if (!chatUpdate) return
//this.pushMessage(chatUpdate.messages).catch(console.error)
// if (!(chatUpdate.type === 'notify' || chatUpdate.type === 'append')) return
let m = chatUpdate.messages[chatUpdate.messages.length - 1]
global.settings = global.db.data.settings
global.fkontak = global.fkontak
if (!m) return
// console.log(m)
try {
m = simple.smsg(this, m) || m
if (!m) return
// console.log(m)
m.exp = 0
m.limit = false
try {
let user = global.db.data.users[m.sender]
if (typeof user !== 'object') global.db.data.users[m.sender] = {}
if (user) {
} else global.db.data.users[m.sender] = {
}
let chat = global.db.data.chats[m.chat]
if (typeof chat !== 'object') global.db.data.chats[m.chat] = {}
if (chat) {
if (!('isBanned' in chat)) chat.isBanned = false
if (!('welcome' in chat)) chat.welcome = false
if (!('autoread' in chat)) chat.autoread = false
if (!('detect' in chat)) chat.detect = false
if (!('sWelcome' in chat)) chat.sWelcome = 'Selamat datang @user!'
if (!('sBye' in chat)) chat.sBye = ''
if (!('sPromote' in chat)) chat.sPromote = '@user telah di promote'
if (!('sDemote' in chat)) chat.sDemote = '@user telah di demote'
if (!('delete' in chat)) chat.delete = true
if (!('antiVirtex' in chat)) chat.antiVirtex = false
if (!('antiLink' in chat)) chat.antiLink = false
if (!('badword' in chat)) chat.badword = false
if (!('antiSpam' in chat)) chat.antiSpam = false
if (!('freply' in chat)) chat.freply = false
if (!('antiSticker' in chat)) chat.antiSticker = false
if (!('stiker' in chat)) chat.stiker = false
if (!('viewonce' in chat)) chat.viewonce = false
if (!('useDocument' in chat)) chat.useDocument = false
if (!('antiToxic' in chat)) chat.antiToxic = false
if (!isNumber(chat.expired)) chat.expired = 0
} else global.db.data.chats[m.chat] = {
isBanned: false,
welcome: false,
autoread: false,
detect: false,
sWelcome: '',
sBye: '',
sPromote: '@user telah di promote!',
sDemote: '@user telah di demote',
delete: true,
antiLink: false,
stiker: false,
antiSticker: false,
antiSpam: false,
freply: false,
viewonce: false,
useDocument: false,
antiToxic: false,
expired: 0,
}
let settings = global.db.data.settings[this.user.jid]
if (typeof settings !== 'object') global.db.data.settings[this.user.jid] = {}
if (settings) {
if (!('self' in settings)) settings.self = false
if (!('autoread' in settings)) settings.autoread = false
if (!('restrict' in settings)) settings.restrict = true
if (!('autorestart' in settings)) settings.autorestart = true
if (!('restartDB' in settings)) settings.restartDB = 0
if (!isNumber(settings.status)) settings.status = 0 // ini buat data set Status, tambah disini
if (!('anticall' in settings)) settings.anticall = true
if (!('clear' in settings)) settings.clear = true
if (!isNumber(settings.clearTime)) settings.clearTime = 0
if (!('freply' in settings)) settings.freply = true
} else global.db.data.settings[this.user.jid] = {
self: false,
autoread: false,
restrict: true,
autorestart: true,
restartDB: 0,
status: 0, // disini juga,
anticall: true, // anticall on apa off?
clear: true,
clearTime: 0,
freply: true
}
} catch (e) {
console.error(e)
}
/*if (db.data.settings[this.user.jid].autoread) await this.readMessages([m.key])*/
if (opts['nyimak']) return
if (!m.fromMe && opts['self']) return
if (opts['pconly'] && m.chat.endsWith('g.us')) return
if (opts['gconly'] && !m.chat.endsWith('g.us')) return
if (opts['swonly'] && m.chat !== 'status@broadcast') return
if (typeof m.text !== 'string') m.text = ''
const isROwner = [conn.decodeJid(global.conn.user.id), ...global.owner.map(([number, isCreator, isDeveloper]) => number)].map(v => v.replace(/[^0-9]/g, '') + '@s.whatsapp.net').includes(m.sender)
const isOwner = isROwner || m.fromMe
const isPrems = global.db.data.users[m.sender].premium
const isBans = global.db.data.users[m.sender].banned
if (opts['queque'] && m.text && !(isMods || isPrems)) {
let queque = this.msgqueque, time = 1000 * 5
const previousID = queque[queque.length - 1]
queque.push(m.id || m.key.id)
setInterval(async function () {
if (queque.indexOf(previousID) === -1) clearInterval(this)
else await delay(time)
}, time)
}
if (m.isBaileys) return
m.exp += Math.ceil(Math.random() * 10)
let usedPrefix
let _user = global.db.data && global.db.data.users && global.db.data.users[m.sender]
const groupMetadata = (m.isGroup ? (conn.chats[m.chat] || {}).metadata : {}) || {}
const participants = (m.isGroup ? groupMetadata.participants : []) || []
const user = (m.isGroup ? participants.find(u => conn.decodeJid(u.id) === m.sender) : {}) || {} // User Data
const bot = (m.isGroup ? participants.find(u => conn.decodeJid(u.id) == this.user.jid) : {}) || {} // Your Data
const isRAdmin = user && user.admin == 'superadmin' || false
const isAdmin = isRAdmin || user && user.admin == 'admin' || false // Is User Admin?
const isBotAdmin = bot && bot.admin || false // Are you Admin?
for (let name in global.plugins) {
let plugins = global.plugins[name]
if (!plugins) continue
if (plugins.disabled) continue
if (typeof plugins.all === 'function') {
try {
await plugins.all.call(this, m, chatUpdate)
} catch (e) {
// if (typeof e === 'string') continue
console.error(e)
}
}
if (!opts['restrict']) if (plugins.tags && plugins.tags.includes('admin')) {
global.dfail('restrict', m, this)
continue
}
const str2Regex = str => str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
let _prefix = plugins.customPrefix ? plugins.customPrefix : conn.prefix ? conn.prefix : global.prefix
let match = (_prefix instanceof RegExp ? // RegExp Mode?
[[_prefix.exec(m.text), _prefix]] :
Array.isArray(_prefix) ? // Array?
_prefix.map(p => {
let re = p instanceof RegExp ? // RegExp in Array?
p :
new RegExp(str2Regex(p))
return [re.exec(m.text), re]
}) :
typeof _prefix === 'string' ? // String?
[[new RegExp(str2Regex(_prefix)).exec(m.text), new RegExp(str2Regex(_prefix))]] :
[[[], new RegExp]]
).find(p => p[1])
if (typeof plugins.before === 'function') if (await plugins.before.call(this, m, {
match,
conn: this,
participants,
groupMetadata,
user,
bot,
isROwner,
isOwner,
isRAdmin,
isAdmin,
isBotAdmin,
isPrems,
isBans,
chatUpdate,
})) continue
if (typeof plugins !== 'function') continue
if ((usedPrefix = (match[0] || '')[0])) {
let noPrefix = m.text.replace(usedPrefix, '')
let [command, ...args] = noPrefix.trim().split` `.filter(v => v)
args = args || []
let _args = noPrefix.trim().split` `.slice(1)
let text = _args.join` `
command = (command || '').toLowerCase()
let fail = plugins.fail || global.dfail // When failed
let isAccept = plugins.command instanceof RegExp ? // RegExp Mode?
plugins.command.test(command) :
Array.isArray(plugins.command) ? // Array?
plugins.command.some(cmd => cmd instanceof RegExp ? // RegExp in Array?
cmd.test(command) :
cmd === command
) :
typeof plugins.command === 'string' ? // String?
plugins.command === command :
false
if (!isAccept) continue
m.plugins = name
if (m.chat in global.db.data.chats || m.sender in global.db.data.users) {
let chat = global.db.data.chats[m.chat]
let user = global.db.data.users[m.sender]
if (name != 'unbanchat.js' && chat && chat.isBanned) return // Except this
if (name != 'unbanuser.js' && user && user.banned) return
}
if (plugins.rowner && plugins.owner && !(isROwner || isOwner)) { // Both Owner
fail('owner', m, this)
continue
}
if (plugins.rowner && !isROwner) { // Real Owner
fail('rowner', m, this)
continue
}
if (plugins.owner && !isOwner) { // Number Owner
fail('owner', m, this)
continue
}
if (plugins.mods && !isMods) { // Moderator
fail('mods', m, this)
continue
}
if (plugins.premium && !isPrems) { // Premium
fail('premium', m, this)
continue
}
if (plugins.banned && !isBans) { // Banned
fail('banned', m, this)
continue
}
if (plugins.group && !m.isGroup) { // Group Only
fail('group', m, this)
continue
} else if (plugins.botAdmin && !isBotAdmin) { // You Admin
fail('botAdmin', m, this)
continue
} else if (plugins.admin && !isAdmin) { // User Admin
fail('admin', m, this)
continue
}
if (plugins.private && m.isGroup) { // Private Chat Only
fail('private', m, this)
continue
}
if (plugins.register == true && _user.registered == false) { // Butuh daftar?
fail('unreg', m, this)
continue
}
m.isCommand = true
let xp = 'exp' in plugins ? parseInt(plugins.exp) : 17 // XP Earning per command
if (xp > 9999999999999999999999) m.reply('Ngecit -_-') // Hehehe
else m.exp += xp
if (!isPrems && plugins.limit && global.db.data.users[m.sender].limit < plugins.limit * 1) {
// this.reply(m.chat, `Limit anda habis, silahkan beli melalui *${usedPrefix}buy*`, m)
this.sendButton(m.chat, `Limit anda habis, silahkan beli melalui *${usedPrefix}buyall* atau *${usedPrefix}hadiah*`, author, null, [['Buy Limit', '/buyall'], ['Hadiah', '/hadiah']], m)
continue // Limit habis
}
if (plugins.level > _user.level) {
this.reply(m.chat, `diperlukan level ${plugins.level} untuk menggunakan perintah ini. Level kamu ${_user.level}`, m)
continue // If the level has not been reached
}
let extra = {
match,
usedPrefix,
noPrefix,
_args,
args,
command,
text,
conn: this,
participants,
groupMetadata,
user,
bot,
isROwner,
isOwner,
isRAdmin,
isAdmin,
isBotAdmin,
isPrems,
isBans,
chatUpdate,
}
try {
await plugins.call(this, m, extra)
if (!isPrems) m.limit = m.limit || plugins.limit || true
} catch (e) {
// Error occured
m.error = e
console.error(e)
if (e) {
let text = util.format(e)
for (let key of Object.values(global.APIKeys))
text = text.replace(new RegExp(key, 'g'), '#HIDDEN#')
if (e.name) for (let [jid] of global.owner.filter(([number, isCreator, isDeveloper]) => isDeveloper && number)) {
let data = (await conn.onWhatsApp(jid))[0] || {}
if (data.exists) m.reply(`*File:* ${m.plugins}\n*Sender:* ${m.sender}\n*Chat:* ${m.chat}\n*Command:* ${usedPrefix}${command} ${args.join(' ')}\n\n\`\`\`${text}\`\`\``.trim(), data.jid)
}
m.reply(text)
}
} finally {
// m.reply(util.format(_user))
if (typeof plugins.after === 'function') {
try {
await plugins.after.call(this, m, extra)
} catch (e) {
console.error(e)
}
}
// if (m.limit) m.reply(+ m.limit + ' Limit terpakai')
}
break
}
}
} catch (e) {
console.error(e)
} finally {
if (opts['queque'] && m.text) {
const quequeIndex = this.msgqueque.indexOf(m.id || m.key.id)
if (quequeIndex !== -1) this.msgqueque.splice(quequeIndex, 1)
}
//console.log(global.db.data.users[m.sender])
let user, stats = global.db.data.stats
if (m) {
if (m.sender && (user = global.db.data.users[m.sender])) {
user.exp += m.exp
user.limit -= m.limit * 1
}
let stat
if (m.plugins) {
let now = + new Date
if (m.plugins in stats) {
stat = stats[m.plugins]
if (!isNumber(stat.total)) stat.total = 1
if (!isNumber(stat.success)) stat.success = m.error != null ? 0 : 1
if (!isNumber(stat.last)) stat.last = now
if (!isNumber(stat.lastSuccess)) stat.lastSuccess = m.error != null ? 0 : now
} else stat = stats[m.plugins] = {
total: 1,
success: m.error != null ? 0 : 1,
last: now,
lastSuccess: m.error != null ? 0 : now
}
stat.total += 1
stat.last = now
if (m.error == null) {
stat.success += 1
stat.lastSuccess = now
}
}
}
try {
require('./lib/print')(m, this)
} catch (e) {
console.log(m, m.quoted, e)
}
/*if (opts['autoread']) await this.chatRead(m.chat, m.isGroup ? m.sender : undefined, m.id || m.key.id).catch(() => { })*/
}
},
async participantsUpdate({ id, participants, action }) {
if (opts['self']) return
if (global.isInit) return
let chat = global.db.data.chats[id] || {}
let text = ''
switch (action) {
case 'add':
case 'remove':
if (chat.welcome) {
let groupMetadata = await this.groupMetadata(id) || (conn.chats[id] || {}).metadata
for (let user of participants) {
let pp = './src/avatar_contact.png'
pp: pp
try {
pp = await this.profilePictureUrl(user, 'image')
} catch (e) {
} finally {
text = (action === 'add' ? (chat.sWelcome || this.welcome || conn.welcome || 'Welcome, @user!').replace('@subject', await this.getName(id)).replace('@desc', groupMetadata.desc ? String.fromCharCode(8206).repeat(4001) + groupMetadata.desc : '') :
(chat.sBye || this.bye || conn.bye || 'Bye, @user!')).replace('@user', await this.getName(user))
this.sendFile(id, action === 'add' ? 'Selamat datang @user 👋' : 'Selamat tinggal @user 👋', 'pp.jpg', text, null, false, { mentions: [user] })
}
}
}
break
case 'promote':
text = (chat.sPromote || this.spromote || conn.spromote || '@user sekarang admin!')
case 'demote':
if (!text)
text = (chat.sDemote || this.sdemote || conn.sdemote || '@user sekarang bukan admin!')
text = text.replace('@user', '@' + participants[0].split('@')[0])
if (chat.detect)
this.sendMessage(id, { text, mentions: this.parseMention(text) })
break
}
},
async delete({ remoteJid, fromMe, id, participant }) {
if (fromMe) return
let chats = Object.entries(conn.chats).find(([user, data]) => data.messages && data.messages[id])
if (!chats) return
let msg = JSON.parse(chats[1].messages[id])
let chat = global.db.data.chats[msg.key.remoteJid] || {}
if (chat.delete) return
await this.reply(msg.key.remoteJid, `
Terdeteksi @${participant.split`@`[0]} telah menghapus pesan
Untuk mematikan fitur ini, ketik
*.enable delete*
`.trim(), msg, {
mentions: [participant]
})
this.copyNForward(msg.key.remoteJid, msg).catch(e => console.log(e, msg))
},
async onCall(json) {
if (!db.data.settings[this.user.jid].anticall) return
let jid = json[2][0][1]['from']
let isOffer = json[2][0][2][0][0] == 'offer'
let users = global.db.data.users
let user = users[jid] || {}
if (user.whitelist) return
if (jid && isOffer) {
const tag = this.generateMessageTag()
const nodePayload = ['action', 'call', ['call', {
'from': this.user.jid,
'to': `${jid.split`@`[0]}@s.whatsapp.net`,
'id': tag
}, [['reject', {
'call-id': json[2][0][2][0][1]['call-id'],
'call-creator': `${jid.split`@`[0]}@s.whatsapp.net`,
'count': '0'
}, null]]]]
this.sendJSON(nodePayload, tag)
m.reply(`Kamu dibanned karena menelepon bot, owner : @${global.owner[0][0]}`)
}
},
async GroupUpdate({ jid, desc, descId, descTime, descOwner, announce }) {
if (!db.data.chats[jid].desc) return
if (!desc) return
let caption = `
@${descOwner.split`@`[0]} telah mengubah deskripsi grup.
${desc}
`.trim()
this.sendMessage(jid, caption, info.wm, m)
}
},
global.dfail = (type, m, conn) => {
let msg = {
rowner: `${global.msg.danied}\n\nPerintah ini hanya dapat digunakan oleh *Real Owner*!`,
owner: `${global.msg.danied}\n\nPerintah ini hanya dapat digunakan oleh *Owner*!`,
banned: `${global.msg.danied}\n\nPerintah ini hanya untuk pengguna yang terbanned..`,
premium: `${global.msg.danied}\n\nPerintah ini hanya dapat digunakan oleh *Premium*!`,
group: `${global.msg.danied}\n\nPerintah ini hanya dapat digunakan di grup!`,
private: `${global.msg.danied}\n\nPerintah ini hanya dapat digunakan di Chat Pribadi!`,
admin: `${global.msg.danied}\n\nPerintah ini hanya untuk *Admin* grup!`,
botAdmin: `${global.msg.danied}\n\nJadikan bot sebagai *Admin* untuk menggunakan perintah ini!`,
restrict: `${global.msg.danied}\n\nFitur ini di *disable*!`,
unreg: `Hai *@${m.sender.split("@")[0]}*\n\nAnda belum terdaftar!\n\nContoh: *#daftar Manusia.16* atau *#regmail xxx@gmail.com*`
}[type]
if (msg) return conn.sendMessage(m.chat, {
text: msg,
contextInfo: {
mentionedJid: [m.sender],
externalAdReply: {
title: info.nameBot,
body: info.wm,
thumbnailUrl: url.thumb,
sourceUrl: url.sig,
mediaType: 1,
renderLargerThumbnail: true
}}})
}
let fs = require('fs')
let chalk = require('chalk')
let file = require.resolve(__filename)
fs.watchFile(file, () => {
fs.unwatchFile(file)
console.log(chalk.redBright("Update handler.js'"))
delete require.cache[file]
if (global.reloadHandler) console.log(global.reloadHandler())
})