· 5 years ago · Oct 28, 2019, 05:18 PM
1const tmi = require('tmi.js');
2
3// Define configuration options
4const opts = {
5 identity: {
6 username: <BOT_USERNAME>,
7 password: <OAUTH_TOKEN>
8 },
9 channels: [
10 <CHANNEL_NAME>
11 ]
12};
13
14// Create a client with our options
15const client = new tmi.client(opts);
16
17// Register our event handlers (defined below)
18client.on('message', onMessageHandler);
19client.on('connected', onConnectedHandler);
20
21// Connect to Twitch:
22client.connect();
23
24// Called every time a message comes in
25function onMessageHandler (target, context, msg, self) {
26 if (self) { return; } // Ignore messages from the bot
27
28 // Remove whitespace from chat message
29 const commandName = msg.trim();
30
31 // If the command is known, let's execute it
32 if (commandName === '!dice') {
33 const num = rollDice();
34 client.say(target, `You rolled a ${num}`);
35 console.log(`* Executed ${commandName} command`);
36 } else {
37 console.log(`* Unknown command ${commandName}`);
38 }
39}
40
41// Function called when the "dice" command is issued
42function rollDice () {
43 const sides = 6;
44 return Math.floor(Math.random() * sides) + 1;
45}
46
47// Called every time the bot connects to Twitch chat
48function onConnectedHandler (addr, port) {
49 console.log(`* Connected to ${addr}:${port}`);
50}