Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created June 9, 2022 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisryosuke/36bfb3fce23228e16be4b6003c79ea7c to your computer and use it in GitHub Desktop.
Save whoisryosuke/36bfb3fce23228e16be4b6003c79ea7c to your computer and use it in GitHub Desktop.
Twitch API + NextJS example. Requires OAuth secret key (see: https://dev.twitch.tv/docs/irc/get-started)
import { useState, useEffect } from "react"
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
// Example from Twitch API docs
// @see: https://dev.twitch.tv/docs/irc/get-started
import tmi from 'tmi.js';
// Define configuration options
const opts = {
identity: {
username: 'whoisryosuke',
// oauth:token
password: 'SECRET_TOKEN'
},
channels: [
'whoisryosuke'
]
};
// Create a client with our options
const client = new tmi.client(opts);
// Connect to Twitch:
client.connect();
// Called every time the bot connects to Twitch chat
function onConnectedHandler (addr, port) {
console.log(`* Connected to ${addr}:${port}`);
}
export default function Home() {
const [points, setPoints] = useState(0);
const increasePoints = () => {
setPoints((prevPoints) => prevPoints + 10)
}
// 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`);
increasePoints();
} 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;
}
useEffect(() => {
// Register our event handlers (defined below)
client.on('message', onMessageHandler);
client.on('connected', onConnectedHandler);
return () => {
client.removeListener('message', onMessageHandler);
client.removeListener('connected', onConnectedHandler);
}
}, [])
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Points: {points}
</h1>
</main>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment