Create a Whatsapp Bot using WhiskeySocket/Baileys Library
create a connection to connect using pairing code
const { makeWASocket } = require("@whiskeysockets/baileys");
const Pino = require("pino");
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const runBot = process.argv[0];
async function connectToWhatsapp() {
// Configuring the Connection
const sock = makeWASocket({
printQRInTerminal: false,
browser: ["Chrome (Windows)", "", ""],
logger: Pino({ level: "silent" })
});
// Function Send Pairing Code
function sendPairingCode() {
rl.question("Enter Number Whatsapp: +", number => {
setTimeout(async () => {
const code = await sock.requestPairingCode(number);
console.log(code);
rl.close();
}, 4000);
});
}
// Executes the function of sending the pairing code
if (runBot && !sock.authState.creds.registered) {
sendPairingCode();
}
// Listening to Connection Updates
sock.ev.on("connection.update", c => {
const { connection, lastDisconnect } = c;
if (connection === "close") {
connectToWhatsapp();
} else if (connection === "open") {
rl.close();
console.log(`Connected ${sock.user.id.split(":")[0]}`);
}
});
}
// Run in main file
connectToWhatsapp();You can configure the connection a makeWASocket object
const sock = makeWASocket({
auth: AuthenticationState, // Provide an auth state object to maintain the auth state
printQRInTerminal: boolean, // Should the QR be printed in the terminal
browser: WABrowserDescription, // Override browser config
connectTimeoutMs: number, // Fails the connection if the socket times out in this interval
keepAliveIntervalMs: number, // Ping-Pong interval for WS connection
defaultQueryTimeoutMs: number | undefined, // Default timeout for queries, undefined for no timeout
logger: Logger, // Pino Logger
syncFullHistory: boolean, // Should Baileys ask the phone for full history, will be received async
generateHighQualityLinkPreview: boolean, // Generate a high quality link preview, entails uploading the jpegThumbnail to WA
})if don't want to keep asking for a pairing code every time you want to connect.
const {useMultiFileAuthState} = require("@whiskeysockets/baileys");
const { state, saveCreds } = await useMultiFileAuthState("session");
const sock = makeWASocket({
...otherOptions,
auth: state
})
sock.ev.on("creds.update", saveCreds);You can listen to these events like this:
sock.ev.on('messages.upsert', ({ messages }) => {
console.log('got messages', messages)
})You can sending message with a single function
Example:
sock.ev.on('messages.upsert', async ({ messages }) => {
const msg = messages[0]
const id = msg.key.remoteJid // "62xxx@s.whatsapp.net"
if (!msg.message) return;
const [typeMsg] = Object.keys(msg.message);
const msgText = typeMsg === "conversation"
? msg.message.conversation
: "";
const msgExt = typeMsg === "extendedTextMessage"
? msg.message.extendedTextMessage.text
: "";
if(msgText.startsWith(".test")) {
// Send a simple text
await sock.sendMessage(id, { text : "Hello"})
// Send a reply message
await sock.sendMessage(id, { text : "Hello" }, {quoted:msg})
// Send a location
await sock.sendMessage( id, {
location: {
degreesLatitude: 24.121281,
degreesLongitude: 55.1121221
}
})
// Send a contact
const vcard = 'BEGIN:VCARD\n'
+ 'VERSION:3.0\n'
+ 'FN:Zelt Namizake\n'
+ 'ORG:IDK;\n'
+ 'TEL;type=CELL;type=VOICE;waid=6283137789511:+62 831 3778-9511\n'
+ 'END:VCARD'
await sock.sendMessage( id,
{
contacts: {
displayName: 'Zelt',
contacts: [{ vcard }]
}
}
)
// Send a image
await socket.sendMessage( id,
{
image: {url: `path/file.jpg`},
mimetype: "image/jpeg",
caption: "Send a image"
}
)
// Send a video gif
await socket.sendMessage( id,
{
video: {url: `path/file.mp4`},
mimetype: "video/mp4",
caption: "Send a video"
}
)
// Send a gif
await socket.sendMessage( id,
{
video: {url: `path/file.mp4`},
mimetype: "video/mp4",
gifPlayback: true
}
)
// Send a audio
await socket.sendMessage( id,
{
audio: {url: `path/file.mp3`},
mimetype: "audio/mp4",
}
)
// Send a document
await socket.sendMessage( id,
{
document: {url: `path/file.pdf`},
mimetype: "application/pdf",
fileName: "document"
}
)
}
})- @whiskeysockets/baileys@6.4.0. I recommend using this version of the library because I think it is the most stable.