Skip to content

Instantly share code, notes, and snippets.

@twitchdevelopers
Last active October 4, 2023 00:05
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save twitchdevelopers/afda75fe0a43453e97e97b25232778de to your computer and use it in GitHub Desktop.
Save twitchdevelopers/afda75fe0a43453e97e97b25232778de to your computer and use it in GitHub Desktop.
Sample Code for Getting Started with Chatbots
const tmi = require('tmi.js');
// Define configuration options
const opts = {
identity: {
username: <BOT_USERNAME>,
password: <OAUTH_TOKEN>
},
channels: [
<CHANNEL_NAME>
]
};
// Create a client with our options
const client = new tmi.client(opts);
// Register our event handlers (defined below)
client.on('message', onMessageHandler);
client.on('connected', onConnectedHandler);
// Connect to Twitch:
client.connect();
// Called every time a message comes in
function onMessageHandler (target, context, msg, self) {
if (self) { return; } // Ignore messages from the bot
// Remove whitespace from chat message
const commandName = msg.trim();
// If the command is known, let's execute it
if (commandName === '!dice') {
const num = rollDice();
client.say(target, `You rolled a ${num}`);
console.log(`* Executed ${commandName} command`);
} else {
console.log(`* Unknown command ${commandName}`);
}
}
// Function called when the "dice" command is issued
function rollDice () {
const sides = 6;
return Math.floor(Math.random() * sides) + 1;
}
// Called every time the bot connects to Twitch chat
function onConnectedHandler (addr, port) {
console.log(`* Connected to ${addr}:${port}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment