Now that we have a bot running on our twitch channel from part 1, we can now work on coding and adding new features to the bot.
When coding the most important thing is to add notes to remember what each function does, or whatever you will find important at a later stage. You do that by adding // before the comment.
// This is my comment. I need to remember this for later. Important stuff here.
JavaScript will ignore this part of the text and move on to the next code.
The way the code works is the computer is constantly reading from top to bottom over and over really fast. If any of the conditions are true, then it does what you programmed then keeps repeating from the top to the bottom of the code.
You have the bot listen for a command, then have the bot do an action when the command is found. It can do many things from doing math calculations, typing things in chat, enable follower only mode, adding mods, and so much more.
A lot of the way I do programming is guess and check, finding sample code online, or learning the JavaScript code to do something similar then modify it. Its not that hard and in the end you are super hyped being able to figure it out, like a complicated puzzle you just finished.
Errors:
When there is a code error, I noticed 3 things that can happen.
One: You open the bot.js bot and the CMD window opens and closes right away. This means there is an error in your code, and the bot is not happy at all. You may have messed with the basic structure of the code, or the twitch API stuff. (Most of the code from the first example).
Two: You open the bot and it shows an error. This error usually shows the line of the code with the error and an arrow at the issue. These are easier to fix as it shows right away where the issue can be at. Sometimes the error is a missing open or close bracket {}, or a missing start or ending quote mark ”.
Three: You run a command and the bot CMD window closes. This means that there is a good chance that command, or the ones before it are the issue. Try another command before and test.
If you are having errors, you can also use the above // to comment out a part of the code to help find the issue and fix it.
Adding commands to the bot:
Lets start with much more simple code from the example at tmi.js website. Copy the following code and replace what you had before in the bot.js file. Be sure you know the Bot username, Oauth key, and the Channel you want to use the bot on before you delete the old code. These are things you want backed up somewhere else too.
const tmi = require('tmi.js');
const client = new tmi.Client({
options: { debug: true },
identity: {
username: 'my_bot_name',
password: 'oauth:my_bot_token'
},
channels: [ 'my_name' ]
});
client.connect();
client.on('message', (channel, tags, message, self) => {
// Ignore echoed messages.
if(self) return;
if(message.toLowerCase() === '!hello') {
// "@alca, heya!"
client.say(channel, `@${tags.username}, heya!`);
}
});
You can see this code it a little different. The login info has a debug option turned on. This will log info in the CMD window and show you more of what is happening when commands are being run.
Go ahead and change the bot name, oauth, and channels the bot should join. Be sure to use ‘single quotes’ around the info.
You can add your own custom code or add more commands to what is there already. Here is where you can add more commands:
client.on('message', (channel, tags, message, self) => {
// Ignore echoed messages.
if(self) return;
if(message.toLowerCase() === '!hello') {
// "@alca, heya!"
client.say(channel, `@${tags.username}, heya!`);
}
// add your custom codes here
});
If you do not want the !hello command then remove that section of the code:
// remove the following if you do not want !hello
if(message.toLowerCase() === '!hello') {
// "@alca, heya!"
client.say(channel, `@${tags.username}, heya!`);
}
I am showing how to add a command for !cat and !dog that will put animal emotes in the chat.
//animals commands
if (message.toLowerCase() === '!cat') {
client.say(channel, `GlitchCat DxCat Keepo RitzMitz Kippa`);
}
if (message.toLowerCase() === '!dog') {
client.say(channel, `FrankerZ RalpherZ CorgiDerp OhMyDog ChefFrank BegWan `);
}
This code will turn upper case letters in the chat command into lower case, then if it matches !cat or !dog it will put the emotes into the chat.
Command Variants:
You can see in the code above there is:
if (message.toLowerCase() === '!cat')
What toLowerCase does is if someone in chat used capitals (!Cat), it will make it small letters (!cat) then see if it matches the command.
If you want something more specific (It will only listen to that exact term), or if its only numbers, you can use:
if (message === '!1') {
If you want it to take a word out of what people are saying, you can use this:
if (message.includes("lurk")) {
If someone types “I am going to be lurking” then the bot will trigger with the word lurk being in that sentence. It also works when people say “I was lurking earlier” so sometimes it funny when people see the bot triggered when they are back.
If you wanted to add a 6 sided dice roll game into the bot, here is the one that I use that is much more simple than the one twitch example from the last article.
//roll dice
if(message.toLowerCase() === '!roll') {
const result = Math.floor(Math.random() * 6) + 1;
client.say(channel, `@${user['display-name']}, You rolled a ${result}.`);
}
I also modified it to have a 20 sided dice for DD players.
if(message.toLowerCase() === '!dd20') {
const result = Math.floor(Math.random() * 20) + 1;
client.say(channel, `@${user['display-name']}, You rolled a ${result}.`);
}
If you want the user to be able to change the bots name color in the chat, then there is a command for that too:
//Change Bot color commands
if (message.toLowerCase() === '!colorred') {
client.say(channel, `/color red `);
}
if (message.toLowerCase() === '!colorblue') {
client.say(channel, `/color blue `);
}
if (message.toLowerCase() === '!colorgreen') {
client.say(channel, `/color green`);
}
if (message.toLowerCase() === '!colororange') {
client.say(channel, `/color coral `);
}
As you see above, it uses the chat / commands that are default in twitch. You can put / in twitch chat and see all the available commands for mods in your own channel or for normal people in other channels. This will give you ideas what you can do from the chat. See the Advanced stuff below where the bot can turn on subscriber only mode and clear the chat.
If the chat / command requires mod, then you need to make the bot itself a mod to use that command. You can easily do that from the chat: /mod @botname
Advanced stuff:
Mod only commands:
If you want commands that work for Mods and Broadcaster only, such as !so or !hateraid (More on hateraid later) then you can add the following at the start of the command code:
//start of commands
client.on('chat', (channel, user, message, self) => {
//Checks if you are Mod or Broadcaster
let isMod = user.mod || user['user-type'] === 'mod';
let isBroadcaster = channel.slice(1) === user.username;
let isModUp = isMod || isBroadcaster;
Now this will let the bot see if the user that posted the command are mod/broadcaster then it will allow the command to be used.
Shoutout command: (needs to be used with the above mod only command)
// SO Command
if(isModUp) {
if (message.includes("!so")) {
const args = message.slice(1).split('@');
const command = args.shift().toLowerCase();
client.say(channel, `Check out ${args.join(' ')} and give them a follow at twitch.tv/${args.join(' ')}`);
}
}
The above code is the !so command. It will make sure a user is Mod or Broadcaster then it gets the command typed after !s0 such as “!so @user” and then removed the @ symbol from the user name, so it can shoutout that user. This was needed to give a twitch link to the user without the @ symbol.
Hate raid commands:
Hate raids are a disgusting part of being online, but we can try and combat it using our own bot. This also requires the Mod only command above.
if(isModUp) {
if(message.toLowerCase() === '!hateraid') {
client.say(channel, `/subscribers`);
client.say(channel, `/clear`);
client.say(channel, `It appears there was a hate raid. The chat is now in Subscribers only mode. `);
}
}
if(isModUp) {
if (message.toLowerCase() === '!hateraidoff') {
client.say(channel, `/subscribersoff `);
client.say(channel, `The chat is now in normal mode. `);
}
}
This above code will make sure the user is Mod or Broadcaster, then put the chat in subscriber only mode, clear the chat, then explain what just happened.
The next command !hateraidoff is also a Mod or Broadcaster command, it will turn everything off and put the chat back to normal.
As you can see, the bot can do multiple actions on each line.
Example of multiple commands doing the same action:
if (message.toLowerCase() === 'goodnight' || message.toLowerCase() === 'good night') {
client.say(channel, `Have a good night! See you next time.`);
}
This code will listen to anyone saying ‘goodnight’ or ‘good night’ and then the bot will respond in chat.
Showing a random answer:
If you want someone to type in !tips and get a random tip for a game, then here is how to do it:
if(message.toLowerCase() === '!tips') {
var answers = [
"Tip 1 info",
"Tip 2 info",
"Tip 3 info"
]
var randomAnswer = answers[Math.floor(Math.random() * answers.length)];
client.say(channel, randomAnswer);
}
New command I just added is temperature conversion from C to F and from F to C:
// Calculate C TO F temps
if (message.includes("!c")) {
//remove the '!' from the command and get the temperature number
const args = message.slice(0).split('!c');
//Get user input for variable 'a'
var a = args.join(" ");
//Multiply 'a' by 1.8 gives us 'b', then 'b' + 32 = 'c'
let b = (a * 1.8);
let c = (b + 32)
client.say(channel, `The temperature in Fahrenheit is:` +c);
};
// Calculate F to C temps
if (message.includes("!f")) {
//remove the '!' from the command and get the temperature number
const args = message.slice(0).split('!f');
//Get user input for variable 'a'
var a = args.join(" ");
//Subtract 'a' by 32 gives us 'b', then 'b' multiplied by 0.5556 = 'c'
let b = (a - 32);
let c = (b * 0.5556)
client.say(channel, `The temperature in Celsius is:` +c);
};
You can see in the above example, you can use variables and math equations to solve things and give the answers in the chat. The answer is provided outside the text area `temp is` and only seems to work on the right side. It needs a Plus sign on the variable answer for it to display the answer.
Telling time in Javascript is weird:
I recently added a !time command to my bot, it reads the time from my server, and being JavaScript, it gives the milliseconds since Jan 1, 1970. So you need to have many commands to get the Current time.
//Time where my server is
if (message.toLowerCase() === '!time') {
// Calculate milliseconds in a year
const minute = 1000 * 60;
const hour = minute * 60;
const day = hour * 24;
const year = day * 365;
// Divide Time with a year
const d = new Date();
let years = Math.round(d.getTime() / year);
client.say(channel, `The time is: ` +d );
}
The output of the above code in chat after using !time is:
The time is: Tue Apr 12 2022 01:31:40 GMT-0700 (Pacific Daylight Time)
Commands page:
Something I like to do with all my bots is create a commands page HTML file.
I create a command that people can use to get the URL:
if (message.toLowerCase() === '!commands') {
client.action(channel, `@${user['display-name']}, https://www.howtoengineering.com/commands.html`);
}
I made the website using basic HTML, since this is an exercise in programming, why not do it all by hand coding it. I also added links to each twitch streamer channel that I have the bots on, so it also promotes them.
I also like to include a simple !credits command to show who made the bot.
if (message.toLowerCase() === '!credits') {
client.action(channel, `@${user['display-name']}, This super smart amazing bot MrDestructoid was made by @Retro_Unlimited`);
}
I just like that personal touch, plus as of now I do not have SQL working properly so I have to manually load and remove the bot from people channels. Progress on SQL is that I can connect to a database, and write data, but not read or use data from the database. Maybe someday I can add that function so people can !join or !remove the bot.
This article is a work in progress. I will keep editing, adding, and always learning. Maybe someday I will make a bot for discord, which is not too different from the twitch chat bots.