2 min read

Twitch Chat Bot

This guide demonstrates how to create a Twitch chat bot using the twitchio library. This library allows you to connect to Twitch's IRC interface to read chat messages and send responses asynchronously.

Modules Used:

  • twitchio: An asynchronous Python wrapper for the Twitch API and IRC.
  • python-dotenv: To securely manage the bot token.

Prerequisites

  1. Twitch Account: You need a Twitch account.
  2. OAuth Token: You need an OAuth token to log in as a bot. You can generate one using a tool like Twitch Token Generator.
    • Scopes required: chat:read, chat:edit.

Installation

pip install twitchio python-dotenv

Setup

Create a .env file in your project directory:

TMI_TOKEN=oauth:your_token_here
CLIENT_ID=your_client_id_here
BOT_NICK=your_bot_username
CHANNEL=channel_to_join

Note: CLIENT_ID is often provided by the token generator or your Twitch Developer Console application.

The Code

Save this as twitch_bot.py.

import os
from dotenv import load_dotenv
from twitchio.ext import commands

# 1. Load Config
load_dotenv()

class Bot(commands.Bot):

    def __init__(self):
        # Initialise our Bot with our access token, prefix and a list of channels to join on boot...
        super().__init__(
            token=os.environ['TMI_TOKEN'],
            client_id=os.environ['CLIENT_ID'],
            nick=os.environ['BOT_NICK'],
            prefix='!',
            initial_channels=[os.environ['CHANNEL']]
        )

    async def event_ready(self):
        # Notify us when everything is ready!
        print(f'Logged in as | {self.nick}')
        print(f'User id is | {self.user_id}')

    async def event_message(self, message):
        # Messages with echo set to True are messages sent by the bot...
        # For now we just want to ignore them...
        if message.echo:
            return

        # Print the contents of our message to console...
        print(f"{message.author.name}: {message.content}")

        # Since we have commands and are overriding the default `event_message`
        # We must let the bot know we want to handle and invoke our commands...
        await self.handle_commands(message)

    @commands.command()
    async def hello(self, ctx: commands.Context):
        # Send a hello back!
        await ctx.send(f'Hello {ctx.author.name}!')

if __name__ == "__main__":
    bot = Bot()
    bot.run()

Usage

  1. Run the script:
    python twitch_bot.py
  2. Go to the Twitch channel specified in your .env.
  3. Type !hello in the chat.

programming/python/python