util#format JavaScript Examples
The following examples show how to use
util#format.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: tools-fetch.js From HinataMd with GNU General Public License v3.0 | 7 votes |
handler = async (m, { text }) => {
if (!text) throw 'Masukkan url'
let { href: url, origin } = new URL(text)
let res = await fetch(url, { headers: { 'referer': origin }})
if (res.headers.get('content-length') > 100 * 1024 * 1024 * 1024) throw `Content-Length: ${res.headers.get('content-length')}`
if (!/text|json/.test(res.headers.get('content-type'))) return conn.sendFile(m.chat, url, 'file', text, m)
let txt = await res.buffer()
try {
txt = format(JSON.parse(txt + ''))
} catch (e) {
txt = txt + ''
} finally {
m.reply(txt.slice(0, 65536) + '')
}
}
Example #2
Source File: main.js From HinataMd with GNU General Public License v3.0 | 6 votes |
global.reload = async (_ev, filename) => {
if (pluginFilter(filename)) {
let dir = global.__filename(join(pluginFolder, filename), true)
if (filename in global.plugins) {
if (existsSync(dir)) conn.logger.info(` updated plugin - '${filename}'`)
else {
conn.logger.warn(`deleted plugin - '${filename}'`)
return delete global.plugins[filename]
}
} else conn.logger.info(`new plugin - '${filename}'`)
let err = syntaxerror(readFileSync(dir), filename, {
sourceType: 'module',
allowAwaitOutsideFunction: true
})
if (err) conn.logger.error(`syntax error while loading '${filename}'\n${format(err)}`)
else try {
const module = (await import(`${global.__filename(dir)}?update=${Date.now()}`))
global.plugins[filename] = module.default || module
} catch (e) {
conn.logger.error(`error require plugin '${filename}\n${format(e)}'`)
} finally {
global.plugins = Object.fromEntries(Object.entries(global.plugins).sort(([a], [b]) => a.localeCompare(b)))
}
}
}
Example #3
Source File: owner-exec.js From HinataMd with GNU General Public License v3.0 | 6 votes |
handler = async (m, _2) => {
let { conn, usedPrefix, noPrefix, args, groupMetadata } = _2
let _return
let _syntax = ''
let _text = (/^=/.test(usedPrefix) ? 'return ' : '') + noPrefix
let old = m.exp * 1
try {
let i = 15
let f = {
exports: {}
}
let exec = new (async () => { }).constructor('print', 'm', 'handler', 'require', 'conn', 'Array', 'process', 'args', 'groupMetadata', 'baileys', 'module', 'exports', 'argument', _text)
_return = await exec.call(conn, (...args) => {
if (--i < 1) return
console.log(...args)
return conn.reply(m.chat, format(...args), m)
}, m, handler, require, conn, CustomArray, process, args, groupMetadata, baileys, f, f.exports, [conn, _2])
} catch (e) {
let err = syntaxerror(_text, 'Execution Function', {
allowReturnOutsideFunction: true,
allowAwaitOutsideFunction: true,
sourceType: 'module'
})
if (err) _syntax = '```' + err + '```\n\n'
_return = e
} finally {
conn.reply(m.chat, _syntax + format(_return), m)
m.exp = old
}
}
Example #4
Source File: sticker-toimg.js From HinataMd with GNU General Public License v3.0 | 6 votes |
handler = async (m, { conn, usedPrefix, command }) => {
if (!global.support.convert &&
!global.support.magick &&
!global.support.gm) return handler.disabled = true // Disable if doesnt support
const notStickerMessage = `Reply sticker with command *${usedPrefix + command}*`
if (!m.quoted) throw notStickerMessage
let q = m.quoted
if (/sticker/.test(q.mediaType)) {
let sticker = await q.download()
if (!sticker) throw sticker
let bufs = []
const [_spawnprocess, ..._spawnargs] = [...(global.support.gm ? ['gm'] : global.support.magick ? ['magick'] : []), 'convert', 'webp:-', 'png:-']
let im = spawn(_spawnprocess, _spawnargs)
im.on('error', e => m.reply(format(e)))
im.stdout.on('data', chunk => bufs.push(chunk))
im.stdin.write(sticker)
im.stdin.end()
im.on('exit', () => {
conn.sendFile(m.chat, Buffer.concat(bufs), 'image.png', author, m)
})
} else throw notStickerMessage
}
Example #5
Source File: index.js From URT-BOT with MIT License | 6 votes |
parser = new YargsParser({
cwd: process.cwd,
env: () => {
return env;
},
format,
normalize,
resolve,
// TODO: figure out a way to combine ESM and CJS coverage, such that
// we can exercise all the lines below:
require: (path) => {
if (typeof require !== 'undefined') {
return require(path);
}
else if (path.match(/\.json$/)) {
// Addresses: https://github.com/yargs/yargs/issues/2040
return JSON.parse(readFileSync(path, 'utf8'));
}
else {
throw Error('only .json config files are supported in ESM');
}
}
})
Example #6
Source File: index.js From bakabo with GNU General Public License v3.0 | 6 votes |
parser = new YargsParser({
cwd: process.cwd,
env: () => {
return env;
},
format,
normalize,
resolve,
// TODO: figure out a way to combine ESM and CJS coverage, such that
// we can exercise all the lines below:
require: (path) => {
if (typeof require !== 'undefined') {
return require(path);
}
else if (path.match(/\.json$/)) {
return readFileSync(path, 'utf8');
}
else {
throw Error('only .json config files are supported in ESM');
}
}
})
Example #7
Source File: nulis-nulis.js From HinataMd with GNU General Public License v3.0 | 5 votes |
handler = async (m, { conn, args }) => {
if (!global.support.convert &&
!global.support.magick &&
!global.support.gm) return handler.disabled = true // Disable if doesnt support
let inputPath = 'src/kertas/magernulis1.jpg'
let d = new Date()
let tgl = d.toLocaleDateString('id-Id')
let hari = d.toLocaleDateString('id-Id', { weekday: 'long' })
let teks = args.join` `
// conn.reply(m.chat, util.format({fontPath, inputPath, outputPath, tgl, hari, teks}), m)
let bufs = []
const [_spawnprocess, ..._spawnargs] = [...(global.support.gm ? ['gm'] : global.support.magick ? ['magick'] : []),
'convert',
inputPath,
'-font',
fontPath,
'-size',
'1024x784',
'-pointsize',
'20',
'-interline-spacing',
'1',
'-annotate',
'+806+78',
hari,
'-font',
fontPath,
'-size',
'1024x784',
'-pointsize',
'18',
'-interline-spacing',
'1',
'-annotate',
'+806+102',
tgl,
'-font',
fontPath,
'-size',
'1024x784',
'-pointsize',
'20',
'-interline-spacing',
'-7.5',
'-annotate',
'+344+142',
teks,
'jpg:-'
]
spawn(_spawnprocess, _spawnargs)
.on('error', e => m.reply(format(e)))
.on('close', () => {
conn.sendFile(m.chat, Buffer.concat(bufs), 'nulis.jpg', 'Hati² ketahuan:v', m)
})
.stdout.on('data', chunk => bufs.push(chunk))
}
Example #8
Source File: nulis-nulis2.js From HinataMd with GNU General Public License v3.0 | 5 votes |
handler = async (m, { conn, args }) => {
if (!global.support.convert &&
!global.support.magick &&
!global.support.gm) return handler.disabled = true // Disable if doesnt support
let inputPath = 'src/kertas/magernulis1.jpg'
let d = new Date
let tgl = d.toLocaleDateString('id-Id')
let hari = d.toLocaleDateString('id-Id', { weekday: 'long' })
let teks = args.join` `
// conn.reply(m.chat, util.format({fontPath, inputPath, outputPath, tgl, hari, teks}), m)
let bufs = []
const [_spawnprocess, ..._spawnargs] = [...(global.support.gm ? ['gm'] : global.support.magick ? ['magick'] : []),
'convert',
inputPath,
'-font',
fontPath,
'-fill',
'blue',
'-size',
'1024x784',
'-pointsize',
'20',
'-interline-spacing',
'1',
'-annotate',
'+806+78',
hari,
'-font',
fontPath,
'-fill',
'blue',
'-size',
'1024x784',
'-pointsize',
'18',
'-interline-spacing',
'1',
'-annotate',
'+806+102',
tgl,
'-font',
fontPath,
'-fill',
'blue',
'-size',
'1024x784',
'-pointsize',
'20',
'-interline-spacing',
'-7.5',
'-annotate',
'+344+142',
teks,
'jpg:-'
]
spawn(_spawnprocess, _spawnargs)
.on('error', e => m.reply(format(e)))
.on('close', () => {
conn.sendFile(m.chat, Buffer.concat(bufs), 'nulis.jpg', 'Hati² ketahuan:v', m)
})
.stdout.on('data', chunk => bufs.push(chunk))
}
Example #9
Source File: sticker-getexif.js From HinataMd with GNU General Public License v3.0 | 5 votes |
handler = async (m) => {
if (!m.quoted) return m.reply('Tag stikernya!')
if (/sticker/.test(m.quoted.mtype)) {
let img = new Image()
await img.load(await m.quoted.download())
m.reply(format(JSON.parse(img.exif.slice(22).toString())))
}
}
Example #10
Source File: tools-getexif.js From HinataMd with GNU General Public License v3.0 | 5 votes |
handler = async (m, { conn }) => {
if (m.quoted && /sticker/.test(m.quoted.mtype)) {
let img = await m.quoted.download()
if (!img) throw 'Can\'t extract metadata sticker!'
let metaData = await extractMetadata(img)
await m.reply(format(metaData))
} else throw 'Reply a sticker!'
}
Example #11
Source File: handler.js From HinataMd with GNU General Public License v3.0 | 4 votes |
/**
* Handle messages upsert
* @param {import('@adiwajshing/baileys').BaileysEventMap<unknown>['messages.upsert']} groupsUpdate
*/
export async function handler(chatUpdate) {
this.msgqueque = this.msgqueque || []
if (!chatUpdate)
return
this.pushMessage(chatUpdate.messages).catch(console.error)
let m = chatUpdate.messages[chatUpdate.messages.length - 1]
if (!m)
return
if (global.db.data == null)
await global.loadDatabase()
try {
m = smsg(this, m) || m
if (!m)
return
m.exp = 0
m.limit = false
try {
// TODO: use loop to insert data instead of this
let user = global.db.data.users[m.sender]
if (typeof user !== 'object')
global.db.data.users[m.sender] = {}
if (user) {
if (!user.registered) {
if (!('name' in user)) user.name = m.name
if (!isNumber(user.age)) user.age = -1
if (!isNumber(user.anggur)) user.anggur = 0
if (!isNumber(user.apel)) user.apel = 0
if (!isNumber(user.bibitanggur)) user.bibitanggur = 0
if (!isNumber(user.bibitapel)) user.bibitapel = 0
if (!isNumber(user.bibitjeruk)) user.bibitjeruk = 0
if (!isNumber(user.bibitmangga)) user.bibitmangga = 0
if (!isNumber(user.bibitpisang)) user.bibitpisang = 0
if (!isNumber(user.emas)) user.emas = 0
if (!isNumber(user.jeruk)) user.jeruk = 0
if (!isNumber(user.kayu)) user.kayu = 0
if (!isNumber(user.makanan)) user.makanan = 0
if (!isNumber(user.mangga)) user.mangga = 0
if (!isNumber(user.pisang)) user.pisang = 0
if (!isNumber(user.premiumDate)) user.premiumDate = -1
if (!isNumber(user.regTime)) user.regTime = -1
if (!isNumber(user.semangka)) user.semangka = 0
if (!isNumber(user.stroberi)) user.stroberi = 0
}
if (!user.lbars) user.lbars = '[▒▒▒▒▒▒▒▒▒]'
if (!'afkReason' in user) user.afkReason = ''
if (!'BannedReason' in user) user.BannedReason = ''
if (!'Banneduser' in user) user.Banneduser = false
if (!('afkReason' in user)) user.afkReason = ''
if (!('autolevelup' in user)) user.autolevelup = false
if (!('banned' in user)) user.banned = false
if (!('job' in user)) user.job = ''
if (!('kingdom' in user)) user.kingdom = true
if (!('misi' in user)) user.misi = ''
if (!('pasangan' in user)) user.pasangan = ''
if (!('registered' in user)) user.registered = false
if (!('role' in user)) user.role = 'Beginner'
if (!('skill' in user)) user.skill = ''
if (!('title' in user)) user.title = ''
if (!isNumber(user.afk)) user.afk = -1
if (!isNumber(user.agility)) user.agility = 0
if (!isNumber(user.anakanjing)) user.anakanjing = 0
if (!isNumber(user.anakcentaur)) user.anakcentaur = 0
if (!isNumber(user.anakgriffin)) user.anakgriffin = 0
if (!isNumber(user.anakkucing)) user.anakkucing = 0
if (!isNumber(user.anakkuda)) user.anakkuda = 0
if (!isNumber(user.anakkyubi)) user.anakkyubi = 0
if (!isNumber(user.anaknaga)) user.anaknaga = 0
if (!isNumber(user.anakphonix)) user.anakphonix = 0
if (!isNumber(user.anakrubah)) user.anakrubah = 0
if (!isNumber(user.anakserigala)) user.anakserigala = 0
if (!isNumber(user.anjing)) user.anjing = 0
if (!isNumber(user.anjinglastclaim)) user.anjinglastclaim = 0
if (!isNumber(user.antispam)) user.antispam = 0
if (!isNumber(user.antispamlastclaim)) user.antispamlastclaim = 0
if (!isNumber(user.apel)) user.apel = 0
if (!isNumber(user.aqua)) user.aqua = 0
if (!isNumber(user.arc)) user.arc = 0
if (!isNumber(user.arcdurability)) user.arcdurability = 0
if (!isNumber(user.arlok)) user.arlok = 0
if (!isNumber(user.armor)) user.armor = 0
if (!isNumber(user.armordurability)) user.armordurability = 0
if (!isNumber(user.as)) user.as = 0
if (!isNumber(user.atm)) user.atm = 0
if (!isNumber(user.ayam)) user.ayam = 0
if (!isNumber(user.ayamb)) user.ayamb = 0
if (!isNumber(user.ayamg)) user.ayamg = 0
if (!isNumber(user.babi)) user.babi = 0
if (!isNumber(user.babihutan)) user.babihutan = 0
if (!isNumber(user.bank)) user.bank = 0
if (!isNumber(user.banteng)) user.banteng = 0
if (!isNumber(user.batu)) user.batu = 0
if (!isNumber(user.bawal)) user.bawal = 0
if (!isNumber(user.botol)) user.botol = 0
if (!isNumber(user.bow)) user.bow = 0
if (!isNumber(user.buaya)) user.buaya = 0
if (!isNumber(user.buntal)) user.buntal = 0
if (!isNumber(user.cat)) user.cat = 0
if (!isNumber(user.catexp)) user.catexp = 0
if (!isNumber(user.catlastfeed)) user.catlastfeed = 0
if (!isNumber(user.centaur)) user.centaur = 0
if (!isNumber(user.centaurlastclaim)) user.centaurlastclaim = 0
if (!isNumber(user.coin)) user.coin = 0
if (!isNumber(user.common)) user.common = 0
if (!isNumber(user.crystal)) user.crystal = 0
if (!isNumber(user.cumi)) user.cumi= 0
if (!isNumber(user.diamond)) user.diamond = 0
if (!isNumber(user.dog)) user.dog = 0
if (!isNumber(user.dogexp)) user.dogexp = 0
if (!isNumber(user.doglastfeed)) user.doglastfeed = 0
if (!isNumber(user.dory)) user.dory = 0
if (!isNumber(user.emas)) user.emas = 0
if (!isNumber(user.emerald)) user.emerald = 0
if (!isNumber(user.enchant)) user.enchant = 0
if (!isNumber(user.esteh)) user.esteh = 0
if (!isNumber(user.exp)) user.exp = 0
if (!isNumber(user.fishingrod)) user.fishingrod = 0
if (!isNumber(user.fishingroddurability)) user.fishingroddurability = 0
if (!isNumber(user.fortress)) user.fortress = 0
if (!isNumber(user.fox)) user.fox = 0
if (!isNumber(user.foxhexp)) user.foxexp = 0
if (!isNumber(user.foxlastfeed)) user.foxlastfeed = 0
if (!isNumber(user.gajah)) user.gajah = 0
if (!isNumber(user.gamemines)) user.gamemines = false
if (!isNumber(user.gems)) user.gems = 0
if (!isNumber(user.glimit)) user.glimit = 20
if (!isNumber(user.glory)) user.glory = 0
if (!isNumber(user.gold)) user.gold = 0
if (!isNumber(user.griffin)) user.griffin = 0
if (!isNumber(user.griffinlastclaim)) user.griffinlastclaim = 0
if (!isNumber(user.gurita)) user.gurita = 0
if (!isNumber(user.harimau)) user.harimau = 0
if (!isNumber(user.haus)) user.haus = 100
if (!isNumber(user.healt)) user.healt = 100
if (!isNumber(user.health)) user.health = 100
if (!isNumber(user.healthmonster)) user.healthmonster = 0
if (!isNumber(user.hiu)) user.hiu = 0
if (!isNumber(user.horse)) user.horse = 0
if (!isNumber(user.horseexp)) user.horseexp = 0
if (!isNumber(user.horselastfeed)) user.horselastfeed = 0
if (!isNumber(user.ikan)) user.ikan = 0
if (!isNumber(user.intelligence)) user.intelligence = 0
if (!isNumber(user.iron)) user.iron = 0
if (!isNumber(user.kaleng)) user.kaleng = 0
if (!isNumber(user.kambing)) user.kambing = 0
if (!isNumber(user.kardus)) user.kardus = 0
if (!isNumber(user.katana)) user.katana = 0
if (!isNumber(user.katanadurability)) user.katanadurability = 0
if (!isNumber(user.kayu)) user.kayu = 0
if (!isNumber(user.kepiting)) user.kepiting = 0
if (!isNumber(user.kerbau)) user.kerbau = 0
if (!isNumber(user.korbanngocok)) user.korbanngocok = 0
if (!isNumber(user.kucing)) user.kucing = 0
if (!isNumber(user.kucinglastclaim)) user.kucinglastclaim = 0
if (!isNumber(user.kuda)) user.kuda = 0
if (!isNumber(user.kudalastclaim)) user.kudalastclaim = 0
if (!isNumber(user.kyubi)) user.kyubi = 0
if (!isNumber(user.laper)) user.laper = 100
if (!isNumber(user.lastadventure)) user.lastadventure = 0
if (!isNumber(user.lastbansos)) user.lastbansos = 0
if (!isNumber(user.lastberbru)) user.lastberbru = 0
if (!isNumber(user.lastberkebon)) user.lastberkebon = 0
if (!isNumber(user.lastbunuhi)) user.lastbunuhi = 0
if (!isNumber(user.lastclaim)) user.lastclaim = 0
if (!isNumber(user.lastcodereg)) user.lastcodereg = 0
if (!isNumber(user.lastdagang)) user.lastdagang = 0
if (!isNumber(user.lastduel)) user.lastduel = 0
if (!isNumber(user.lastdungeon)) user.lastdungeon = 0
if (!isNumber(user.lastfight)) user.lastfight = 0
if (!isNumber(user.lastfishing)) user.lastfishing = 0
if (!isNumber(user.lastgift)) user.lastgift = 0
if (!isNumber(user.lastgrab)) user.lastgrab = 0
if (!isNumber(user.lasthourly)) user.lasthourly = 0
if (!isNumber(user.lasthunt)) user.lasthunt = 0
if (!isNumber(user.lastIstigfar)) user.lastIstigfar = 0
if (!isNumber(user.lastjb)) user.lastjb = 0
if (!isNumber(user.lastkill)) user.lastkill = 0
if (!isNumber(user.lastmining)) user.lastmining = 0
if (!isNumber(user.lastmisi)) user.lastmisi = 0
if (!isNumber(user.lastmonthly)) user.lastmonthly = 0
if (!isNumber(user.lastngocok)) user.lastngocok = 0
if (!isNumber(user.lastngojek)) user.lastngojek = 0
if (!isNumber(user.lastroket)) user.lastroket = 0
if (!isNumber(user.lastrampok)) user.lastrampok = 0
if (!isNumber(user.lastrob)) user.lastrob = 0
if (!isNumber(user.lastsda)) user.lastsda = 0
if (!isNumber(user.lastseen)) user.lastseen = 0
if (!isNumber(user.lastSetStatus)) user.lastSetStatus = 0
if (!isNumber(user.lastturu)) user.lastturu = 0
if (!isNumber(user.lastwar)) user.lastwar = 0
if (!isNumber(user.lastweekly)) user.lastweekly = 0
if (!isNumber(user.lastwork)) user.lastwork = 0
if (!isNumber(user.legendary)) user.legendary = 0
if (!isNumber(user.lele)) user.lele = 0
if (!isNumber(user.leleb)) user.leleb = 0
if (!isNumber(user.leleg)) user.leleg = 0
if (!isNumber(user.level)) user.level = 0
if (!isNumber(user.limit)) user.limit = 10
if (!isNumber(user.lobster)) user.lobster = 0
if (!isNumber(user.lumba)) user.lumba = 0
if (!isNumber(user.magicwand)) user.magicwand = 0
if (!isNumber(user.magicwanddurability)) user.magicwanddurability = 0
if (!isNumber(user.makanancentaur)) user.makanancentaur = 0
if (!isNumber(user.makanangriffin)) user.makanangriffin = 0
if (!isNumber(user.makanannaga)) user.makanannaga = 0
if (!isNumber(user.makananpet)) user.makananpet
if (!isNumber(user.makananpet)) user.makananpet = 0
if (!isNumber(user.makananphonix)) user.makananphonix = 0
if (!isNumber(user.makananserigala)) user.makananserigala = 0
if (!isNumber(user.mana)) user.mana = 0
if (!isNumber(user.money)) user.money = 0
if (!isNumber(user.monyet)) user.monyet = 0
if (!isNumber(user.mythic)) user.mythic = 0
if (!isNumber(user.naga)) user.naga = 0
if (!isNumber(user.nagalastclaim)) user.nagalastclaim = 0
if (!isNumber(user.net)) user.net = 0
if (!isNumber(user.nila)) user.nila = 0
if (!isNumber(user.ojekk)) user.ojekk = 0
if (!isNumber(user.roket)) user.roket = 0
if (!isNumber(user.orca)) user.orca = 0
if (!isNumber(user.pancing)) user.pancing = 0
if (!isNumber(user.panda)) user.panda = 0
if (!isNumber(user.paus)) user.paus = 0
if (!isNumber(user.pc)) user.pc = 0
if (!isNumber(user.pertambangan)) user.pertambangan = 0
if (!isNumber(user.pertanian)) user.pertanian = 0
if (!isNumber(user.pet)) user.pet = 0
if (!isNumber(user.petFood)) user.petFood = 0
if (!isNumber(user.phonix)) user.phonix = 0
if (!isNumber(user.phonixlastclaim)) user.phonixlastclaim = 0
if (!isNumber(user.pickaxe)) user.pickaxe = 0
if (!isNumber(user.pickaxedurability)) user.pickaxedurability = 0
if (!isNumber(user.pointxp)) user.pointxp = 0
if (!isNumber(user.potion)) user.potion = 0
if (!isNumber(user.psenjata)) user.psenjata = 0
if (!isNumber(user.psepick)) user.psepick = 0
if (!isNumber(user.ramuan)) user.ramuan = 0
if (!isNumber(user.rock)) user.rock = 0
if (!isNumber(user.rubah)) user.rubah = 0
if (!isNumber(user.rubahlastclaim)) user.rubahlastclaim = 0
if (!isNumber(user.rumahsakit)) user.rumahsakit= 0
if (!isNumber(user.sampah)) user.sampah = 0
if (!isNumber(user.sapi)) user.sapi = 0
if (!isNumber(user.sapir)) user.sapir = 0
if (!isNumber(user.serigala)) user.serigala = 0
if (!isNumber(user.serigalalastclaim)) user.serigalalastclaim = 0
if (!isNumber(user.shield)) user.shield = false
if (!isNumber(user.skillexp)) user.skillexp = 0
if (!isNumber(user.ssapi)) user.ssapi = 0
if (!isNumber(user.stamina)) user.stamina = 0
if (!isNumber(user.stamina)) user.stamina = 100
if (!isNumber(user.strength)) user.strength = 0
if (!isNumber(user.string)) user.string = 0
if (!isNumber(user.sword)) user.sword = 0
if (!isNumber(user.sworddurability)) user.sworddurability = 0
if (!isNumber(user.tigame)) user.tigame = 50
if (!isNumber(user.tiketcoin)) user.tiketcoin = 0
if (!isNumber(user.title)) user.title = 0
if (!isNumber(user.tprem)) user.tprem = 0
if (!isNumber(user.trash)) user.trash = 0
if (!isNumber(user.trofi)) user.trofi= 0
if (!isNumber(user.troopcamp)) user.troopcamp = 0
if (!isNumber(user.udang)) user.udang = 0
if (!isNumber(user.umpan)) user.umpan = 0
if (!isNumber(user.uncommon)) user.uncommon = 0
if (!isNumber(user.wallet)) user.wallet = 0
if (!isNumber(user.warn)) user.warn = 0
if (!isNumber(user.wood)) user.wood = 0
if (!user.job) user.job = 'Pengangguran'
if (!user.premium) user.premium = false
if (!user.premium) user.premiumTime= 0
if (!user.rtrofi) user.rtrofi = 'Perunggu'
} else
global.db.data.users[m.sender] = {
afk: -1,
afkReason: '',
age: -1,
agility: 16,
anakanjing: 0,
anakkucing: 0,
anakkuda: 0,
anakrubah: 0,
anjing: 0,
anjinglastclaim: 0,
antispam: 0,
antispamlastclaim: 0,
apel: 20,
arc: 0,
arcdurability: 0,
arlok: 0,
armor: 0,
armordurability: 0,
as: 0,
atm: 0,
autolevelup: false,
ayam: 0,
ayamb: 0,
ayamg: 0,
babi: 0,
babihutan: 0,
bank: 0,
banned: false,
BannedReason: '',
Banneduser: false,
banteng: 0,
batu: 0,
bawal: 0,
bow: 0,
buaya: 0,
buntal: 0,
cat: 0,
catlastfeed: 0,
catngexp: 0,
centaur: 0,
centaurlastclaim: 0,
coin: 0,
common: 0,
crystal: 0,
cumi: 0,
diamond: 0,
dog: 0,
dogexp: 0,
doglastfeed: 0,
dory: 0,
emas: 0,
emerald: 0,
esteh: 0,
exp: 0,
fishingrod: 0,
fishingroddurability: 0,
fortress: 0,
fox: 0,
foxexp: 0,
foxlastfeed: 0,
fullatm: 0,
gajah: 0,
gamemines: false,
gems: 0,
gold: 0,
griffin: 0,
griffinlastclaim: 0,
gurita: 0,
harimau: 0,
haus: 100,
healt: 100,
health: 100,
hiu: 0,
horse: 0,
horseexp: 0,
horselastfeed: 0,
ikan: 0,
intelligence: 10,
iron: 0,
jeruk: 0,
job: '',
job: 'Pengangguran',
kambing: 0,
katana: 0,
katanadurability: 0,
kayu: 0,
kepiting: 0,
kerbau : 0,
korbanngocok: 0,
kucing: 0,
kucinglastclaim: 0,
kuda: 0,
kudalastclaim: 0,
laper: 100,
lastadventure: 0,
lastberbru: 0,
lastbunga: 0,
lastbunuhi: 0,
lastclaim: 0,
lastdaang: 0,
lastduel: 0,
lastdungeon: 0,
lastfight: 0,
lastfishing: 0,
lastgrab: 0,
lasthourly: 0,
lasthunt: 0,
lastjb: 0,
lastkill: 0,
lastmining: 0,
lastmisi: 0,
lastmonthly: 0,
lastngocok: 0,
lastngojek: 0,
lastrob: 0,
lastroket: 0,
lastseen: 0,
lastSetStatus: 0,
lastturu: 0,
lastweekly: 0,
lastwork: 0,
lbars: '[▒▒▒▒▒▒▒▒▒]',
legendary: 0,
lele: 0,
leleb: 0,
leleg: 0,
level: 0,
limit: 10,
limit: 20,
limit: 100,
lobster: 0,
lumba: 0,
magicwand: 0,
magicwanddurability: 0,
makanan: 0,
makanancentaur: 0,
makanannaga: 0,
makananpet: 0,
makananphonix: 0,
makananserigala: 0,
mana: 20,
mangga: 0,
misi: "",
money: 0,
monyet : 0,
mythic: 0,
naga: 0,
nagalastclaim: 0,
name: conn.getName(m.sender),
name: m.name,
name: this.getName(m.sender),
net: 0,
nila: 0,
ojekk: 0,
roket: 0,
orca: 0,
panda: 0,
pasangan: '',
paus: 0,
pc : 0,
pc: false,
pet: 0,
phonix: 0,
phonixlastclaim: 0,
pickaxe: 0,
pickaxedurability: 0,
pointxp: 0,
potion: 0,
potion: 10,
premium: false,
premiumTime: 0,
registered: false,
regTime: -1,
rock: 0,
role: 'Beginner',
role: 'Newbie ㋡',
rtrofi: 'perunggu',
rubah: 0,
rubahlastclaim: 0,
rumahsakit: 0,
sampah: 0,
sapi: 0,
sapir: 0,
semangka: 0,
serigala: 0,
serigalalastclaim: 0,
shield: 0,
skill: "",
skillexp: 0,
ssapi: 0,
stamina : 100,
stamina: 100,
strength: 30,
string: 0,
stroberi: 0,
superior: 0,
sword: 0,
sworddurability: 0,
tigame: 50,
tiketcoin: 0,
title: "",
title: '',
tprem: 0,
trash: 0,
trofi: 0,
troopcamp: 0,
udang: 0,
umpan: 0,
uncommon: 0,
upgrader: 0,
wallet: 0,
warn: 0,
wood: 0,
}
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 = true
if (!('detect' in chat))
chat.detect = true
if (!('sWelcome' in chat))
chat.sWelcome = ''
if (!('sBye' in chat))
chat.sBye = ''
if (!('sPromote' in chat))
chat.sPromote = ''
if (!('sDemote' in chat))
chat.sDemote = ''
if (!('delete' in chat))
chat.delete = false
if (!('antiLink' in chat))
chat.antiLink = false
if (!('viewonce' in chat))
chat.viewonce = false
if (!('antiToxic' in chat))
chat.antiToxic = true
if (!('simi' in chat))
chat.simi = false
if (!('nsfw' in chat))
chat.nsfw = false
if (!('premnsfw' in chat))
chat.premnsfw = false
if (!isNumber(chat.expired))
chat.expired = 0
if (!('getmsg' in chat))
chat.getmsg = true
} else
global.db.data.chats[m.chat] = {
isBanned: false,
welcome: true,
detect: true,
sWelcome: '',
sBye: '',
sPromote: '',
sDemote: '',
delete: false,
antiLink: false,
viewonce: false,
antiToxic: true,
simi: false,
expired: 0,
nsfw: false,
premnsfw: false,
getmsg: true,
}
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 = true
if (!('restrict' in settings)) settings.restrict = true
if (!'jadibot' in settings) settings.jadibot = true
if (!('autorestart' in settings)) settings.autorestart = true
if (!('restartDB' in settings)) settings.restartDB = 0
} else global.db.data.settings[this.user.jid] = {
self: false,
autoread: true,
jadibot: true,
restrict: true,
autorestart: true,
restartDB: 0
}
} catch (e) {
console.error(e)
}
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]) => number)].map(v => v.replace(/[^0-9]/g, '') + '@s.whatsapp.net').includes(m.sender)
const isOwner = isROwner || m.fromMe
const isMods = isOwner || global.mods.map(v => v.replace(/[^0-9]/g, '') + '@s.whatsapp.net').includes(m.sender)
const isPrems = isROwner || global.prems.map(v => v.replace(/[^0-9]/g, '') + '@s.whatsapp.net').includes(m.sender)
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)
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 || await this.groupMetadata(m.chat).catch(_ => null)) : {}) || {}
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?.admin == 'superadmin' || false
const isAdmin = isRAdmin || user?.admin == 'admin' || false // Is User Admin?
const isBotAdmin = bot?.admin || false // Are you Admin?
const ___dirname = path.join(path.dirname(fileURLToPath(import.meta.url)), './plugins')
for (let name in global.plugins) {
let plugin = global.plugins[name]
if (!plugin)
continue
if (plugin.disabled)
continue
const __filename = join(___dirname, name)
if (typeof plugin.all === 'function') {
try {
await plugin.all.call(this, m, {
chatUpdate,
__dirname: ___dirname,
__filename
})
} catch (e) {
// if (typeof e === 'string') continue
console.error(e)
for (let [jid] of global.owner.filter(([number, _, isDeveloper]) => isDeveloper && number)) {
let data = (await conn.onWhatsApp(jid))[0] || {}
if (data.exists)
m.reply(`*?️ Plugin:* ${name}\n*? Sender:* ${m.sender}\n*? Chat:* ${m.chat}\n*? Command:* ${m.text}\n\n\`\`\`${format(e)}\`\`\``.trim(), data.jid)
}
}
}
if (!opts['restrict'])
if (plugin.tags && plugin.tags.includes('admin')) {
// global.dfail('restrict', m, this)
continue
}
const str2Regex = str => str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
let _prefix = plugin.customPrefix ? plugin.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 plugin.before === 'function') {
if (await plugin.before.call(this, m, {
match,
conn: this,
participants,
groupMetadata,
user,
bot,
isROwner,
isOwner,
isRAdmin,
isAdmin,
isBotAdmin,
isPrems,
chatUpdate,
__dirname: ___dirname,
__filename
}))
continue
}
if (typeof plugin !== '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 = plugin.fail || global.dfail // When failed
let isAccept = plugin.command instanceof RegExp ? // RegExp Mode?
plugin.command.test(command) :
Array.isArray(plugin.command) ? // Array?
plugin.command.some(cmd => cmd instanceof RegExp ? // RegExp in Array?
cmd.test(command) :
cmd === command
) :
typeof plugin.command === 'string' ? // String?
plugin.command === command :
false
if (!isAccept)
continue
m.plugin = 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 != 'owner-unbanchat.js' && chat?.isBanned)
return // Except this
if (name != 'owner-unbanuser.js' && user?.banned)
return
}
if (plugin.rowner && plugin.owner && !(isROwner || isOwner)) { // Both Owner
fail('owner', m, this)
continue
}
if (plugin.rowner && !isROwner) { // Real Owner
fail('rowner', m, this)
continue
}
if (plugin.owner && !isOwner) { // Number Owner
fail('owner', m, this)
continue
}
if (plugin.mods && !isMods) { // Moderator
fail('mods', m, this)
continue
}
if (plugin.premium && !isPrems) { // Premium
fail('premium', m, this)
continue
}
if (plugin.group && !m.isGroup) { // Group Only
fail('group', m, this)
continue
} else if (plugin.botAdmin && !isBotAdmin) { // You Admin
fail('botAdmin', m, this)
continue
} else if (plugin.admin && !isAdmin) { // User Admin
fail('admin', m, this)
continue
}
if (plugin.private && m.isGroup) { // Private Chat Only
fail('private', m, this)
continue
}
if (plugin.register == true && _user.registered == false) { // Butuh daftar?
fail('unreg', m, this)
continue
}
m.isCommand = true
let xp = 'exp' in plugin ? parseInt(plugin.exp) : 17 // XP Earning per command
if (xp > 200)
// m.reply('Ngecit -_-') // Hehehe
this.sendButton(m.chat, `Jirr.. Ngecit -_- pake kalkulator.. Gpp lahh\nPencet dibawah, meresahkan`, wm, null, [
['Ngechit', `/ngechit`]
], m)
else
m.exp += xp
if (!isPrems && plugin.limit && global.db.data.users[m.sender].limit < plugin.limit * 1) {
this.reply(m.chat, `[❗] Limit anda habis, silahkan beli melalui *${usedPrefix}buy limit*`, m)
continue // Limit habis
}
if (plugin.level > _user.level) {
this.sendButton(m.chat, `[?] Diperlukan level *${plugin.level}* untuk menggunakan perintah ini. Level kamu *${_user.level}?*\n*${plugin.level}* level is required to use this command. Your level is *${_user.level}?*`, author, null,[["Ok", "ok"]] , 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,
chatUpdate,
__dirname: ___dirname,
__filename
}
try {
await plugin.call(this, m, extra)
if (!isPrems)
m.limit = m.limit || plugin.limit || false
} catch (e) {
// Error occured
m.error = e
console.error(e)
if (e) {
let text = 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, _, isDeveloper]) => isDeveloper && number)) {
let data = (await conn.onWhatsApp(jid))[0] || {}
if (data.exists)
return m.reply(`*?️ Plugin:* ${m.plugin}\n*? Sender:* ${m.sender}\n*? Chat:* ${m.chat}\n*? Command:* ${usedPrefix}${command} ${args.join(' ')}\n? *Error Logs:*\n\n\`\`\`${text}\`\`\``.trim(), data.jid)
}
m.reply(text)
}
} finally {
// m.reply(util.format(_user))
if (typeof plugin.after === 'function') {
try {
await plugin.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.plugin) {
let now = +new Date
if (m.plugin in stats) {
stat = stats[m.plugin]
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.plugin] = {
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 {
if (!opts['noprint']) await (await import(`./lib/print.js`)).default(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(() => { })
}
}
Example #12
Source File: simple.js From HinataMd with GNU General Public License v3.0 | 4 votes |
export function makeWASocket(connectionOptions, options = {}) {
/**
* @type {import('@adiwajshing/baileys').WASocket | import('@adiwajshing/baileys').WALegacySocket}
*/
let conn = (global.opts['legacy'] ? makeWALegacySocket : _makeWaSocket)(connectionOptions)
let sock = Object.defineProperties(conn, {
chats: {
value: { ...(options.chats || {}) },
writable: true
},
decodeJid: {
value(jid) {
if (!jid || typeof jid !== 'string') return (!nullish(jid) && jid) || null
return jid.decodeJid()
}
},
logger: {
get() {
return {
info(...args) {
console.log(
chalk.bold.bgRgb(51, 204, 51)('INFO '),
`[${chalk.rgb(255, 255, 255)(new Date().toUTCString())}]:`,
chalk.cyan(format(...args))
)
},
error(...args) {
console.log(
chalk.bold.bgRgb(247, 38, 33)('ERROR '),
`[${chalk.rgb(255, 255, 255)(new Date().toUTCString())}]:`,
chalk.rgb(255, 38, 0)(format(...args))
)
},
warn(...args) {
console.log(
chalk.bold.bgRgb(255, 153, 0)('WARNING '),
`[${chalk.rgb(255, 255, 255)(new Date().toUTCString())}]:`,
chalk.redBright(format(...args))
)
},
trace(...args) {
console.log(
chalk.grey('TRACE '),
`[${chalk.rgb(255, 255, 255)(new Date().toUTCString())}]:`,
chalk.white(format(...args))
)
},
debug(...args) {
console.log(
chalk.bold.bgRgb(66, 167, 245)('DEBUG '),
`[${chalk.rgb(255, 255, 255)(new Date().toUTCString())}]:`,
chalk.white(format(...args))
)
}
}
},
enumerable: true
},
getFile: {
/**
* getBuffer hehe
* @param {fs.PathLike} PATH
* @param {Boolean} saveToFile
*/
async value(PATH, saveToFile = false) {
let res, filename
const data = Buffer.isBuffer(PATH) ? PATH : PATH instanceof ArrayBuffer ? PATH.toBuffer() : /^data:.*?\/.*?;base64,/i.test(PATH) ? Buffer.from(PATH.split`,`[1], 'base64') : /^https?:\/\//.test(PATH) ? await (res = await fetch(PATH)).buffer() : fs.existsSync(PATH) ? (filename = PATH, fs.readFileSync(PATH)) : typeof PATH === 'string' ? PATH : Buffer.alloc(0)
if (!Buffer.isBuffer(data)) throw new TypeError('Result is not a buffer')
const type = await fileTypeFromBuffer(data) || {
mime: 'application/octet-stream',
ext: '.bin'
}
if (data && saveToFile && !filename) (filename = path.join(__dirname, '../tmp/' + new Date * 1 + '.' + type.ext), await fs.promises.writeFile(filename, data))
return {
res,
filename,
...type,
data,
deleteFile() {
return filename && fs.promises.unlink(filename)
}
}
},
enumerable: true
},
waitEvent: {
/**
* waitEvent
* @param {String} eventName
* @param {Boolean} is
* @param {Number} maxTries
*/
value(eventName, is = () => true, maxTries = 25) { //Idk why this exist?
return new Promise((resolve, reject) => {
let tries = 0
let on = (...args) => {
if (++tries > maxTries) reject('Max tries reached')
else if (is()) {
conn.ev.off(eventName, on)
resolve(...args)
}
}
conn.ev.on(eventName, on)
})
}
},
sendFile: {
/**
* Send Media/File with Automatic Type Specifier
* @param {String} jid
* @param {String|Buffer} path
* @param {String} filename
* @param {String} caption
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo} quoted
* @param {Boolean} ptt
* @param {Object} options
*/
async value(jid, path, filename = '', caption = '', quoted, ptt = false, options = {}) {
let type = await conn.getFile(path, true)
let { res, data: file, filename: pathFile } = type
if (res && res.status !== 200 || file.length <= 65536) {
try { throw { json: JSON.parse(file.toString()) } }
catch (e) { if (e.json) throw e.json }
}
const fileSize = fs.statSync(pathFile).size / 1024 / 1024
if (fileSize >= 100) throw new Error('File size is too big!')
let opt = {}
if (quoted) opt.quoted = quoted
if (!type) options.asDocument = true
let mtype = '', mimetype = options.mimetype || type.mime, convert
if (/webp/.test(type.mime) || (/image/.test(type.mime) && options.asSticker)) mtype = 'sticker'
else if (/image/.test(type.mime) || (/webp/.test(type.mime) && options.asImage)) mtype = 'image'
else if (/video/.test(type.mime)) mtype = 'video'
else if (/audio/.test(type.mime)) (
convert = await toAudio(file, type.ext),
file = convert.data,
pathFile = convert.filename,
mtype = 'audio',
mimetype = options.mimetype || 'audio/ogg; codecs=opus'
)
else mtype = 'document'
if (options.asDocument) mtype = 'document'
delete options.asSticker
delete options.asLocation
delete options.asVideo
delete options.asDocument
delete options.asImage
let message = {
...options,
caption,
ptt,
[mtype]: { url: pathFile },
mimetype,
fileName: filename || pathFile.split('/').pop()
}
/**
* @type {import('@adiwajshing/baileys').proto.WebMessageInfo}
*/
let m
try {
m = await conn.sendMessage(jid, message, { ...opt, ...options })
} catch (e) {
console.error(e)
m = null
} finally {
if (!m) m = await conn.sendMessage(jid, { ...message, [mtype]: file }, { ...opt, ...options })
file = null // releasing the memory
return m
}
},
enumerable: true
},
sendContact: {
/**
* Send Contact
* @param {String} jid
* @param {String[][]|String[]} data
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo} quoted
* @param {Object} options
*/
async value(jid, data, quoted, options) {
if (!Array.isArray(data[0]) && typeof data[0] === 'string') data = [data]
let contacts = []
for (let [number, name] of data) {
number = number.replace(/[^0-9]/g, '')
let njid = number + '@s.whatsapp.net'
let biz = await conn.getBusinessProfile(njid).catch(_ => null) || {}
let vcard = `
BEGIN:VCARD
VERSION:3.0
N:;${name.replace(/\n/g, '\\n')};;;
FN:${name.replace(/\n/g, '\\n')}
TEL;type=CELL;type=VOICE;waid=${number}:${PhoneNumber('+' + number).getNumber('international')}${biz.description ? `
X-WA-BIZ-NAME:${(conn.chats[njid]?.vname || conn.getName(njid) || name).replace(/\n/, '\\n')}
X-WA-BIZ-DESCRIPTION:${biz.description.replace(/\n/g, '\\n')}
`.trim() : ''}
END:VCARD
`.trim()
contacts.push({ vcard, displayName: name })
}
return await conn.sendMessage(jid, {
...options,
contacts: {
...options,
displayName: (contacts.length >= 2 ? `${contacts.length} kontak` : contacts[0].displayName) || null,
contacts,
}
}, { quoted, ...options })
},
enumerable: true
},
reply: {
/**
* Reply to a message
* @param {String} jid
* @param {String|Buffer} text
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo} quoted
* @param {Object} options
*/
value(jid, text = '', quoted, options) {
return Buffer.isBuffer(text) ? conn.sendFile(jid, text, 'file', '', quoted, false, options) : conn.sendMessage(jid, { ...options, text }, { quoted, ...options })
}
},
sendButton: {
/**
* send Button
* @param {String} jid
* @param {String} text
* @param {String} footer
* @param {Buffer} buffer
* @param {String[] | String[][]} buttons
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo} quoted
* @param {Object} options
*/
async value(jid, text = '', footer = '', buffer, buttons, quoted, options) {
let type
if (Array.isArray(buffer)) (options = quoted, quoted = buttons, buttons = buffer, buffer = null)
else if (buffer) try { (type = await conn.getFile(buffer), buffer = type.data) } catch { buffer = null }
if (!Array.isArray(buttons[0]) && typeof buttons[0] === 'string') buttons = [buttons]
if (!options) options = {}
let message = {
...options,
[buffer ? 'caption' : 'text']: text || '',
footer,
buttons: buttons.map(btn => ({
buttonId: !nullish(btn[1]) && btn[1] || !nullish(btn[0]) && btn[0] || '',
buttonText: {
displayText: !nullish(btn[0]) && btn[0] || !nullish(btn[1]) && btn[1] || ''
}
})),
...(buffer ?
options.asLocation && /image/.test(type.mime) ? {
location: {
...options,
jpegThumbnail: buffer
}
} : {
[/video/.test(type.mime) ? 'video' : /image/.test(type.mime) ? 'image' : 'document']: buffer
} : {})
}
return await conn.sendMessage(jid, message, {
quoted,
upload: conn.waUploadToServer,
...options
})
},
enumerable: true
},
sendHydrated: {
/**
*
* @param {String} jid
* @param {String} text
* @param {String} footer
* @param {fs.PathLike} buffer
* @param {String|string[]} url
* @param {String|string[]} urlText
* @param {String|string[]} call
* @param {String|string[]} callText
* @param {String[][]} buttons
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo} quoted
* @param {Object} options
*/
async value(jid, text = '', footer = '', buffer, url, urlText, call, callText, buttons, quoted, options) {
let type
if (buffer) try { (type = await conn.getFile(buffer), buffer = type.data) } catch { buffer = buffer }
if (buffer && !Buffer.isBuffer(buffer) && (typeof buffer === 'string' || Array.isArray(buffer))) (options = quoted, quoted = buttons, buttons = callText, callText = call, call = urlText, urlText = url, url = buffer, buffer = null)
if (!options) options = {}
let templateButtons = []
if (url || urlText) {
if (!Array.isArray(url)) url = [url]
if (!Array.isArray(urlText)) urlText = [urlText]
templateButtons.push(...(
url.map((v, i) => [v, urlText[i]])
.map(([url, urlText], i) => ({
index: templateButtons.length + i + 1,
urlButton: {
displayText: !nullish(urlText) && urlText || !nullish(url) && url || '',
url: !nullish(url) && url || !nullish(urlText) && urlText || ''
}
})) || []
))
}
if (call || callText) {
if (!Array.isArray(call)) call = [call]
if (!Array.isArray(callText)) callText = [callText]
templateButtons.push(...(
call.map((v, i) => [v, callText[i]])
.map(([call, callText], i) => ({
index: templateButtons.length + i + 1,
callButton: {
displayText: !nullish(callText) && callText || !nullish(call) && call || '',
phoneNumber: !nullish(call) && call || !nullish(callText) && callText || ''
}
})) || []
))
}
if (buttons.length) {
if (!Array.isArray(buttons[0])) buttons = [buttons]
templateButtons.push(...(
buttons.map(([text, id], index) => ({
index: templateButtons.length + index + 1,
quickReplyButton: {
displayText: !nullish(text) && text || !nullish(id) && id || '',
id: !nullish(id) && id || !nullish(text) && text || ''
}
})) || []
))
}
let message = {
...options,
[buffer ? 'caption' : 'text']: text || '',
footer,
templateButtons,
...(buffer ?
options.asLocation && /image/.test(type.mime) ? {
location: {
...options,
jpegThumbnail: buffer
}
} : {
[/video/.test(type.mime) ? 'video' : /image/.test(type.mime) ? 'image' : 'document']: buffer
} : {})
}
return await conn.sendMessage(jid, message, {
quoted,
upload: conn.waUploadToServer,
...options
})
},
enumerable: true
},
sendHydrated2: {
/**
*
* @param {String} jid
* @param {String} text
* @param {String} footer
* @param {fs.PathLike} buffer
* @param {String|string[]} url
* @param {String|string[]} urlText
* @param {String|string[]} call
* @param {String|string[]} callText
* @param {String[][]} buttons
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo} quoted
* @param {Object} options
*/
async value(jid, text = '', footer = '', buffer, url, urlText, url2, urlText2, buttons, quoted, options) {
let type
if (buffer) try { (type = await conn.getFile(buffer), buffer = type.data) } catch { buffer = buffer }
if (buffer && !Buffer.isBuffer(buffer) && (typeof buffer === 'string' || Array.isArray(buffer))) (options = quoted, quoted = buttons, buttons = callText, callText = call, call = urlText, urlText = url, url = buffer, buffer = null)
if (!options) options = {}
let templateButtons = []
if (url || urlText) {
if (!Array.isArray(url)) url = [url]
if (!Array.isArray(urlText)) urlText = [urlText]
templateButtons.push(...(
url.map((v, i) => [v, urlText[i]])
.map(([url, urlText], i) => ({
index: templateButtons.length + i + 1,
urlButton: {
displayText: !nullish(urlText) && urlText || !nullish(url) && url || '',
url: !nullish(url) && url || !nullish(urlText) && urlText || ''
}
})) || []
))
}
if (url2 || urlText2) {
if (!Array.isArray(url2)) url2 = [url2]
if (!Array.isArray(urlText2)) urlText2 = [urlText2]
templateButtons.push(...(
url2.map((v, i) => [v, urlText2[i]])
.map(([url2, urlText2], i) => ({
index: templateButtons.length + i + 1,
urlButton: {
displayText: !nullish(urlText2) && urlText2 || !nullish(url2) && url2 || '',
url: !nullish(url2) && url2 || !nullish(urlText2) && urlText2 || ''
}
})) || []
))
}
if (buttons.length) {
if (!Array.isArray(buttons[0])) buttons = [buttons]
templateButtons.push(...(
buttons.map(([text, id], index) => ({
index: templateButtons.length + index + 1,
quickReplyButton: {
displayText: !nullish(text) && text || !nullish(id) && id || '',
id: !nullish(id) && id || !nullish(text) && text || ''
}
})) || []
))
}
let message = {
...options,
[buffer ? 'caption' : 'text']: text || '',
footer,
templateButtons,
...(buffer ?
options.asLocation && /image/.test(type.mime) ? {
location: {
...options,
jpegThumbnail: buffer
}
} : {
[/video/.test(type.mime) ? 'video' : /image/.test(type.mime) ? 'image' : 'document']: buffer
} : {})
}
return await conn.sendMessage(jid, message, {
quoted,
upload: conn.waUploadToServer,
...options
})
},
enumerable: true
},
cMod: {
/**
* cMod
* @param {String} jid
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo} message
* @param {String} text
* @param {String} sender
* @param {*} options
* @returns
*/
value(jid, message, text = '', sender = conn.user.jid, options = {}) {
if (options.mentions && !Array.isArray(options.mentions)) options.mentions = [options.mentions]
let copy = message.toJSON()
delete copy.message.messageContextInfo
delete copy.message.senderKeyDistributionMessage
let mtype = Object.keys(copy.message)[0]
let msg = copy.message
let content = msg[mtype]
if (typeof content === 'string') msg[mtype] = text || content
else if (content.caption) content.caption = text || content.caption
else if (content.text) content.text = text || content.text
if (typeof content !== 'string') {
msg[mtype] = { ...content, ...options }
msg[mtype].contextInfo = {
...(content.contextInfo || {}),
mentionedJid: options.mentions || content.contextInfo?.mentionedJid || []
}
}
if (copy.participant) sender = copy.participant = sender || copy.participant
else if (copy.key.participant) sender = copy.key.participant = sender || copy.key.participant
if (copy.key.remoteJid.includes('@s.whatsapp.net')) sender = sender || copy.key.remoteJid
else if (copy.key.remoteJid.includes('@broadcast')) sender = sender || copy.key.remoteJid
copy.key.remoteJid = jid
copy.key.fromMe = areJidsSameUser(sender, conn.user.id) || false
return proto.WebMessageInfo.fromObject(copy)
},
enumerable: true
},
copyNForward: {
/**
* Exact Copy Forward
* @param {String} jid
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo} message
* @param {Boolean|Number} forwardingScore
* @param {Object} options
*/
async value(jid, message, forwardingScore = true, options = {}) {
let vtype
if (options.readViewOnce && message.message.viewOnceMessage?.message) {
vtype = Object.keys(message.message.viewOnceMessage.message)[0]
delete message.message.viewOnceMessage.message[vtype].viewOnce
message.message = proto.Message.fromObject(
JSON.parse(JSON.stringify(message.message.viewOnceMessage.message))
)
message.message[vtype].contextInfo = message.message.viewOnceMessage.contextInfo
}
let mtype = Object.keys(message.message)[0]
let m = generateForwardMessageContent(message, !!forwardingScore)
let ctype = Object.keys(m)[0]
if (forwardingScore && typeof forwardingScore === 'number' && forwardingScore > 1) m[ctype].contextInfo.forwardingScore += forwardingScore
m[ctype].contextInfo = {
...(message.message[mtype].contextInfo || {}),
...(m[ctype].contextInfo || {})
}
m = generateWAMessageFromContent(jid, m, {
...options,
userJid: conn.user.jid
})
await conn.relayMessage(jid, m.message, { messageId: m.key.id, additionalAttributes: { ...options } })
return m
},
enumerable: true
},
fakeReply: {
/**
* Fake Replies
* @param {String} jid
* @param {String|Object} text
* @param {String} fakeJid
* @param {String} fakeText
* @param {String} fakeGroupJid
* @param {String} options
*/
value(jid, text = '', fakeJid = this.user.jid, fakeText = '', fakeGroupJid, options) {
return conn.reply(jid, text, { key: { fromMe: areJidsSameUser(fakeJid, conn.user.id), participant: fakeJid, ...(fakeGroupJid ? { remoteJid: fakeGroupJid } : {}) }, message: { conversation: fakeText }, ...options })
}
},
downloadM: {
/**
* Download media message
* @param {Object} m
* @param {String} type
* @param {fs.PathLike | fs.promises.FileHandle} saveToFile
* @returns {Promise<fs.PathLike | fs.promises.FileHandle | Buffer>}
*/
async value(m, type, saveToFile) {
let filename
if (!m || !(m.url || m.directPath)) return Buffer.alloc(0)
const stream = await downloadContentFromMessage(m, type)
let buffer = Buffer.from([])
for await (const chunk of stream) {
buffer = Buffer.concat([buffer, chunk])
}
if (saveToFile) ({ filename } = await conn.getFile(buffer, true))
return saveToFile && fs.existsSync(filename) ? filename : buffer
},
enumerable: true
},
parseMention: {
/**
* Parses string into mentionedJid(s)
* @param {String} text
* @returns {Array<String>}
*/
value(text = '') {
return [...text.matchAll(/@([0-9]{5,16}|0)/g)].map(v => v[1] + '@s.whatsapp.net')
},
enumerable: true
},
getName: {
/**
* Get name from jid
* @param {String} jid
* @param {Boolean} withoutContact
*/
value(jid = '', withoutContact = false) {
jid = conn.decodeJid(jid)
withoutContact = conn.withoutContact || withoutContact
let v
if (jid.endsWith('@g.us')) return new Promise(async (resolve) => {
v = conn.chats[jid] || {}
if (!(v.name || v.subject)) v = await conn.groupMetadata(jid) || {}
resolve(v.name || v.subject || PhoneNumber('+' + jid.replace('@s.whatsapp.net', '')).getNumber('international'))
})
else v = jid === '[email protected]' ? {
jid,
vname: 'WhatsApp'
} : areJidsSameUser(jid, conn.user.id) ?
conn.user :
(conn.chats[jid] || {})
return (withoutContact ? '' : v.name) || v.subject || v.vname || v.notify || v.verifiedName || PhoneNumber('+' + jid.replace('@s.whatsapp.net', '')).getNumber('international')
},
enumerable: true
},
loadMessage: {
/**
*
* @param {String} messageID
* @returns {import('@adiwajshing/baileys').proto.WebMessageInfo}
*/
value(messageID) {
return Object.entries(conn.chats)
.filter(([_, { messages }]) => typeof messages === 'object')
.find(([_, { messages }]) => Object.entries(messages)
.find(([k, v]) => (k === messageID || v.key?.id === messageID)))
?.[1].messages?.[messageID]
},
enumerable: true
},
sendGroupV4Invite: {
/**
* sendGroupV4Invite
* @param {String} jid
* @param {*} participant
* @param {String} inviteCode
* @param {Number} inviteExpiration
* @param {String} groupName
* @param {String} caption
* @param {Buffer} jpegThumbnail
* @param {*} options
*/
async value(jid, participant, inviteCode, inviteExpiration, groupName = 'unknown subject', caption = 'Invitation to join my WhatsApp group', jpegThumbnail, options = {}) {
const msg = proto.Message.fromObject({
groupInviteMessage: proto.GroupInviteMessage.fromObject({
inviteCode,
inviteExpiration: parseInt(inviteExpiration) || + new Date(new Date + (3 * 86400000)),
groupJid: jid,
groupName: (groupName ? groupName : await conn.getName(jid)) || null,
jpegThumbnail: Buffer.isBuffer(jpegThumbnail) ? jpegThumbnail : null,
caption
})
})
const message = generateWAMessageFromContent(participant, msg, options)
await conn.relayMessage(participant, message.message, { messageId: message.key.id, additionalAttributes: { ...options } })
return message
},
enumerable: true
},
processMessageStubType: {
/**
* to process MessageStubType
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo} m
*/
async value(m) {
if (!m.messageStubType) return
const chat = conn.decodeJid(m.key.remoteJid || m.message?.senderKeyDistributionMessage?.groupId || '')
if (!chat || chat === 'status@broadcast') return
const emitGroupUpdate = (update) => {
ev.emit('groups.update', [{ id: chat, ...update }])
}
switch (m.messageStubType) {
case WAMessageStubType.REVOKE:
case WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
emitGroupUpdate({ revoke: m.messageStubParameters[0] })
break
case WAMessageStubType.GROUP_CHANGE_ICON:
emitGroupUpdate({ icon: m.messageStubParameters[0] })
break
default: {
console.log({
messageStubType: m.messageStubType,
messageStubParameters: m.messageStubParameters,
type: WAMessageStubType[m.messageStubType]
})
break
}
}
const isGroup = chat.endsWith('@g.us')
if (!isGroup) return
let chats = conn.chats[chat]
if (!chats) chats = conn.chats[chat] = { id: chat }
chats.isChats = true
const metadata = await conn.groupMetadata(chat).catch(_ => null)
if (!metadata) return
chats.subject = metadata.subject
chats.metadata = metadata
}
},
insertAllGroup: {
async value() {
const groups = await conn.groupFetchAllParticipating().catch(_ => null) || {}
for (const group in groups) conn.chats[group] = { ...(conn.chats[group] || {}), id: group, subject: groups[group].subject, isChats: true, metadata: groups[group] }
return conn.chats
},
},
pushMessage: {
/**
* pushMessage
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo[]} m
*/
async value(m) {
if (!m) return
if (!Array.isArray(m)) m = [m]
for (const message of m) {
try {
// if (!(message instanceof proto.WebMessageInfo)) continue // https://github.com/adiwajshing/Baileys/pull/696/commits/6a2cb5a4139d8eb0a75c4c4ea7ed52adc0aec20f
if (!message) continue
if (message.messageStubType && message.messageStubType != WAMessageStubType.CIPHERTEXT) conn.processMessageStubType(message).catch(console.error)
const _mtype = Object.keys(message.message || {})
const mtype = (!['senderKeyDistributionMessage', 'messageContextInfo'].includes(_mtype[0]) && _mtype[0]) ||
(_mtype.length >= 3 && _mtype[1] !== 'messageContextInfo' && _mtype[1]) ||
_mtype[_mtype.length - 1]
const chat = conn.decodeJid(message.key.remoteJid || message.message?.senderKeyDistributionMessage?.groupId || '')
if (message.message?.[mtype]?.contextInfo?.quotedMessage) {
/**
* @type {import('@adiwajshing/baileys').proto.IContextInfo}
*/
let context = message.message[mtype].contextInfo
let participant = conn.decodeJid(context.participant)
const remoteJid = conn.decodeJid(context.remoteJid || participant)
/**
* @type {import('@adiwajshing/baileys').proto.IMessage}
*
*/
let quoted = message.message[mtype].contextInfo.quotedMessage
if ((remoteJid && remoteJid !== 'status@broadcast') && quoted) {
let qMtype = Object.keys(quoted)[0]
if (qMtype == 'conversation') {
quoted.extendedTextMessage = { text: quoted[qMtype] }
delete quoted.conversation
qMtype = 'extendedTextMessage'
}
if (!quoted[qMtype].contextInfo) quoted[qMtype].contextInfo = {}
quoted[qMtype].contextInfo.mentionedJid = context.mentionedJid || quoted[qMtype].contextInfo.mentionedJid || []
const isGroup = remoteJid.endsWith('g.us')
if (isGroup && !participant) participant = remoteJid
const qM = {
key: {
remoteJid,
fromMe: areJidsSameUser(conn.user.jid, remoteJid),
id: context.stanzaId,
participant,
},
message: JSON.parse(JSON.stringify(quoted)),
...(isGroup ? { participant } : {})
}
let qChats = conn.chats[participant]
if (!qChats) qChats = conn.chats[participant] = { id: participant, isChats: !isGroup }
if (!qChats.messages) qChats.messages = {}
if (!qChats.messages[context.stanzaId] && !qM.key.fromMe) qChats.messages[context.stanzaId] = qM
let qChatsMessages
if ((qChatsMessages = Object.entries(qChats.messages)).length > 40) qChats.messages = Object.fromEntries(qChatsMessages.slice(30, qChatsMessages.length)) // maybe avoid memory leak
}
}
if (!chat || chat === 'status@broadcast') continue
const isGroup = chat.endsWith('@g.us')
let chats = conn.chats[chat]
if (!chats) {
if (isGroup) await conn.insertAllGroup().catch(console.error)
chats = conn.chats[chat] = { id: chat, isChats: true, ...(conn.chats[chat] || {}) }
}
let metadata, sender
if (isGroup) {
if (!chats.subject || !chats.metadata) {
metadata = await conn.groupMetadata(chat).catch(_ => ({})) || {}
if (!chats.subject) chats.subject = metadata.subject || ''
if (!chats.metadata) chats.metadata = metadata
}
sender = conn.decodeJid(message.key?.fromMe && conn.user.id || message.participant || message.key?.participant || chat || '')
if (sender !== chat) {
let chats = conn.chats[sender]
if (!chats) chats = conn.chats[sender] = { id: sender }
if (!chats.name) chats.name = message.pushName || chats.name || ''
}
} else if (!chats.name) chats.name = message.pushName || chats.name || ''
if (['senderKeyDistributionMessage', 'messageContextInfo'].includes(mtype)) continue
chats.isChats = true
if (!chats.messages) chats.messages = {}
const fromMe = message.key.fromMe || areJidsSameUser(sender || chat, conn.user.id)
if (!['protocolMessage'].includes(mtype) && !fromMe && message.messageStubType != WAMessageStubType.CIPHERTEXT && message.message) {
delete message.message.messageContextInfo
delete message.message.senderKeyDistributionMessage
chats.messages[message.key.id] = JSON.parse(JSON.stringify(message, null, 2))
let chatsMessages
if ((chatsMessages = Object.entries(chats.messages)).length > 40) chats.messages = Object.fromEntries(chatsMessages.slice(30, chatsMessages.length))
}
} catch (e) {
console.error(e)
}
}
}
},
serializeM: {
/**
* Serialize Message, so it easier to manipulate
* @param {import('@adiwajshing/baileys').proto.WebMessageInfo} m
*/
value(m) {
return smsg(conn, m)
}
},
...(typeof conn.chatRead !== 'function' ? {
chatRead: {
/**
* Read message
* @param {String} jid
* @param {String|undefined|null} participant
* @param {String} messageID
*/
value(jid, participant = conn.user.jid, messageID) {
return conn.sendReadReceipt(jid, participant, [messageID])
},
enumerable: true
}
} : {}),
...(typeof conn.setStatus !== 'function' ? {
setStatus: {
/**
* setStatus bot
* @param {String} status
*/
value(status) {
return conn.query({
tag: 'iq',
attrs: {
to: S_WHATSAPP_NET,
type: 'set',
xmlns: 'status',
},
content: [
{
tag: 'status',
attrs: {},
content: Buffer.from(status, 'utf-8')
}
]
})
},
enumerable: true
}
} : {})
})
if (sock.user?.id) sock.user.jid = sock.decodeJid(sock.user.id)
store.bind(sock)
return sock
}
Example #13
Source File: games-_tictactoe.js From HinataMd with GNU General Public License v3.0 | 4 votes |
export async function before(m) {
let ok
let isWin = !1
let isTie = !1
let isSurrender = !1
this.game = this.game ? this.game : {}
let room = Object.values(this.game).find(room => room.id && room.game && room.state && room.id.startsWith('tictactoe') && [room.game.playerX, room.game.playerO].includes(m.sender) && room.state == 'PLAYING')
if (room) {
// m.reply(`[DEBUG]\n${parseInt(m.text)}`)
if (!/^([1-9]|(me)?nyerah|surr?ender)$/i.test(m.text))
return !0
isSurrender = !/^[1-9]$/.test(m.text)
if (m.sender !== room.game.currentTurn) { // nek wayahku
if (!isSurrender)
return !0
}
if (debugMode)
m.reply('[DEBUG]\n' + require('util').format({
isSurrender,
text: m.text
}))
if (!isSurrender && 1 > (ok = room.game.turn(m.sender === room.game.playerO, parseInt(m.text) - 1))) {
m.reply({
'-3': 'Game telah berakhir',
'-2': 'Invalid',
'-1': 'Posisi Invalid',
0: 'Posisi Invalid',
}[ok])
return !0
}
if (m.sender === room.game.winner)
isWin = true
else if (room.game.board === 511)
isTie = true
let arr = room.game.render().map(v => {
return {
X: '❌',
O: '⭕',
1: '1️⃣',
2: '2️⃣',
3: '3️⃣',
4: '4️⃣',
5: '5️⃣',
6: '6️⃣',
7: '7️⃣',
8: '8️⃣',
9: '9️⃣',
}[v]
})
if (isSurrender) {
room.game._currentTurn = m.sender === room.game.playerX
isWin = true
}
let winner = isSurrender ? room.game.currentTurn : room.game.winner
let str = `
${arr.slice(0, 3).join('')}
${arr.slice(3, 6).join('')}
${arr.slice(6).join('')}
${isWin ? `@${winner.split('@')[0]} Menang! (+${winScore} XP)` : isTie ? `Game berakhir (+${playScore} XP)` : `Giliran ${['❌', '⭕'][1 * room.game._currentTurn]} (@${room.game.currentTurn.split('@')[0]})`}
❌: @${room.game.playerX.split('@')[0]}
⭕: @${room.game.playerO.split('@')[0]}
Ketik *nyerah* untuk nyerah
Room ID: ${room.id}
`.trim()
let users = global.db.data.users
if ((room.game._currentTurn ^ isSurrender ? room.x : room.o) !== m.chat)
room[room.game._currentTurn ^ isSurrender ? 'x' : 'o'] = m.chat
const btn = isTie ? ['TicTacToe', '/ttt'] : ['Nyerah', 'nyerah']
if (room.x !== room.o)
await this.sendButton(room.x, str, author, btn, m, {
mentions: this.parseMention(str)
})
await this.sendButton(room.o, str, author, btn, m, {
mentions: this.parseMention(str)
})
if (isTie || isWin) {
users[room.game.playerX].exp += playScore
users[room.game.playerO].exp += playScore
if (isWin)
users[winner].exp += winScore - playScore
if (debugMode)
m.reply('[DEBUG]\n' + format(room))
delete this.game[room.id]
}
}
return !0
}
Example #14
Source File: Tabs-test.js From Lambda with MIT License | 4 votes |
describe('<Tabs />', () => {
beforeEach(() => resetIdCounter());
beforeAll(() => {
// eslint-disable-next-line no-console
console.error = (error, ...args) => {
if (args.length > 0 && typeof error === 'string') {
if (error.endsWith('%s%s')) {
throw new Error(format(error.slice(0, -2), ...args.slice(0, -1)));
}
throw new Error(format(error, ...args));
}
throw new Error(error);
};
});
describe('props', () => {
test('should have sane defaults', () => {
expectToMatchSnapshot(createTabs());
});
test('should honor positive defaultIndex prop', () => {
expectToMatchSnapshot(createTabs({ defaultIndex: 1 }));
});
test('should honor negative defaultIndex prop', () => {
expectToMatchSnapshot(createTabs({ defaultIndex: -1 }));
});
test('should call onSelect when selection changes', () => {
const called = { index: -1, last: -1 };
render(
createTabs({
onSelect(index, last) {
called.index = index;
called.last = last;
},
}),
);
userEvent.click(screen.getByTestId('tab2'));
expect(called.index).toBe(1);
expect(called.last).toBe(0);
});
test('should accept className', () => {
expectToMatchSnapshot(createTabs({ className: 'foobar' }));
});
test('should accept domRef', () => {
let domNode;
render(
createTabs({
domRef: (node) => {
domNode = node;
},
}),
);
expect(domNode).not.toBeUndefined();
expect(domNode.className).toBe('react-tabs');
});
});
describe('child props', () => {
test('should reset ids correctly', () => {
expectToMatchSnapshot(createTabs());
resetIdCounter();
expectToMatchSnapshot(createTabs());
});
});
describe('interaction', () => {
describe('mouse', () => {
test('should update selectedIndex when clicked', () => {
render(createTabs());
userEvent.click(screen.getByTestId('tab2'));
assertTabSelected(2);
});
test('should update selectedIndex when tab child is clicked', () => {
render(createTabs());
userEvent.click(screen.getByTestId('tab3'));
assertTabSelected(3);
});
test('should not change selectedIndex when clicking a disabled tab', () => {
render(createTabs({ defaultIndex: 0 }));
userEvent.click(screen.getByTestId('tab4'));
assertTabSelected(1);
});
});
describe('keyboard', () => {
test('should update selectedIndex when arrow right key pressed', () => {
render(createTabs());
const element = screen.getByTestId('tab1');
userEvent.click(element);
userEvent.type(element, '{arrowright}');
assertTabSelected(2);
});
test('should update selectedIndex when arrow left key pressed (RTL)', () => {
render(createTabs({ direction: 'rtl' }));
const element = screen.getByTestId('tab1');
userEvent.click(element);
userEvent.type(element, '{arrowleft}');
assertTabSelected(2);
});
test.skip('should not change selectedIndex when arrow left key pressed on a disabled tab', () => {
render(createTabs());
const element = screen.getByTestId('tab4');
userEvent.click(element);
userEvent.type(element, '{arrowleft}');
assertTabSelected(1);
});
});
});
describe('performance', () => {
test('should only render the selected tab panel', () => {
render(createTabs());
const tabPanels = screen.getAllByRole('tabpanel');
expect(tabPanels[0]).toHaveTextContent('Hello Tab1');
expect(tabPanels[1]).toHaveTextContent('');
expect(tabPanels[2]).toHaveTextContent('');
expect(tabPanels[3]).toHaveTextContent('');
userEvent.click(screen.getByTestId('tab2'));
expect(tabPanels[0]).toHaveTextContent('');
expect(tabPanels[1]).toHaveTextContent('Hello Tab2');
expect(tabPanels[2]).toHaveTextContent('');
expect(tabPanels[3]).toHaveTextContent('');
userEvent.click(screen.getByTestId('tab3'));
expect(tabPanels[0]).toHaveTextContent('');
expect(tabPanels[1]).toHaveTextContent('');
expect(tabPanels[2]).toHaveTextContent('Hello Tab3');
expect(tabPanels[3]).toHaveTextContent('');
});
test('should render all tabs if forceRenderTabPanel is true', () => {
expectToMatchSnapshot(createTabs({ forceRenderTabPanel: true }));
});
});
describe('validation', () => {
test('should result with warning when tabs/panels are imbalanced', () => {
expect(() =>
render(
<Tabs>
<TabList>
<Tab>Foo</Tab>
</TabList>
</Tabs>,
),
).toThrowErrorMatchingSnapshot();
});
test('should result with warning when tab outside of tablist', () => {
expect(() =>
render(
<Tabs>
<TabList>
<Tab>Foo</Tab>
</TabList>
<Tab>Foo</Tab>
<TabPanel />
<TabPanel />
</Tabs>,
),
).toThrowErrorMatchingSnapshot();
});
test('should result with warning when multiple tablist components exist', () => {
expect(() =>
render(
<Tabs>
<TabList>
<Tab>Foo</Tab>
</TabList>
<TabList>
<Tab>Foo</Tab>
</TabList>
<TabPanel />
<TabPanel />
</Tabs>,
),
).toThrowErrorMatchingSnapshot();
});
test('should result with warning when onSelect missing when selectedIndex set', () => {
expect(() =>
render(
<Tabs selectedIndex={1}>
<TabList>
<Tab>Foo</Tab>
</TabList>
<TabPanel>Foo</TabPanel>
</Tabs>,
),
).toThrowErrorMatchingSnapshot();
});
test('should result with warning when defaultIndex and selectedIndex set', () => {
expect(() =>
render(
<Tabs selectedIndex={1} defaultIndex={1}>
<TabList>
<Tab>Foo</Tab>
</TabList>
<TabPanel>Foo</TabPanel>
</Tabs>,
),
).toThrowErrorMatchingSnapshot();
});
test('should result with warning when tabs/panels are imbalanced and it should ignore non tab children', () => {
expect(() =>
render(
<Tabs>
<TabList>
<Tab>Foo</Tab>
<div>+</div>
</TabList>
<TabPanel>Hello Foo</TabPanel>
<TabPanel>Hello Bar</TabPanel>
</Tabs>,
),
).toThrowErrorMatchingSnapshot();
});
test('should allow random order for elements', () => {
expectToMatchSnapshot(
<Tabs forceRenderTabPanel>
<TabPanel>Hello Foo</TabPanel>
<TabList>
<Tab>Foo</Tab>
<Tab>Bar</Tab>
</TabList>
<TabPanel>Hello Bar</TabPanel>
</Tabs>,
);
});
test('should not throw a warning when wrong element is found', () => {
expectToMatchSnapshot(
<Tabs>
<TabList>
<Tab />
<div />
</TabList>
<TabPanel />
</Tabs>,
);
});
test('should be okay with rendering without any children', () => {
expectToMatchSnapshot(<Tabs />);
});
test('should be okay with rendering just TabList', () => {
expectToMatchSnapshot(
<Tabs>
<TabList />
</Tabs>,
);
});
test('should gracefully render null', () => {
expectToMatchSnapshot(
<Tabs>
<TabList>
<Tab>Tab A</Tab>
{false && <Tab>Tab B</Tab>}
</TabList>
<TabPanel>Content A</TabPanel>
{false && <TabPanel>Content B</TabPanel>}
</Tabs>,
);
});
test('should support nested tabs', () => {
render(
<Tabs data-testid="first">
<TabList>
<Tab data-testid="tab1" />
<Tab />
</TabList>
<TabPanel data-testid="panel1">
Hello Tab1
<Tabs data-testid="second">
<TabList>
<Tab />
<Tab data-testid="tab2" />
</TabList>
<TabPanel />
<TabPanel data-testid="panel2">Hello Tab2</TabPanel>
</Tabs>
</TabPanel>
<TabPanel />
</Tabs>,
);
userEvent.click(within(screen.getByTestId('second')).getByTestId('tab2'));
assertTabSelected(1);
assertTabSelected(2, within(screen.getByTestId('second')));
});
test('should allow other DOM nodes', () => {
expectToMatchSnapshot(
<Tabs>
<div id="tabs-nav-wrapper">
<button type="button">Left</button>
<div className="tabs-container">
<TabList>
<Tab />
<Tab />
</TabList>
</div>
<button type="button">Right</button>
</div>
<div className="tab-panels">
<TabPanel />
<TabPanel />
</div>
</Tabs>,
);
});
});
test('should pass through custom properties', () => {
expectToMatchSnapshot(<Tabs data-tooltip="Tooltip contents" />);
});
test('should not add known props to dom', () => {
expectToMatchSnapshot(<Tabs defaultIndex={3} />);
});
test('should cancel if event handler returns false', () => {
render(createTabs({ onSelect: () => false }));
assertTabSelected(1);
userEvent.click(screen.getByTestId('tab2'));
assertTabSelected(1);
userEvent.click(screen.getByTestId('tab3'));
assertTabSelected(1);
});
test('should trigger onSelect handler when clicking', () => {
let wasClicked = false;
render(
createTabs({
onSelect: () => {
wasClicked = true;
},
}),
);
assertTabSelected(1);
userEvent.click(screen.getByTestId('tab2'));
assertTabSelected(2);
expect(wasClicked).toBe(true);
});
test('should trigger onSelect handler when clicking on open tab', () => {
let wasClicked = false;
render(
createTabs({
onSelect: () => {
wasClicked = true;
},
}),
);
assertTabSelected(1);
userEvent.click(screen.getByTestId('tab1'));
assertTabSelected(1);
expect(wasClicked).toBe(true);
});
test('should switch tabs if setState is called within onSelect', () => {
class Wrap extends React.Component {
state = {};
handleSelect = () => this.setState({ foo: 'bar' });
render() {
const { foo } = this.state;
return createTabs({
onSelect: this.handleSelect,
className: foo,
});
}
}
render(<Wrap />);
userEvent.click(screen.getByTestId('tab2'));
assertTabSelected(2);
userEvent.click(screen.getByTestId('tab3'));
assertTabSelected(3);
});
test('should allow for higher order components', () => {
expectToMatchSnapshot(
<Tabs>
<TabListWrapper>
<TabWrapper>Foo</TabWrapper>
<TabWrapper>Bar</TabWrapper>
</TabListWrapper>
<TabPanelWrapper>Foo</TabPanelWrapper>
<TabPanelWrapper>Bar</TabPanelWrapper>
</Tabs>,
);
});
test('should allow string children', () => {
expectToMatchSnapshot(
<Tabs>
Foo
<TabList>
Foo
<Tab>Foo</Tab>
Foo
<Tab>Bar</Tab>
Foo
</TabList>
<TabPanel>Bar</TabPanel>
<TabPanel>Foo</TabPanel>
Foo
</Tabs>,
);
});
});