HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Jarvis the discord.js chat bot

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thechatdiscordbotjarvis

Problem

Just finished creating my first bot using Discord.js for the chat application, Discord. This is my first bot and first javascript program I have ever created. I'm mainly interested in ways I can optimize the code and make it a bit cleaner. Any help or suggestions is greatly appreciated.

Github Repo

Main:

```
/*
File: Jarvis.js
Author: Sean Peters
Created: 06/22/2016
Description: Main Bot File
Version: 0.1.4
*/
var Discord = require("discord.js");
var bot = new Discord.Client();
require('String.prototype.startsWith'); // used to parse complicated messages

// begin main bot
bot.on("message", function(message) {
// convert message into all upper case and store it in input
var input = message.content.toUpperCase();
var server = message.channel.server;
var roles = message.channel.server.roles;
var user = message.author;
var role;
var roleName = message.content.split(" "); // roleName[0] = "ADDROLE", roleName[1] = "GivenRole"
var channels = message.channel.server.channels;
var channel;
var reserved; // Hello Jarvis
if (input === "HELLO JARVIS") {
bot.reply(message, "Hello! Good to be back.");

}else if (input.startsWith("!VOICE") && (parsed[1] === "Guild-Chat" || parsed[1] === "Raiding" || parsed[1] === "Overwatch" || parsed[1] === "PvP" || parsed[1] === "Officers")) {
channel = channels.get("name", parsed[1]).id;
role = roles.get("name", "Officers").id;
if (bot.memberHasRole(user, role)) {
if (bot.voiceConnection == null) {
bot.joinVoiceChannel(channel);
bot.voiceConnection.playfile(parsed[2], {
volume: 0.25
}, function(error, intent) {
if (error) console.log(error);
intent.on("end", function() {
bot.voiceConnection.stopPlaying();
});
});
}
bot.leaveVoiceChannel(channel);
}
}
// !say channel message
else if (input.startsWith("!SAY") && (par

Solution

You can simplify all of the basic text responses by putting them into a table.
Instead of:

if (message.content === "foo") message.channel.sendMessage("bar");


Do:

var responses = {"foo": "bar"};
if (responses[message]) message.channel.sendMessage(responses[message]);


It may be more complicated for shorter stacks of if else statements but it is more efficient for large ones like the one in your code.

Code Snippets

if (message.content === "foo") message.channel.sendMessage("bar");
var responses = {"foo": "bar"};
if (responses[message]) message.channel.sendMessage(responses[message]);

Context

StackExchange Code Review Q#132754, answer score: 2

Revisions (0)

No revisions yet.