@mengkodingan/ckptw
Version:
Create powerful WhatsApp bots easily
311 lines (310 loc) • 15.4 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Client = void 0;
const baileys_1 = __importStar(require("@whiskeysockets/baileys"));
const pino_1 = __importDefault(require("pino"));
const events_1 = __importDefault(require("events"));
const Events_1 = require("../Constant/Events");
const collection_1 = require("@discordjs/collection");
const Ctx_1 = require("./Ctx");
const Functions_1 = require("../Common/Functions");
const MessageEvents_1 = require("../Handler/MessageEvents");
const PHONENUMBER_MCC_1 = require("../Constant/PHONENUMBER_MCC");
const consolefy_1 = require("@mengkodingan/consolefy");
const ExtractEventsContent_1 = __importDefault(require("../Handler/ExtractEventsContent"));
class Client {
constructor(opts) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
this.prefix = opts.prefix;
this.readIncommingMsg = (_a = opts.readIncommingMsg) !== null && _a !== void 0 ? _a : false;
this.authDir = (_b = opts.authDir) !== null && _b !== void 0 ? _b : './state';
this.printQRInTerminal = (_c = opts.printQRInTerminal) !== null && _c !== void 0 ? _c : true;
this.phoneNumber = opts.phoneNumber;
this.usePairingCode = (_d = opts.usePairingCode) !== null && _d !== void 0 ? _d : false;
this.qrTimeout = (_e = opts.qrTimeout) !== null && _e !== void 0 ? _e : 60000;
this.markOnlineOnConnect = (_f = opts.markOnlineOnConnect) !== null && _f !== void 0 ? _f : true;
this.logger = (_g = opts.logger) !== null && _g !== void 0 ? _g : (0, pino_1.default)({ level: "fatal" });
this.selfReply = (_h = opts.selfReply) !== null && _h !== void 0 ? _h : false;
this.WAVersion = opts.WAVersion;
this.autoMention = (_j = opts.autoMention) !== null && _j !== void 0 ? _j : false;
this.fallbackWAVersion = [2, 3000, 1025144028];
this.authAdapter = (_k = opts.authAdapter) !== null && _k !== void 0 ? _k : (0, baileys_1.useMultiFileAuthState)(this.authDir);
this.browser = (_l = opts.browser) !== null && _l !== void 0 ? _l : baileys_1.Browsers.ubuntu('CHROME');
this.ev = new events_1.default();
this.cmd = new collection_1.Collection();
this.cooldown = new collection_1.Collection();
this.hearsMap = new collection_1.Collection();
this.middlewares = new collection_1.Collection();
this.consolefy = new consolefy_1.Consolefy();
if (typeof this.prefix === "string")
this.prefix = this.prefix.split('');
}
onConnectionUpdate() {
var _a;
(_a = this.core) === null || _a === void 0 ? void 0 : _a.ev.on('connection.update', (update) => {
var _a, _b, _c, _d;
this.ev.emit(Events_1.Events.ConnectionUpdate, update);
const { connection, lastDisconnect } = update;
if (update.qr)
this.ev.emit(Events_1.Events.QR, update.qr);
if (connection === 'close') {
const shouldReconnect = ((_b = (_a = lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error) === null || _a === void 0 ? void 0 : _a.output) === null || _b === void 0 ? void 0 : _b.statusCode) !== baileys_1.DisconnectReason.loggedOut;
(_c = this.consolefy) === null || _c === void 0 ? void 0 : _c.error('connection closed due to ', lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error, ', reconnecting ', shouldReconnect);
if (shouldReconnect)
this.launch();
}
else if (connection === 'open') {
this.readyAt = Date.now();
(_d = this.ev) === null || _d === void 0 ? void 0 : _d.emit(Events_1.Events.ClientReady, this.core);
}
});
}
onCredsUpdate() {
var _a;
(_a = this.core) === null || _a === void 0 ? void 0 : _a.ev.on("creds.update", this.saveCreds);
}
read(m) {
var _a;
(_a = this.core) === null || _a === void 0 ? void 0 : _a.readMessages([
{
remoteJid: m.key.remoteJid,
id: m.key.id,
participant: m.key.participant
},
]);
}
use(fn) {
var _a;
(_a = this.middlewares) === null || _a === void 0 ? void 0 : _a.set(this.middlewares.size, fn);
}
runMiddlewares(ctx, index = 0) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const middlewareFn = (_a = this.middlewares) === null || _a === void 0 ? void 0 : _a.get(index);
if (!middlewareFn)
return true;
let nextCalled = false;
let chainCompleted = false;
yield middlewareFn(ctx, () => __awaiter(this, void 0, void 0, function* () {
nextCalled = true;
chainCompleted = yield this.runMiddlewares(ctx, index + 1);
}));
return nextCalled && chainCompleted;
});
}
onMessage() {
var _a;
(_a = this.core) === null || _a === void 0 ? void 0 : _a.ev.on("messages.upsert", (m) => __awaiter(this, void 0, void 0, function* () {
var _b;
let msgType = (0, baileys_1.getContentType)(m.messages[0].message);
let text = (0, Functions_1.getContentFromMsg)(m.messages[0]);
m.content = null;
if (text === null || text === void 0 ? void 0 : text.length)
m.content = text;
m.messageType = msgType;
m = Object.assign(Object.assign({}, m), m.messages[0]);
delete m.messages;
let self = Object.assign(Object.assign({}, this), { getContentType: baileys_1.getContentType, downloadContentFromMessage: baileys_1.downloadContentFromMessage, proto: baileys_1.proto, m });
let used = (0, ExtractEventsContent_1.default)(m, msgType);
let ctx = new Ctx_1.Ctx({ used, args: [], self, client: this.core });
if (MessageEvents_1.MessageEventList[msgType]) {
yield MessageEvents_1.MessageEventList[msgType](m, this.ev, self, this.core);
}
(_b = this.ev) === null || _b === void 0 ? void 0 : _b.emit(Events_1.Events.MessagesUpsert, m, ctx);
if (this.readIncommingMsg)
this.read(m);
yield require('../Handler/Commands')(self, this.runMiddlewares.bind(this));
}));
}
onGroupParticipantsUpdate() {
var _a;
(_a = this.core) === null || _a === void 0 ? void 0 : _a.ev.on("group-participants.update", (m) => __awaiter(this, void 0, void 0, function* () {
if (m.action === "add")
return this.ev.emit(Events_1.Events.UserJoin, m);
if (m.action === "remove")
return this.ev.emit(Events_1.Events.UserLeave, m);
}));
}
onGroupsJoin() {
var _a;
(_a = this.core) === null || _a === void 0 ? void 0 : _a.ev.on('groups.upsert', (m) => {
this.ev.emit(Events_1.Events.GroupsJoin, m);
});
}
onCall() {
var _a;
(_a = this.core) === null || _a === void 0 ? void 0 : _a.ev.on('call', (m) => {
let withDecodedId = m.map(v => (Object.assign(Object.assign({}, v), { decodedFrom: (0, Functions_1.decodeJid)(v.from), decodedChatId: (0, Functions_1.decodeJid)(v.chatId) })));
this.ev.emit(Events_1.Events.Call, withDecodedId);
});
}
/**
* Create a new command.
* @param opts Command options object or command name string.
* @param code If the first parameter is a command name as a string, then you should create a callback function in second parameter.
* @example
* ```
* bot.command('ping', async(ctx) => ctx.reply({ text: 'Pong!' }));
*
* // same as
*
* bot.command({
* name: 'ping',
* code: async(ctx) => {
* ctx.reply('Pong!');
* }
* });
* ```
*/
command(opts, code) {
var _a, _b;
if (typeof opts !== 'string')
return (_a = this.cmd) === null || _a === void 0 ? void 0 : _a.set(this.cmd.size, opts);
if (!code)
code = () => __awaiter(this, void 0, void 0, function* () { return null; });
return (_b = this.cmd) === null || _b === void 0 ? void 0 : _b.set(this.cmd.size, { name: opts, code });
}
/**
* "Callback" will be triggered when someone sends the "query" in the chats. Hears function like command but without command prefix.
* @param query The trigger.
* @param callback Callback function
*/
hears(query, callback) {
this.hearsMap.set(this.hearsMap.size, { name: query, code: callback });
}
/**
* Set the bot bio/about.
* @param content The bio content.
*/
bio(content) {
var _a;
(_a = this.core) === null || _a === void 0 ? void 0 : _a.query({
tag: "iq",
attrs: {
to: "@s.whatsapp.net",
type: "set",
xmlns: "status",
},
content: [
{
tag: "status",
attrs: {},
content,
},
],
});
}
/**
* Fetch bio/about from given Jid or if the param empty will fetch the bot bio/about.
* @param [jid] the jid.
*/
fetchBio(jid) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
let decodedJid = (0, Functions_1.decodeJid)(jid ? jid : (_b = (_a = this.core) === null || _a === void 0 ? void 0 : _a.user) === null || _b === void 0 ? void 0 : _b.id);
let re = yield ((_c = this.core) === null || _c === void 0 ? void 0 : _c.fetchStatus(decodedJid));
return re;
});
}
/**
* All the groups that the bot joins.
*/
groups() {
return __awaiter(this, void 0, void 0, function* () {
return yield this.core.groupFetchAllParticipating();
});
}
decodeJid(jid) {
return (0, Functions_1.decodeJid)(jid);
}
launch() {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
return __awaiter(this, void 0, void 0, function* () {
const { state, saveCreds } = yield this.authAdapter;
this.state = state;
this.saveCreds = saveCreds;
const version = this.WAVersion ? this.WAVersion : this.fallbackWAVersion;
this.core = (0, baileys_1.default)({
logger: this.logger,
printQRInTerminal: this.printQRInTerminal,
auth: this.state,
browser: this.browser,
version,
qrTimeout: this.qrTimeout,
markOnlineOnConnect: this.markOnlineOnConnect
});
if (this.usePairingCode && !this.core.authState.creds.registered) {
(_a = this.consolefy) === null || _a === void 0 ? void 0 : _a.setTag("pairing-code");
if (this.printQRInTerminal) {
(_b = this.consolefy) === null || _b === void 0 ? void 0 : _b.error("If you are set the usePairingCode to true then you need to set printQRInTerminal to false.");
(_c = this.consolefy) === null || _c === void 0 ? void 0 : _c.resetTag();
return;
}
if (!this.phoneNumber) {
(_d = this.consolefy) === null || _d === void 0 ? void 0 : _d.error("The phoneNumber options are required if you are using usePairingCode.");
(_e = this.consolefy) === null || _e === void 0 ? void 0 : _e.resetTag();
return;
}
this.phoneNumber = this.phoneNumber.replace(/[^0-9]/g, '');
if (!this.phoneNumber.length) {
(_f = this.consolefy) === null || _f === void 0 ? void 0 : _f.error("Invalid phoneNumber.");
(_g = this.consolefy) === null || _g === void 0 ? void 0 : _g.resetTag();
return;
}
if (!PHONENUMBER_MCC_1.PHONENUMBER_MCC.some(v => this.phoneNumber.startsWith(v))) {
(_h = this.consolefy) === null || _h === void 0 ? void 0 : _h.error("phoneNumber format must be like: 62xxx (starts with the country code).");
(_j = this.consolefy) === null || _j === void 0 ? void 0 : _j.resetTag();
return;
}
setTimeout(() => __awaiter(this, void 0, void 0, function* () {
var _k, _l;
const code = yield this.core.requestPairingCode(this.phoneNumber);
(_k = this.consolefy) === null || _k === void 0 ? void 0 : _k.info(`Pairing Code: ${code}`);
(_l = this.consolefy) === null || _l === void 0 ? void 0 : _l.resetTag();
}), 3000);
}
this.onConnectionUpdate();
this.onCredsUpdate();
this.onMessage();
this.onGroupParticipantsUpdate();
this.onGroupsJoin();
this.onCall();
});
}
}
exports.Client = Client;