@kamuridesu/whatframework
Version:
A simple WhatsApp Bot Framework on top of Baileys
227 lines (226 loc) • 9.74 kB
JavaScript
import Pino from 'pino';
import { makeWASocket, DisconnectReason, useMultiFileAuthState, makeCacheableSignalKeyStore } from '@whiskeysockets/baileys';
import { Language } from "../../libs/lang/language.js";
import { parseMedia } from '../funcs/mediaParsers.js';
import { checkJidInTextAndConvert } from '../../libs/text.js';
import { parseMessage } from '../funcs/parser.js';
const logger = Pino().child({
level: 'trace',
stream: 'store',
});
// const storage = makeInMemoryStore({ logger });
// storage.readFromFile("./states/baileys_storage_dump.json");
// setInterval(() => {
// storage.writeToFile("./states/baileys_storage_dump.json");
// }, 10_000);
const { state, saveCreds, } = await useMultiFileAuthState('./states/auth');
class WABot {
constructor(name = 'bot', prefix = '!', ownerNumber = '', language = '') {
var _a;
this.connection = undefined;
this.name = name;
this.prefix = prefix;
this.botNumber = (_a = state.creds.me) === null || _a === void 0 ? void 0 : _a.id;
this.ownerNumber = ownerNumber;
this.language = language;
this.reconnectOnClose = true;
this.lang = new Language(this).get();
this.groupsData = {}; // This is for caching purpose, details @ src/funcs/parsers.ts#145
}
async getMessage(key) {
// if (storage) {
// const msg = await storage.loadMessage(key.remoteJid!,
// key.id!)
// return msg?.message || undefined
// }
// only if store is present
return undefined;
}
async init(messageHandler) {
this.connection = makeWASocket({
printQRInTerminal: true,
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, logger)
},
getMessage: this.getMessage,
version: [2, 3000, 1015901307]
});
this.connection.ev.on('creds.update', saveCreds);
this.connection.ev.on('connection.update', (update) => {
var _a, _b, _c;
this.botNumber = (_a = state.creds.me) === null || _a === void 0 ? void 0 : _a.id.replace(/:\d+/, "");
const { connection, lastDisconnect } = update;
if (connection === 'close') {
const shouldReconnect = ((_c = (_b = lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error) === null || _b === void 0 ? void 0 : _b.output) === null || _c === void 0 ? void 0 : _c.statusCode) !== DisconnectReason.loggedOut;
console.log('connection closed due to ', lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error, ', reconnecting ', shouldReconnect);
// reconnect if not logged out
if (shouldReconnect) {
this.init(messageHandler);
}
}
else if (connection === 'open') {
console.log('opened connection');
}
});
// storage.bind(this.connection.ev);
this.connection.ev.on('messages.upsert', async (handle) => {
for (let message of handle.messages) {
if (!message.key.fromMe && handle.type === "notify") {
messageHandler.handle(message, this);
}
}
});
this.connection.ev.on("messages.reaction", async (handle) => {
for (let reaction of handle) {
// console.log((reaction));
}
});
this.connection.ev.on("group-participants.update", async (handle) => {
if (handle.action == "add") {
return messageHandler.handleNewMember(handle, this);
}
if (handle.action == "remove") {
return messageHandler.handleRemoveMember(handle, this);
}
});
}
async getGroups() {
var _a;
return (await ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.groupFetchAllParticipating()));
}
async replyText(ctx, text, options = {}) {
options.quoted = ctx.originalMessage;
return await this.sendTextMessage(ctx, text, options);
}
async replyMedia(ctx, media, messageType, mimeType, mediaCaption, options = {}) {
var _a, _b, _c, _d;
let sentMessage = undefined;
try {
await ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.presenceSubscribe(ctx.author.chatJid));
await ((_b = this.connection) === null || _b === void 0 ? void 0 : _b.sendPresenceUpdate('recording', ctx.author.chatJid));
const params = await parseMedia(media, messageType, mimeType, mediaCaption);
const response = await ((_c = this.connection) === null || _c === void 0 ? void 0 : _c.sendMessage(ctx.author.chatJid, params, Object.assign({ quoted: ctx.originalMessage }, options)));
if (response)
sentMessage = await parseMessage(response, this);
await ((_d = this.connection) === null || _d === void 0 ? void 0 : _d.sendPresenceUpdate("paused", ctx.author.chatJid));
}
catch (e) {
console.error(e);
sentMessage = await this.replyText(ctx, this.lang.sendingMediaError);
}
finally {
return sentMessage;
}
}
async sendTextMessage(ctx, text, options) {
var _a, _b, _c, _d;
let recipient;
if (typeof ctx != "string" && ctx.originalMessage) {
recipient = ctx.author.chatJid;
}
else {
recipient = ctx.toString();
}
let sentMessage = undefined;
try {
const textData = checkJidInTextAndConvert(text);
if (options != undefined && options.mentions) {
textData.mentions = textData.mentions.concat(options.mentions);
}
let messageData = {
text: textData.text,
mentions: textData.mentions,
};
if (options.edit != undefined) {
messageData.edit = options.edit;
delete options.edit;
}
await ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.presenceSubscribe(recipient));
await ((_b = this.connection) === null || _b === void 0 ? void 0 : _b.sendPresenceUpdate("composing", recipient));
const response = await ((_c = this.connection) === null || _c === void 0 ? void 0 : _c.sendMessage(recipient, messageData, options));
if (response)
sentMessage = await parseMessage(response, this);
await ((_d = this.connection) === null || _d === void 0 ? void 0 : _d.sendPresenceUpdate("paused", recipient));
}
catch (e) {
console.error(e);
}
finally {
return sentMessage;
}
}
async reactMessage(ctx, reactionMessage, options) {
var _a, _b, _c;
let recipient;
if (typeof ctx != "string" && ctx.originalMessage) {
recipient = ctx.author.chatJid;
}
else {
recipient = ctx.toString();
}
let sentMessage = undefined;
try {
await ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.presenceSubscribe(recipient));
const response = await ((_b = this.connection) === null || _b === void 0 ? void 0 : _b.sendMessage(recipient, reactionMessage, options == undefined ? {} : options));
if (response)
sentMessage = await parseMessage(response, this);
await ((_c = this.connection) === null || _c === void 0 ? void 0 : _c.sendPresenceUpdate("paused", recipient));
}
catch (e) {
console.error(e);
}
finally {
return sentMessage;
}
}
async createPoll(ctx, pollName, options) {
var _a;
console.log(pollName);
console.log(options);
try {
console.log("creting poll");
console.log(await ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.sendMessage(ctx.author.chatJid, {
poll: {
name: pollName,
values: options,
selectableCount: options.length
},
})));
console.log("done");
return true;
}
catch (e) {
console.error(e);
return false;
}
}
async loadMessage(ctx) {
// let originJid: string;
// let stanzaId: string;
// if (ctx instanceof Message) {
// if (!ctx.hasQuotedMessage || ctx.quotedMessageType != "conversation") {
// return undefined;
// }
// originJid = ctx.author.chatJid;
// stanzaId = ctx.quotedMessage?.originalMessage.key?.id!;
// } else {
// if (!ctx.remoteJid || !ctx.id) {
// return undefined;
// }
// originJid = ctx.remoteJid;
// stanzaId = ctx.id;
// }
// const messageInformation = await this.loadMessageById(originJid, stanzaId);
// return messageInformation != undefined ? (ctx instanceof Message ? parseMessage(messageInformation, this) : messageInformation) : undefined;
return undefined;
}
async loadMessageById(originJid, stanzaId) {
// const messageInformation = await storage.loadMessage(originJid, stanzaId);
// if (messageInformation) {
// return messageInformation;
// }
return undefined;
}
}
export { WABot as Bot };