Skip to content

Instantly share code, notes, and snippets.

@LighteningCode
Created March 17, 2022 00:47
Show Gist options
  • Save LighteningCode/6608c6490468452873a85085dc53784e to your computer and use it in GitHub Desktop.
Save LighteningCode/6608c6490468452873a85085dc53784e to your computer and use it in GitHub Desktop.
Managing sessions in a bot locally for NodeJS (wwebjs)
const { Client, LocalAuth } = require("whatsapp-web.js");
const Session = require("./context").default;
let ServerSession = new Session()
/** function to check if participant isAdmin
* @param {any} participants this is the array of participants from the group https://docs.wwebjs.dev/GroupChat.html#participants
* @param {any} senderContact this is the object of the msg.getContact() https://docs.wwebjs.dev/Message.html#getContact
*/
function isAdmin(participants, senderContact) {
const foundParticipant = participants.find((participant) => {
return senderContact.id.user.includes(participant.id.user);
});
return foundParticipant.isAdmin;
}
// instantiate client
const client = new Client()
// handle QR events and all others
client.on("message", async (msg) => {
const chat = await msg.getChat();
const sessionId = chat?.id._serialized.toString() //you can choose what ever you wish
let currentSession;
currentSession = _Session.getSession(sessionId)
if (!currentSession) {
// if session doesnt exist create new session
const sessionObject = {
message: "No Message",
// you can add more objects here
};
_Session.setSession(sessionId, sessionObject);
console.log("<<<<<<<<< Session Saved >>>>>>>>")
currentSession = sessionObject
}
// saving data
if (msg.body == "!save") {
let newSessionData = { ...currentSession, message: "Hello data saved" }
ServerSession.setSession(sessionId, newSessionData) //save data in session
}
// getting data
if (msg.body == "!fetch") {
if(isAdmin(chat.participants, msg.getContact())){
let message = currentSession.message //access session data
msg.reply(message)
} else{
msg.reply("Only Admins can fetch")
}
}
})
// You can create a new file like this
class Session {
// this is just to make sure you are isolating data that pertains to multiple groups
constructor() {
this.sessions = {};
}
getSession(sessionId) {
const _session = this.sessions[sessionId];
console.log("Getting",sessionId, _session)
return _session ? _session : null;
}
setSession(sessionId, userData) {
if (this.sessions[sessionId]) {
Object.assign(this.sessions[sessionId], userData);
return;
}
this.sessions[sessionId] = userData;
}
}
// take note
exports.default = Session;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment