Skip to content

Instantly share code, notes, and snippets.

@yusufusta
Created September 14, 2022 13:55
Show Gist options
  • Save yusufusta/49e30d6dbb50516d97e0bd4d9622961d to your computer and use it in GitHub Desktop.
Save yusufusta/49e30d6dbb50516d97e0bd4d9622961d to your computer and use it in GitHub Desktop.
const P = require('pino')
const { delay, DisconnectReason, useSingleFileAuthState } = require('@adiwajshing/baileys')
const makeWASocket = require('@adiwajshing/baileys').default;
// start a connection
const startSock = () => {
const { state, saveState } = useSingleFileAuthState('./auth.json')
const sock = makeWASocket({
logger: P({ level: 'fatal' }),
printQRInTerminal: true,
auth: state,
});
const sendMessageWTyping = async (msg, jid) => {
await sock.presenceSubscribe(jid)
await delay(500)
await sock.sendPresenceUpdate('composing', jid)
await delay(2000)
await sock.sendPresenceUpdate('paused', jid)
await sock.sendMessage(jid, msg)
}
sock.ev.on('chats.set', item => console.log(`recv ${item.chats.length} chats (is latest: ${item.isLatest})`))
sock.ev.on('messages.set', item => console.log(`recv ${item.messages.length} messages (is latest: ${item.isLatest})`))
sock.ev.on('contacts.set', item => console.log(`recv ${item.contacts.length} contacts`))
sock.ev.on('messages.upsert', async m => {
console.log(JSON.stringify(m, undefined, 2))
const msg = m.messages[0]
if (!msg.key.fromMe && m.type === 'notify') {
console.log('replying to', m.messages[0].key.remoteJid)
await sendMessageWTyping({ text: 'maraba amk' }, msg.key.remoteJid)
}
})
sock.ev.on('messages.update', m => console.log(m))
sock.ev.on('message-receipt.update', m => console.log(m))
sock.ev.on('presence.update', m => console.log(m))
sock.ev.on('chats.update', m => console.log(m))
sock.ev.on('contacts.upsert', m => console.log(m))
sock.ev.on('creds.update', saveState)
sock.ev.on('connection.update', function (update, connection2) {
let _a, _b;
let connection = update.connection, lastDisconnect = update.lastDisconnect;
if (connection === 'close') {
// reconnect if not logged out
if (((_b = (_a = lastDisconnect.error) === null || _a === void 0 ? void 0 : _a.output) === null || _b === void 0 ? void 0 : _b.statusCode) !== DisconnectReason.loggedOut) {
startSock()
}
else {
console.log('connection closed');
}
}
console.log('connection update', update);
});
return sock
}
startSock()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment