0% found this document useful (0 votes)
113 views8 pages

Baileys WhatsApp Bot Setup Guide

This document contains code for connecting a WhatsApp bot to the WhatsApp network and handling various events like messages, calls, contacts updates, and group participants updates. It includes functions for sending messages, images, contacts, getting profile photos and names, and more. The code imports and requires various Node.js modules and libraries like Baileys, Axios, FileType, Lodash, and others.

Uploaded by

Peter Joshua
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views8 pages

Baileys WhatsApp Bot Setup Guide

This document contains code for connecting a WhatsApp bot to the WhatsApp network and handling various events like messages, calls, contacts updates, and group participants updates. It includes functions for sending messages, images, contacts, getting profile photos and names, and more. The code imports and requires various Node.js modules and libraries like Baileys, Axios, FileType, Lodash, and others.

Uploaded by

Peter Joshua
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
  • Initialization and Setup
  • Database Configuration
  • Event Handling
  • Contact Management
  • Message Handling
  • Data Streams Handling
  • Media Handling
  • Error Handling and Reconnection

/*

› Create By qio
› Base Ori qio

☆KALAU MAU RENAME TARO CREDITS GUA : HW MODS WA☆ */

require('./qioo')
const { default: makeWASocket, useMultiFileAuthState, DisconnectReason,
fetchLatestBaileysVersion, generateForwardMessageContent, prepareWAMessageMedia,
generateWAMessageFromContent, generateMessageID, downloadContentFromMessage,
makeInMemoryStore, jidDecode, getAggregateVotesInPollMessage, proto } =
require("@whiskeysockets/baileys")
const fs = require('fs')
const pino = require('pino')
const chalk = require('chalk')
const path = require('path')
const readline = require("readline");
const axios = require('axios')
const FileType = require('file-type')
const yargs = require('yargs/yargs')
const _ = require('lodash')
const { Boom } = require('@hapi/boom')
const PhoneNumber = require('awesome-phonenumber')
const usePairingCode = true
const { imageToWebp, videoToWebp, writeExifImg, writeExifVid } =
require('./lib/exif')
const { smsg, isUrl, generateMessageTag, getBuffer, getSizeMedia, fetchJson, await,
sleep } = require('./lib/myfunc')
const question = (text) => {
const rl = [Link]({
input: [Link],
output: [Link]
});
return new Promise((resolve) => {
[Link](text, resolve)
})
};
//=================================================//
var low
try {
low = require('lowdb')
} catch (e) {
low = require('./lib/lowdb')}
//=================================================//
const { Low, JSONFile } = low
const mongoDB = require('./lib/mongoDB')
//=================================================//
//=================================================//
const store = makeInMemoryStore({ logger: pino().child({ level: 'silent', stream:
'store' }) })
//=================================================//
[Link] = new Object(yargs([Link](2)).exitProcess(false).parse())
[Link] = new Low(
/https?:\/\//.test(opts['db'] || '') ?
new cloudDBAdapter(opts['db']) : /mongodb/.test(opts['db']) ?
new mongoDB(opts['db']) :
new JSONFile(`./src/[Link]`)
)
[Link] = [Link] // Backwards Compatibility
[Link] = async function loadDatabase() {
if ([Link]) return new Promise((resolve) => setInterval(function () { (!
[Link] ? (clearInterval(this), resolve([Link] == null ?
[Link]() : [Link])) : null) }, 1 * 1000))
if ([Link] !== null) return
[Link] = true
await [Link]()
[Link] = false
[Link] = {
users: {},
chats: {},
game: {},
database: {},
settings: {},
setting: {},
others: {},
sticker: {},
...([Link] || {})}
[Link] = _.chain([Link])}
loadDatabase()
//=================================================//
//=================================================//
async function connectToWhatsApp() {
const { state, saveCreds } = await useMultiFileAuthState([Link])
const qio = makeWASocket({
logger: pino({ level: "silent" }),
printQRInTerminal: !usePairingCode,
auth: state,
browser: ['Chrome (Linux)', '', '']
});
if(usePairingCode && ![Link]) {
const phoneNumber = await question('mohon di masukin gan nomor bot lu
supaya terhubung dengan Qioo V5 di awali dengan 62:\n');
const code = await [Link]([Link]())
[Link](`Pairing code: ${code}`)

}
//=================================================//
[Link] = (jid) => {
if (!jid) return jid
if (/:\d+@/[Link](jid)) {
let decode = jidDecode(jid) || {}
return [Link] && [Link] && [Link] + '@' + [Link] || jid
} else return jid
}
//=================================================//
[Link]('[Link]', async chatUpdate => {
try {
mek = [Link][0]
if (![Link]) return
[Link] = ([Link]([Link])[0] === 'ephemeralMessage') ?
[Link] : [Link]
if ([Link] && [Link] === 'status@broadcast') return
if (![Link] && ![Link] && [Link] === 'notify') return
if ([Link]('BAE5') && [Link] === 16) return
m = smsg(qio, mek, store)
require("./qio")(qio, m, chatUpdate, store)
} catch (err) {
[Link](err)
}
})

[Link]('call', async (celled) => {


let botNumber = await [Link]([Link])
let koloi = [Link]
if (!koloi) return
[Link](celled)
for (let kopel of celled) {
if ([Link] == false) {
if ([Link] == "offer") {
let nomer = await [Link]([Link], `*${[Link]}* tidak
bisa menerima panggilan ${[Link] ? `video` : `suara`}. Maaf @$
{[Link]('@')[0]} kamu akan diblokir. Silahkan hubungi Owner membuka
blok !`)
[Link]([Link], [Link]( i => [Link]("@")[0]), nomer)
await sleep(8000)
await [Link]([Link], "block")
}
}
}
})
//=================================================//
[Link]('[Link]', async (anu) => {
if (![Link]([Link])) return
[Link](anu)
try {
let metadata = await [Link]([Link])
let participants = [Link]
for (let num of participants) {
// Get Profile Picture User
try {
ppuser = await [Link](num, 'image')
} catch {
ppuser = '[Link]
973460_960_720.png?q=60'
}

// Get Profile Picture Group


try {
ppgroup = await [Link]([Link], 'image')
} catch {
ppgroup = '[Link]
973460_960_720.png?q=60'
}

if ([Link] == 'add') {
[Link]([Link], { image: { url: ppuser }, mentions: [num], caption: `Haii
Kak *@${[Link]("@")[0]}* Selamat Datang Di Group *${[Link]}* 👋
▬▭▬▭▬▭▬▭▬▬▭▬▭▬
Terima Kasih Sudah Bergabung Jangan Lupa Baca Deskripsi Yah
▬▭▬▭▬▭▬▭▬▬▭▬▭▬
Creator : [Link]
} else if ([Link] == 'remove') {
[Link]([Link], { image: { url: ppuser }, mentions: [num], caption: `Karena
Untuk Setiap Ucapan Selamat Datang Akan Selalu Diakhiri Dengan Ucapan Selamat
Tinggal 👋
▬▭▬▭▬▭▬▭▬▬▭▬▭▬
Selamat Tinggal *@${[Link]("@")[0]}* Di Group *${[Link]}*
▬▭▬▭▬▭▬▭▬▬▭▬▭▬
Creator : [Link]
} else if ([Link] == 'promote') {
[Link]([Link], { image: { url: ppuser }, mentions: [num], caption: `@$
{[Link]('@')[0]} Ciee Jadi Admin Di Group ${[Link]} ${[Link]}`
})
} else if ([Link] == 'demote') {
[Link]([Link], { image: { url: ppuser }, mentions: [num], caption: `@$
{[Link]('@')[0]} Ciee Di Hapus Jadi Admin Di Group ${[Link]} $
{[Link]}`})
}
}
} catch (err) {
[Link](err)
}
})
//=================================================//
[Link]('[Link]', update => {
for (let contact of update) {
let id = [Link]([Link])
if (store && [Link]) [Link][id] = { id, name: [Link] }}})
//=================================================//
[Link] = (jid, withoutContact = false) => {
id = [Link](jid)
withoutContact = [Link] || withoutContact
let v
if ([Link]("@[Link]")) return new Promise(async (resolve) => {
v = [Link][id] || {}
if (!([Link] || [Link])) v = [Link](id) || {}
resolve([Link] || [Link] || PhoneNumber('+' + [Link]('@[Link]',
'')).getNumber('international'))
})
else v = id === '0@[Link]' ? {
id,
name: 'WhatsApp'
} : id === [Link]([Link]) ?
[Link] :
([Link][id] || {})
return (withoutContact ? '' : [Link]) || [Link] || [Link] ||
PhoneNumber('+' + [Link]('@[Link]', '')).getNumber('international')}
//=================================================//
[Link] = async (jid, kon, quoted = '', opts = {}) => {
let list = []
for (let i of kon) {
[Link]({
displayName: await [Link](i + '@[Link]'),
vcard: `BEGIN:VCARD\nVERSION:3.0\nN:${await [Link](i + '@[Link]')}\
nFN:${await [Link](i + '@[Link]')}\[Link];waid=${i}:${i}\nitem1.X-
ABLabel:Ponsel\[Link];type=INTERNET:aplusscell@[Link]\nitem2.X-
ABLabel:Email\[Link]:[Link]
ABLabel:Instagram\[Link]:;;Indonesia;;;;\nitem4.X-ABLabel:Region\nEND:VCARD`})}
//=================================================//
[Link](jid, { contacts: { displayName: `${[Link]} Kontak`, contacts:
list }, ...opts }, { quoted })}
//=================================================//
//Kalau Mau Self Lu Buat Jadi false
[Link] = true
//=================================================//
//=================================================//
[Link]('[Link]', saveCreds)
//=================================================//
[Link] = async (message) => {
let mime = ([Link] || message).mimetype || ''
let messageType = [Link] ? [Link](/Message/gi, '') :
[Link]('/')[0]
const stream = await downloadContentFromMessage(message, messageType)
let buffer = [Link]([])
for await(const chunk of stream) {
buffer = [Link]([buffer, chunk])}
return buffer}
//=================================================//
[Link] = async (jid, path, caption = '', quoted = '', options) => {
let buffer = [Link](path) ? path : /^data:.*?\/.*?;base64,/[Link](path) ?
[Link]([Link]`,`[1], 'base64') : /^https?:\/\//.test(path) ? await (await
getBuffer(path)) : [Link](path) ? [Link](path) : [Link](0)
return await [Link](jid, { image: buffer, caption: caption, ...options },
{ quoted })}
//=================================================//
[Link] = (jid, text, quoted = '', options) => [Link](jid, { text:
text, ...options }, { quoted })
//=================================================//
[Link] = async (jid, text, quoted, options = {}) =>
[Link](jid, { text: text, contextInfo: { mentionedJid:
[...[Link](/@(\d{0,16})/g)].map(v => v[1] + '@[Link]') }, ...options
}, { quoted })
//=================================================//
[Link] = async (jid, path, quoted, options = {}) => {
let buff = [Link](path) ? path : /^data:.*?\/.*?;base64,/[Link](path) ?
[Link]([Link]`,`[1], 'base64') : /^https?:\/\//.test(path) ? await (await
getBuffer(path)) : [Link](path) ? [Link](path) : [Link](0)
let buffer
if (options && ([Link] || [Link])) {
buffer = await writeExifImg(buff, options)
} else {
buffer = await imageToWebp(buff)}
await [Link](jid, { sticker: { url: buffer }, ...options }, { quoted })
return buffer}
//=================================================//
[Link] = async (jid, path, quoted, options = {}) => {
let buff = [Link](path) ? path : /^data:.*?\/.*?;base64,/[Link](path) ?
[Link]([Link]`,`[1], 'base64') : /^https?:\/\//.test(path) ? await (await
getBuffer(path)) : [Link](path) ? [Link](path) : [Link](0)
let buffer
if (options && ([Link] || [Link])) {
buffer = await writeExifVid(buff, options)
} else {
buffer = await videoToWebp(buff)}
await [Link](jid, { sticker: { url: buffer }, ...options }, { quoted })
return buffer}
//=================================================//
[Link] = async (message, filename, attachExtension =
true) => {
let quoted = [Link] ? [Link] : message
let mime = ([Link] || message).mimetype || ''
let messageType = [Link] ? [Link](/Message/gi, '') :
[Link]('/')[0]
const stream = await downloadContentFromMessage(quoted, messageType)
let buffer = [Link]([])
for await(const chunk of stream) {
buffer = [Link]([buffer, chunk])}
let type = await [Link](buffer)
trueFileName = attachExtension ? (filename + '.' + [Link]) : filename
// save to file
await [Link](trueFileName, buffer)
return trueFileName}
//=================================================
[Link] = (jid, copy, text = '', sender = [Link], options = {}) => {
//let copy = [Link]()
let mtype = [Link]([Link])[0]
let isEphemeral = mtype === 'ephemeralMessage'
if (isEphemeral) {
mtype = [Link]([Link])[0]}
let msg = isEphemeral ? [Link] : [Link]
let content = msg[mtype]
if (typeof content === 'string') msg[mtype] = text || content
else if ([Link]) [Link] = text || [Link]
else if ([Link]) [Link] = text || [Link]
if (typeof content !== 'string') msg[mtype] = {
...content,
...options}
if ([Link]) sender = [Link] = sender ||
[Link]
else if ([Link]) sender = [Link] = sender ||
[Link]
if ([Link]('@[Link]')) sender = sender ||
[Link]
else if ([Link]('@broadcast')) sender = sender ||
[Link]
[Link] = jid
[Link] = sender === [Link]
return [Link](copy)}
[Link] = async(jid, PATH, fileName, quoted = {}, options = {}) => {
let types = await [Link](PATH, true)
let { filename, size, ext, mime, data } = types
let type = '', mimetype = mime, pathFile = filename
if ([Link]) type = 'document'
if ([Link] || /webp/.test(mime)) {
let { writeExif } = require('./lib/[Link]')
let media = { mimetype: mime, data }
pathFile = await writeExif(media, { packname: [Link], author:
global.packname2, categories: [Link] ? [Link] : [] })
await [Link](filename)
type = 'sticker'
mimetype = 'image/webp'}
else if (/image/.test(mime)) type = 'image'
else if (/video/.test(mime)) type = 'video'
else if (/audio/.test(mime)) type = 'audio'
else type = 'document'
await [Link](jid, { [type]: { url: pathFile }, mimetype,
fileName, ...options }, { quoted, ...options })
return [Link](pathFile)}
[Link] = async(text) => {
return [...[Link](/@([0-9]{5,16}|0)/g)].map(v => v[1] + '@[Link]')}
//=================================================//
[Link] = async (jid, message, forceForward = false, options = {}) => {
let vtype
if ([Link]) {
[Link] = [Link] && [Link] &&
[Link] ? [Link]
: ([Link] || undefined)
vtype = [Link]([Link])[0]
delete([Link] && [Link] ? [Link] :
([Link] || undefined))
delete [Link][vtype].viewOnce
[Link] = {
...[Link]}}
let mtype = [Link]([Link])[0]
let content = await generateForwardMessageContent(message, forceForward)
let ctype = [Link](content)[0]
let context = {}
if (mtype != "conversation") context = [Link][mtype].contextInfo
content[ctype].contextInfo = {
...context,
...content[ctype].contextInfo}
const waMessage = await generateWAMessageFromContent(jid, content, options ? {
...content[ctype],
...options,
...([Link] ? {
contextInfo: {
...content[ctype].contextInfo,
...[Link]}} : {})} : {})
await [Link](jid, [Link], { messageId: [Link] })
return waMessage}
//=================================================//
[Link] = async (PATH, save) => {
let res
let data = [Link](PATH) ? PATH : /^data:.*?\/.*?;base64,/[Link](PATH) ?
[Link]([Link]`,`[1], 'base64') : /^https?:\/\//.test(PATH) ? await (res =
await getBuffer(PATH)) : [Link](PATH) ? (filename = PATH,
[Link](PATH)) : typeof PATH === 'string' ? PATH : [Link](0)
//if (![Link](data)) throw new TypeError('Result is not a buffer')
let type = await [Link](data) || {
mime: 'application/octet-stream',
ext: '.bin'
}
filename = [Link](__filename, '../src/' + new Date * 1 + '.' + [Link])
if (data && save) [Link](filename, data)
return {
res,
filename,
size: await getSizeMedia(data),
...type,
data
}
}
[Link] = (m) => smsg(qio, m, store)
[Link]("[Link]", async (update) => {
const { connection, lastDisconnect } = update;
if (connection === "close") {
let reason = new Boom(lastDisconnect?.error)?.[Link];
if (reason === [Link]) {
[Link](`Bad Session File, Please Delete Session and Scan Again`);
[Link]();
} else if (reason === [Link]) {
[Link]("Connection closed, reconnecting....");
connectToWhatsApp();
} else if (reason === [Link]) {
[Link]("Connection Lost from Server, reconnecting...");
connectToWhatsApp();
} else if (reason === [Link]) {
[Link]("Connection Replaced, Another New Session Opened, Please Restart Bot");
[Link]();
} else if (reason === [Link]) {
[Link](`Device Logged Out, Please Delete Folder Session yusril and Scan
Again.`);
[Link]();
} else if (reason === [Link]) {
[Link]("Restart Required, Restarting...");
connectToWhatsApp();
} else if (reason === [Link]) {
[Link]("Connection TimedOut, Reconnecting...");
connectToWhatsApp();
} else {
[Link](`Unknown DisconnectReason: ${reason}|${connection}`);
connectToWhatsApp();
}
} else if (connection === "open") {
[Link]('62887082474470' + "@[Link]", { text: `*SUKSES TERHUBUNG
DENGAN QIOO V5` });
}
// [Link]('Connected...', update)
});
return qio
}
connectToWhatsApp()
let file = [Link](__filename)
[Link](file, () => {
[Link](file)
[Link]([Link](`Update ${__filename}`))
delete [Link][file]
require(file)
})

/*
› Create By qio
› Base Ori qio
 KALAU MAU RENAME TARO CREDITS GUA : HW MODS WA☆ */
☆
require('./qioo')
const { default: ma
global.loadDatabase = async function loadDatabase() {
if (global.db.READ) return new Promise((resolve) => setInterval(functio
}
})
qio.ev.on('call', async (celled) => {
let botNumber = await qio.decodeJid(qio.user.id)
let koloi = global.anticall
if (!
▬▬▬▬▬▬▬▬
▭▭▭▭
▭▭
Creator : https://wa.me/62887082474470`})
} else if (anu.action == 'promote') {
qio.sendMessage(anu.id, { im
qio.ev.on('creds.update', saveCreds)
 //=================================================//
 qio.downloadMediaMessage = async
for await(const chunk of stream) {
buffer = Buffer.concat([buffer, chunk])}
let type = await FileType.fromBuffer(buffer)
true
message.message = message.message && message.message.ephemeralMessage && 
message.message.ephemeralMessage.message ? message.
} else if (reason === DisconnectReason.connectionLost) {
console.log("Connection Lost from Server, reconnecting...");
conne

You might also like