Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keshav pahwa #1

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
.DS_Store
node_modules/
node_modules
build/Release
*.env
.env.test
Expand Down
83 changes: 68 additions & 15 deletions BotsApp.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,87 @@
const conn = require('./core/sessionString')
const fs = require('fs')
const { join } = require('path')
const config = require('./config')
const banner = require('./lib/banner');
const chalk = require('chalk');
const wa = require('./core/helper');
const { MessageType } = require('@adiwajshing/baileys');

const client = conn.WhatsApp;
var client = conn.WhatsApp;

async function BotsApp() {
async function main() {

client.logger.level = 'debug'
client.logger.level = 'error'
console.log(banner);
var session = conn.restoreSession(config.STRING_SESSION)
var commandHandler = new Map();
try{
var session = conn.restoreSession(config.STRING_SESSION)
client.loadAuthInfo(session)
} catch(err) {
if (err instanceof TypeError || err.message === "given authInfo is null"){
if(config.STRING_SESSION === ''){
console.log(
chalk.redBright.bold("Please create a String Session first using command -> " + chalk.yellowBright.bold("node qr.js")));
}
if (err instanceof TypeError || err.message === "given authInfo is null" || err instanceof SyntaxError){
console.log(
chalk.redBright.bold("Incorrect Session String. Please authenticate again using command -> "),
chalk.yellowBright.bold("npm start")
);
console.debug("[DEBUG] " + err);
fs.writeFileSync('./config.env', `STRING_SESSION=""`);
process.exit(0);
}
else {
console.log(chalk.redBright.bold(err))
console.log(
chalk.redBright.bold("SOMETHING WENT WRONG.\n"),
chalk.redBright.bold("[DEBUG] " + err)
);
process.exit(0)
}
}
await client.connect()
client.on('chat-update', async (upd) => {
console.log(upd)

client.on('connecting', async () => {
console.log(chalk.yellowBright("[INFO] Connecting to WhatsApp..."));
})

client.on('open', async () => {
console.log(chalk.greenBright.bold("[INFO] Connected! Welcome to BotsApp"));
console.log(chalk.whiteBright.bold("[INFO] Installing Plugins... Please wait."));
var moduleFiles = fs.readdirSync(join(__dirname, 'modules')).filter((file) => file.endsWith('.js'))
for(var file of moduleFiles){
const command = require(join(__dirname, 'modules', `${file}`));
console.log(
chalk.magentaBright("[INFO] Successfully imported module"),
chalk.cyanBright.bold(`${file}`)
)
commandHandler.set(command.name, command);
}
console.log(chalk.green.bold("[INFO] Plugins Installed Successfully. The bot is ready to use."));
})


await client.connect();
client.on('chat-update', async chat => {
if (!chat.hasNewMessage) return
if (!chat.messages) return
console.log("-------------------------------------------")
var sender = chat.messages.all()[0].key.remoteJid;
const groupMetadata = sender.endsWith("@g.us") ? await client.groupMetadata(sender) : '';
var BotsApp = wa.resolve(chat.messages.all()[0], client, groupMetadata);
console.log(BotsApp);
// if(BotsApp.from === "917838204238@s.whatsapp.net" && BotsApp.fromMe === false){ client.sendMessage(BotsApp.from, "xD", MessageType.text)}
if(BotsApp.isCmd){
const command = commandHandler.get(BotsApp.commandName);
if(!command){
client.sendMessage(BotsApp.from, "Woops, incorrect command! Use .help for command list.", MessageType.text);
return;
}
var args = BotsApp.body.trim().split(/\s+/).slice(1);
console.log(args);
console.log("-------------------------------------------")
try{
command.handle(client, chat, BotsApp, args);
}catch(err){
console.log(chalk.red("[ERROR] ", err));
}
}
})
}

console.log(config.STRING_SESSION);
BotsApp();
main().catch(err => console.log('[ERROR] : %s', chalk.redBright.bold(err)));
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Changelog
All notable changes to this add-on will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and
this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Changed
- [core/sessionString.js] Authenticate when bot has first been executed
- [BotsApp.js] Better Session handling
- [package.json] Add npm scripts
- [qr.js] Authenticate Session Asynchronously

### Added
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
<div align="center">
<h1>BotsApp</h1>
<h2>Your Personal Assisstant, on WhatsApp!</h2>
</div>
# BotsApp
## Your Personal Assisstant, on WhatsApp!

## Starting the bot

```bash
git clone https://github.com/DTU-DCODER/BotsApp.git
cd BotsApp
npm install
npm start
```
3 changes: 2 additions & 1 deletion config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ if (fs.existsSync('config.env')){

const env = {
STRING_SESSION: process.env.STRING_SESSION === undefined ? '' : process.env.STRING_SESSION,
HEROKU: process.env.HEROKU === undefined ? false : true
HEROKU: process.env.HEROKU === undefined ? false : true,
PREFIX: process.env.PREFIX === undefined ? /^[.?!]/g : process.env.PREFIX
}

module.exports = env
41 changes: 41 additions & 0 deletions core/helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const fs = require('fs')
const config = require('../config')
var BotsAppClass = require("../sidekick/sidekick")


exports.resolve = function(messageInstance, client, groupMetadata) {
var BotsApp = new BotsAppClass();
var prefixRegex = config.PREFIX;
console.log(messageInstance);
console.log(JSON.stringify(messageInstance));
BotsApp.mimeType = messageInstance.message ? Object.keys(messageInstance.message)[0] : null;
BotsApp.type = BotsApp.mimeType === 'imageMessage' ? 'image' : (BotsApp.mimeType === 'videoMessage') ? 'video' : (BotsApp.mimeType === 'conversation' || BotsApp.mimeType == 'extendedTextMessage') ? 'text' : (BotsApp.mimeType === 'audioMessage') ? 'audio' : (BotsApp.mimeType === 'stickerMessage') ? 'sticker' : '';
BotsApp.isReply = BotsApp.mimeType === 'extendedTextMessage';
BotsApp.body = BotsApp.mimeType === 'conversation' ? messageInstance.message.conversation : (BotsApp.mimeType == 'imageMessage') ? messageInstance.message.imageMessage.caption : (BotsApp.mimeType == 'videoMessage') ? messageInstance.message.videoMessage.caption : (BotsApp.mimeType == 'extendedTextMessage') ? messageInstance.message.extendedTextMessage.text : '';
BotsApp.isCmd = prefixRegex.test(BotsApp.body);
BotsApp.commandName = BotsApp.isCmd ? BotsApp.body.slice(1).trim().split(/ +/).shift().toLowerCase() : '';
BotsApp.from = messageInstance.key.remoteJid || '';
BotsApp.fromMe = messageInstance.key.fromMe;
BotsApp.owner = client.user.jid || '';
BotsApp.logGroup = client.user.jid || '';
BotsApp.isGroup = BotsApp.from.endsWith('@g.us');
BotsApp.isPm = !BotsApp.isGroup;
BotsApp.sender = (BotsApp.isGroup && messageInstance.message) ? messageInstance.participant : '';
BotsApp.groupName = BotsApp.isGroup ? groupMetadata.subject : '';
BotsApp.groupMembers = BotsApp.isGroup ? groupMetadata.participants : '';
BotsApp.groupAdmins = BotsApp.isGroup ? getGroupAdmins(BotsApp.groupMembers) : '';
BotsApp.groupId = BotsApp.isGroup ? groupMetadata.id : '';
BotsApp.isBotGroupAdmin = BotsApp.isGroup ? BotsApp.groupAdmins.includes(BotsApp.owner) || false : '';
BotsApp.isSenderGroupAdmin = BotsApp.isGroup ? BotsApp.groupAdmins.includes(BotsApp.sender) || false : '';

return BotsApp;
}

function getGroupAdmins(participants){
var admins = [];
for (var i in participants) {
participants[i].isAdmin ? admins.push(participants[i].jid) : '';
}
console.log("ADMINS -> " + admins);
return admins;
}
24 changes: 12 additions & 12 deletions core/sessionString.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,23 @@ const conn = new WAConnection();
exports.WhatsApp = conn;

exports.saveSession = async () => {

if (!fs.existsSync('./config.env') || config.STRING_SESSION == "") {
conn.browserDescription = Browsers.macOS('Chrome')

conn.browserDescription = Browsers.macOS('Chrome')
conn.on('qr', async (qr) => {
console.log(chalk.blueBright.bold("Scan the QR code above.\n"));
})
await conn.connect();

conn.on('qr', async (qr) => {
console.log(chalk.blueBright.bold("Scan the QR code above.\n"));
})
await conn.connect();

var sass = JSON.stringify(conn.base64EncodedAuthInfo());
var stringSession = Buffer.from(sass).toString('base64');
console.log(chalk.greenBright.bold("Your string session ->"), stringSession)
if(config.HEROKU === false){
if (!fs.existsSync('./config.env')) {
var sass = JSON.stringify(conn.base64EncodedAuthInfo());
var stringSession = Buffer.from(sass).toString('base64');
console.log(chalk.greenBright.bold("Your string session ->"), stringSession)
if(config.HEROKU === false){
fs.writeFileSync('./config.env', `STRING_SESSION="${stringSession}"`);
}
process.exit(0);
}
process.exit(1);
}

exports.restoreSession = function(sessionString) {
Expand Down
15 changes: 15 additions & 0 deletions core/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const { MessageType, Mimetype } = require('@adiwajshing/baileys')


class Handlers{

constructor(client){
this.sendMsessage = this.sendMsessage;
}

sendMsessage(id, content){
this.sendMessage(id, content, MessageType.text);
}
}

module.exports = Handlers;
10 changes: 10 additions & 0 deletions modules/id.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const { MessageType } = require("@adiwajshing/baileys")

module.exports = {
name: "alive",
description: "OOF",
extendedDescription: "Not OOOf",
async handle(client, chat, BotsApp, args){
client.sendMessage(BotsApp.from, "I'm alive.", MessageType.text);
}
}
96 changes: 96 additions & 0 deletions modules/promote.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const { MessageType } = require("@adiwajshing/baileys")
const chalk = require('chalk');
module.exports = {
name: "promote",
description: "Promote",
extendedDescription: "Promote member to admin",
async handle(client, chat , BotsApp, args){
if(!BotsApp.isGroup){
client.sendMessage(BotsApp.from, "*This is not a group*", MessageType.text);
}
else{
if(!BotsApp.isBotGroupAdmin){
client.sendMessage(BotsApp.from,"*I am not group admin*", MessageType.text);
}

else{
try{
if(chat.messages.all()[0].message.extendedTextMessage.text.split("@")[1]== null){

var adm = false;
let parName = " ";
for (const key in BotsApp.groupMembers) {
if(chat.messages.all()[0].message.extendedTextMessage.contextInfo.participant.split('@')[0] == BotsApp.groupMembers[key].id.split('@')[0]){
parName = BotsApp.groupMembers[key].name;
if(BotsApp.groupMembers[key].isAdmin){
adm = true;

}
}
}
console.log("-------------/-------------/-------------/-------------\n");
console.log(chat.messages.all()[0].message.extendedTextMessage.contextInfo.participant.split('@')[0]);
console.log(parName);
console.log("-------------/-------------/-------------/-------------\n");

if(!adm == true){
const arr =[];
arr.push(chat.messages.all()[0].message.extendedTextMessage.contextInfo.participant)
client.groupMakeAdmin (BotsApp.from,arr)
client.sendMessage(BotsApp.from, "*" + parName + " promoted to admin*", MessageType.text);
}
else{
client.sendMessage(BotsApp.from, "*" + parName + " is already an admin*", MessageType.text);
}
}

else{

var adm = false;
let parName = " ";
for (const key in BotsApp.groupMembers) {
if(chat.messages.all()[0].message.extendedTextMessage.text.split("@")[1] == BotsApp.groupMembers[key].id.split('@')[0]){
parName = BotsApp.groupMembers[key].name;
if(BotsApp.groupMembers[key].isAdmin){
adm = true;

}
}
}
console.log("-------------/-------------/-------------/-------------\n");
console.log(chat.messages.all()[0].message.extendedTextMessage.text.split("@")[1]);
console.log(parName);
console.log("-------------/-------------/-------------/-------------\n");

if(!adm == true){
const arr =[];
arr.push(chat.messages.all()[0].message.extendedTextMessage.text.split("@")[1] + "@s.whatsapp.net")
await client.groupMakeAdmin (BotsApp.from,arr)
client.sendMessage(BotsApp.from, "*" + parName + " promoted to admin*", MessageType.text);
}
else{
client.sendMessage(BotsApp.from, "*" + parName + " is already an admin*", MessageType.text);
}
}
}
catch(err){
if(chat.messages.all()[0].message.extendedTextMessage || err instanceof TypeError){
console.log(
chalk.redBright.bold("Please reply to the person for promotion"));
client.sendMessage(BotsApp.from, "*Please reply to someone for promotion*", MessageType.text);
}
else{
console.log(err);
}

}

}

}
}
}




3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node qr.js && node BotsApp.js"
},
"author": "Prince Mendiratta",
"license": "ISC",
Expand Down
6 changes: 3 additions & 3 deletions qr.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ const con = require('./core/sessionString.js')
const fs = require('fs')
const chalk = require('chalk')

function generateStringSession () {
console.log(chalk.yellow.bold("Make sure you copy the string properly!\n\n"))
async function generateStringSession() {
try{
con.saveSession();
await con.saveSession();
} catch (err) {
console.log("Stopped.")
process.exit(1)
}
}

Expand Down
Loading