Skip to content

Commit 52b0da2

Browse files
author
Gunawan
committed
v2.0.7
[Changelogs & Fixes] -> Fix reconnecting issues, command "number" -> Removed "vminfo" -> Output chat in new line -> Add "dice, flip" command, debugger (Enable from config), Error handling in index.js -> Optimize code & Documented
1 parent ff8612a commit 52b0da2

File tree

10 files changed

+114
-108
lines changed

10 files changed

+114
-108
lines changed

README.md

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,5 @@ All code that i've taken from other sources has been labeled in JS Files.
2020
3. /index.js:93 - [collabvm-1.2.ts/cvmts/src/Utilities.ts:26](https://github.com/computernewb/collabvm-1.2.ts/blob/master/cvmts/src/Utilities.ts)
2121

2222
# Versions
23-
- Stable: v2.0.5
24-
- Latest: v2.0.6a
25-
- Note: I recommend you to use stable version. Latest are not considered to be fully stable yet!
23+
- Stable: [v2.0.7](https://github.com/gunawan092w/cvmbotJS/releases/latest)
24+
- Latest: [v2.0.7](https://github.com/gunawan092w/cvmbotJS/releases)

config.example.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
[bot]
2-
user = "cvmBotJS-v2" # Bot Username
2+
user = "cvmBotJS" # Bot Username
33
login = "hunter2" # Admin / Mod Password
44
ip = "ws://127.0.0.1:6004" # Websocket VM Endpoint
55
prefix = "j?" # Command Prefix
66

77
[settings]
88
login = "true" # Enable / Disable Bot Login
99
startup = "true" # Enable / Disable Startup message
10-
startupmsg = "cvmBotJS-v2 appeared in chat! Prefix is: 'j?'" # Send message everytime bot connects to VM
10+
startupmsg = "cvmBotJS appeared in chat! Prefix is: 'j?'" # Send Startup Message
11+
debug = "false" # Enable / Disable websocket message logging

files/commands/dice.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module.exports = {
2+
desc: 'Rolls a dice',
3+
async execute(chat) {
4+
const dice = Math.floor(Math.random() * 6) + 1 // Rolls 1-6
5+
chat(`You rolled ${dice}!`)
6+
}
7+
}

files/commands/flip.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module.exports = {
2+
desc: "Flips a coin",
3+
async execute(chat) {
4+
var rand = ['Heads', 'Tails'];
5+
return chat(`You landed ${rand[Math.floor(Math.random()*rand.length)]}!`); // Uses Math.floor & Math.random
6+
}
7+
}

files/commands/help.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@ module.exports = {
2020
const args = cmd[2].trim().split(' ');
2121
if(args.length===1){ // If user did not request for command's description
2222
chat(`My prefix is "${prefix}" ! Available Commands: ${Object.keys(command).join(', ')}`);
23-
chat(`Do ${prefix}help for more info!`);
23+
chat(`Do ${prefix}help [command] for more info!`);
2424
} else if(args.length===2){ // If user requests for command's description
2525
if (command[args[1]]) { // This was fixed in v2.0.4 - Where user tries to request a command that doesn't exists.
2626
if (command[args[1]].desc) { // If the command has description set
2727
chat(command[args[1]].desc)
28-
} else {chat(`Oops, ${args[1]} doesn't have a description set.`)} // If not.
28+
} else {chat(`${args[1]} doesn't have a description`)} // If not.
2929
}
3030
}
3131
} catch(error) { // Catch error!

files/commands/number.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
1+
const toml = require('toml');
2+
const fs = require('node:fs');
3+
const config = toml.parse(fs.readFileSync('./config.toml', 'utf-8'));
4+
15
module.exports = {
26
desc: 'Sends a random number with two numbers given by user',
37
async execute(chat, xss, cmd) {
48
const args = cmd[2].trim().split(' ');
59
const min = parseInt(args[1]);
610
const max = parseInt(args[2]);
711

8-
if (isNaN(min) || isNaN(max)) {chat(`Usage: ${prefix}number <min> <max>`);return};
9-
if (min >= max) {chat("Min value should be less than max value.");return};
12+
if (isNaN(min) || isNaN(max)) {chat(`Usage: ${config.bot.prefix}number <min> <max>`);return}; // If returned not an number (or no usage), sends usage
13+
if (min >= max) {chat("Min value should be less than max value.");return}; // If B (Max) is bigger than A (Min), let user know.
1014

1115
const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
1216
chat(`Random number between ${min} and ${max} is ${randomNumber}.`);

files/commands/vminfo.js

Lines changed: 0 additions & 8 deletions
This file was deleted.

files/commands/xsstest.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ const msg = "<h3>XSS Test Success!</h3>";
22
module.exports = {
33
desc: 'Sends a test xss message',
44
async execute(chat, xss, cmd) {
5-
const {permissions, botrole} = require('../../index.js'); // Mentioned in index.js Line 87
5+
const {permissions, botrole} = require('../../index.js');
66
if (botrole === 'mod') {
77
if (permissions.xss) { xss(msg) } // Checks if Bot has permission to send XSS.
88
else {chat("Sorry, i don't have permission to peform this task.")} // Only if the server doesn't allow mods to have perm to send XSS.

index.js

Lines changed: 85 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,11 @@ const WSClient = require('websocket').client;
44
const toml = require('toml');
55
const fs = require('node:fs');
66
const path = require('node:path');
7-
const rl = require('readline');
87

98
const Permissions = require('./files/utils/Permissions.js');
109
const {encode, decode} = require('./files/utils/Guacutils.js');
1110

1211
const config = toml.parse(fs.readFileSync('./config.toml', 'utf-8'));
13-
const prefix = config.bot.prefix;
1412
const Client = new WSClient();
1513

1614
// Loads all commands in commands folder
@@ -26,98 +24,96 @@ let readline;
2624
let permissions;
2725
function bot() {
2826
Client.removeAllListeners(); // Removes remaining listener
29-
30-
Client.on('connectFailed',function(){reconnect()});
31-
Client.on('error',function(error){console.log("An error has accoured.){ " + error.toString())});
32-
Client.on('close',function(){reconnect()});
33-
34-
readline = rl.createInterface({input: process.stdin, output: process.stdout});
27+
readline = require('readline').createInterface({input: process.stdin, output: process.stdout});
3528

29+
Client.on('connectFailed', reconnect);
3630
Client.on('connect', client => {
37-
function send(msg){client.sendUTF(msg)} // Added in v2.0.3 - easier rather than typing client.sendUTF
38-
39-
console.log(`Connected to VM!`); // Success!
40-
send(encode(['rename',config.bot.user])); // Bot sets Username
41-
send(encode(['list'])); // It appears this were not pushed to github (v2.0.6).
42-
43-
function chat(message){send(encode(['chat',message]))}; // Chat
44-
function xss(message){send(encode(["admin","21",message]))}; // XSS
45-
function chatsession() {
46-
readline.question('Chat: ',(msg)=>{
47-
if (botrole==="mod") {
48-
if (permissions.xss){xss(msg)} else(chat(msg));
49-
} else if (botrole==="admin"){xss(msg)} else{chat(msg)};
50-
chatsession(); // In loop.
51-
})
52-
}; chatsession();
31+
client.on('close', reconnect);
32+
33+
client.on('error',error => {console.log(`An error has accoured. {${error.toString()}}`)});
34+
35+
try {
36+
function send(msg){client.sendUTF(msg)} // Added in v2.0.3
37+
38+
console.log(`Connected to VM!`); // Connection established
39+
send(encode(['rename',config.bot.user])); // Bot sets Username
40+
41+
function chat(message){send(encode(['chat',message]))}; // Chat
42+
function xss(message){send(encode(["admin","21",message]))}; // XSS
43+
44+
function chatsession() {
45+
readline.question('Chat: ',(msg)=>{
46+
if (botrole==="mod") {
47+
if (permissions.xss){xss(msg)} else(chat(msg));
48+
} else if (botrole==="admin"){xss(msg)} else{chat(msg)};
49+
chatsession(); // In loop.
50+
})
51+
}; chatsession();
5352

54-
// Check if bot has been disallowed to login
55-
let botrole;
56-
if (config.settings.login==="false"){
57-
console.log("Not logging in as mod / admin."); botrole="null"
58-
} else{send(encode(['admin','2',config.bot.login]))} // If not, Bot proceeds to log in
59-
60-
if (config.settings.startup==="true") {if(client.connected){chat(config.settings.startupmsg)}}; // Startup Message. Enable/Disable in Config.
61-
62-
client.on('message', message =>{
63-
const cmd = decode(message.utf8Data);
64-
const action = cmd[0];
65-
const prefix = config.bot.prefix;
66-
67-
if(action==="disconnect"){reconnect()}; // If Disconnect, Kill Websocket Session, Kill Chat Session and reconnects.
68-
if(action==="nop"){send(encode(['nop']))}; // Send Heartbeat
69-
70-
if (action==="adduser") {
71-
if (cmd[2]!==config.bot.user&&cmd[1]==="1") { // Bot ignored + Only filter 1 user (v2.0.4)
72-
if (cmd[3]==='0'){console.log(`${cmd[2]} Joined!`)}; // Logs User Joins.
73-
if (cmd[3]==='2'){console.log(`${cmd[2]} is now Administrator!`)}; // Logs User logged in as Administrator
74-
if (cmd[3]==='3'){console.log(`${cmd[2]} is now Moderator!`)} // Logs user logged in as Moderator
53+
// Check if bot has been disallowed to login
54+
let botrole;
55+
if (config.settings.login==="false"){
56+
console.log("Not logging in as mod / admin."); botrole="null"
57+
} else{send(encode(['admin','2',config.bot.login]))} // If not, Bot proceeds to log in
58+
59+
// Startup Message. Enable/Disable in Config.
60+
if (config.settings.startup==="true") {if(client.connected){chat(`${config.settings.startupmsg}`)}};
61+
62+
client.on('message', message =>{
63+
const cmd = decode(message.utf8Data);
64+
const action = cmd[0];
65+
const prefix = config.bot.prefix;
66+
67+
if(action==="nop"){send(encode(['nop']))}; // Send Heartbeat
68+
69+
if (action==="adduser") {
70+
if (cmd[2]!==config.bot.user&&cmd[1]==="1") { // Ignore bot & Detect 1 user only. [v2.0.4]
71+
if (cmd[3]==='0'){console.log(`${cmd[2]} Joined!`)}; // Logs User Joins.
72+
if (cmd[3]==='2'){console.log(`${cmd[2]} is now Administrator!`)}; // Logs User logged in as Administrator
73+
if (cmd[3]==='3'){console.log(`${cmd[2]} is now Moderator!`)} // Logs user logged in as Moderator.
74+
};
7575
};
76-
};
77-
if(action==="remuser"){console.log(`${cmd[2]} Left!`)}; // Logs user leaves.
78-
if(action==="rename"&&cmd[1]==='1'){console.log(`${cmd[2]} Renamed to ${cmd[3]}`)}; // Detect if user renames
79-
80-
// Detects if the bot is logged in as admin / mod or fails to login.
81-
if (action==="admin") {
82-
if (cmd[2]==='0'){console.log("Incorrect login password!");botrole = "null"};
83-
if (cmd[2]==='1'){console.log("Logged in as Administrator!");botrole = "admin"};
84-
if (cmd[2]==='3'){
85-
console.log("Logged in as Moderator!"); botrole = "mod";
86-
permissions = new Permissions(cmd[3]); // Check Moderator Permissions
87-
console.log(permissions); // Outputs Moderator Permissions [true/false] (as JSON)
88-
module.exports = {permissions}; // Can be used for other admin / mod commands to check the bot's permission.
76+
if(action==="remuser"){console.log(`${cmd[2]} Left!`)}; // Logs user leaves.
77+
if(action==="rename"&&cmd[1]==='1'){console.log(`${cmd[2]} Renamed to ${cmd[3]}`)}; // Detect if user renames
78+
79+
// Check if the bot has logged in as admin / mod
80+
if (action==="admin") {
81+
if (cmd[2]==='0'){console.log("Incorrect login password!");botrole = "null"};
82+
if (cmd[2]==='1'){console.log("Logged in as Administrator!");botrole = "admin"};
83+
if (cmd[2]==='3'){console.log("Logged in as Moderator!"); botrole = "mod";
84+
permissions = new Permissions(cmd[3]); // Check Moderator Permissions
85+
} module.exports = {botrole, permissions}; // export botrole, permissions
8986
}
90-
module.exports = {botrole}; // xsstest was not working when the bot is administrator.
91-
}
92-
93-
if(action==="chat"){
94-
if(cmd[2] !=="") {
95-
// https://github.com/computernewb/collabvm-1.2.ts/blob/master/cvmts/src/Utilities.ts Line 26
96-
const decodedmsg = cmd[2]
97-
.replace(/&#x27;/g, "'") .replace(/&quot;/g, '"')
98-
.replace(/&#x2F;/g, "/") .replace( /&lt;/g, "<" )
99-
.replace( /&gt;/g, ">" ) .replace( /&amp;/g, "&");
100-
console.log(`${cmd[1]} says: ${decodedmsg}`); // Logs user message
101-
} else {}; // Ignores if the message is empty.
87+
88+
if(action==="chat"){
89+
if(cmd[2] !=="") {
90+
// https://github.com/computernewb/collabvm-1.2.ts/blob/master/cvmts/src/Utilities.ts Line 26
91+
// Message Decoder to make it readable
92+
const decodedmsg = cmd[2]
93+
.replace(/&#x27;/g, "'") .replace(/&quot;/g, '"')
94+
.replace(/&#x2F;/g, "/") .replace( /&lt;/g, "<" )
95+
.replace( /&gt;/g, ">" ) .replace( /&amp;/g, "&");
96+
console.log(`\n${cmd[1]} says: ${decodedmsg}`); // Output messages to console
97+
} else {}; // Ignores if the message is empty (Happens if user send empty message through XSS)
10298

103-
const cmdName = cmd[2].slice(prefix.length).trim().split(' ')[0];
104-
if(cmd[1]!==config.bot.user){ // Ignore bot messages
105-
if (cmd[2].startsWith(prefix) && command[cmdName]){
106-
if (command[cmdName].execute) {
107-
command[cmdName].execute(chat, xss, cmd);
108-
}else { chat(`It looks like ${cmdName} doesn't have 'execute' property set!`) };
109-
};
110-
};
111-
};
112-
113-
if (action==='list') { // For vminfo command. You may remove this code if you don't want this command.
114-
const vmname = cmd[1];
115-
const vmdesc = cmd[2];
116-
module.exports = {vmname, vmdesc};
117-
};
118-
});
119-
});
120-
Client.connect(config.bot.ip, 'guacamole'); // Bot connects to VM
99+
const cmdName = cmd[2].slice(prefix.length).trim().split(' ')[0];
100+
if(cmd[1]!==config.bot.user){ // Ignore bot messages
101+
if (cmd[2].startsWith(prefix) && command[cmdName]){
102+
if (command[cmdName].execute) {
103+
command[cmdName].execute(chat, xss, cmd);
104+
}else { chat(`It looks like ${cmdName} doesn't have 'execute' property set!`) };
105+
};
106+
};
107+
};
108+
109+
// Debugger
110+
if (config.settings.debug === 'true' && cmd[0] !== 'nop') { // Check if debug is true in config & ignore 'nop'
111+
console.log(cmd); //Outputs WebSocket Messages through console.
112+
};
113+
114+
});
115+
} catch (error){chat (`Something went wrong, check console for more details.`); console.log(error)}
116+
}); Client.connect(config.bot.ip, 'guacamole'); // Bot connects to VM
121117
}
122118

123119
console.log('Connecting to VM...');
@@ -128,7 +124,7 @@ function reconnect() {
128124
console.log("Reconnecting..."); bot(); // Calls the bot() again
129125
}
130126

131-
// Catch the CTRL+C !!!!
127+
// If process recieved "SIGINT" (or CTRL+C), Kill session
132128
process.on('SIGINT', () => {
133129
console.log('\nKilling Bot Session...');
134130
if (readline) readline.close(); process.exit(0);

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "cvmbotjs",
3-
"version": "2.0.5",
3+
"version": "2.0.7",
44
"description": "A CollabVM Bot written in Javascript",
55
"keywords": [],
66
"homepage": "https://github.com/gunawan092w/cvmbotJS#readme",

0 commit comments

Comments
 (0)