Twitch is currently the largest streaming platform. Due to the high number of viewers, many steamers not only use human moderation teams, but also moderation bots.

Bots can be useful when moderating Twitch chats as they can help you enforce rules and keep the chat organized. Here are a few tasks that bots can do:

  • Filter out inappropriate or spam messages
  • Issuing warnings to users who break the rules
  • Answers to frequently asked questions or commands from users
  • Entertainment through for example a question and answer quiz
  • Connect external systems such as subscriber alarms or games with chat integration

By automating these tasks, bots can help your moderators keep chat clean and focused, giving you more time to interact with your viewers. Unlike human moderators, bots don’t get tired.

In this tutorial you will learn how to implement a simple chatbot in Python. We use the TwitchIO Module because it can be implemented quickly and expanded modularly.

Twitch chat interfaces

Twitch uses Internet Relay Chat (IRC) for its chat functionality. IRC is a protocol that allows users to communicate with each other. It is designed for group communication in channels, but also allows one-to-one communication via private messages.

Twitch chat servers use a modified version of the IRC protocol that includes additional functions and features specific to Twitch. To connect and interact with Twitch chat, you need to use an IRC library or client compatible with Twitch IRC server.

Alternatively, you can also use the Twitch API to access chat data and features. The Twitch API uses HTTP (Hypertext Transfer Protocol) to communicate with the Twitch servers and provides a way to programmatically access data and functionality on the Twitch platform.

In this tutorial we use the TwitchIO module, which handles the communication. So we don’t have to worry about the logs anymore.

What is TwitchIO

TwitchIO is an asynchronous Python wrapper around both the Twitch API and IRC with a powerful command extension for creating Twitch chat bots. TwitchIO covers almost the entire new Twitch API and offers support for Commands, PubSub, Webhooks and EventSub.

The latest version is currently 2.5.0.

Install TwitchIO

Like most Python modules, you can easily install TwitchIO with Pypi.

pip install twitchio

Preparation

If you want to operate a Twitch bot, you must first create it as a new account on Twitch. You then have to generate an OAuth token. TwitchIO needs this token to connect to the Twitchchat.

Create a new Twitch account

You can register the account like your own on Twitch. If you are already logged in, you must of course log out first.

By the way, in your profile settings you will find an option that allows you to create multiple accounts with the same email address or phone number.

Generate login token

Once you have created your new account, all you need is a login token. You can generate this yourself according to the documentation or simply use the generator by swiftyspiffy for test purposes.

Twitch bot base

Here is an example of a Twitchbot that responds to the command “!hello” with “Hello” + name.

from twitchio.ext import commands

token = "" # put your token here

class Bot(commands.Bot):
    def __init__(self):
        super().__init__(
            token=token,
            prefix="!", #prefix for commands
            initial_channels=["nymn", "forsen"], # list of channels
        )

    async def event_ready(self):
        print(f"Logged in as | {self.nick}")
        print(f"User id is | {self.user_id}")

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

    async def event_message(self, message): # this function will be executed on every chat message
        if message.echo: #message.echo are the bots own messages
            return # we ignore those
        m = message

        print( # print on console
            f"#{message.author.channel.name}-{message.author.name}({message.timestamp}): {message.content}"
        )

        await self.handle_commands(message) # go through commands

bot = Bot() # initialize bot
bot.run() # execute bot

As you can see you can put all the configuration in the Bot class.

Prefix for commands

When initializing, you must also specify a prefix in addition to the channels to which your bot should connect. This prefix prevents the bot from recognizing each line as a command. Instead, only lines beginning with this prefix are considered.

In the example, the prefix is an exclamation mark.

Any methods you decorate with the @commands.command() decorator are commands. For example the hello() method from the example. hello() is executed every time someone writes !hello in the chat.

Event message

The event_message() method is executed on every message event in one of the connected chats. In the example we simply displayed the content of the incoming chat messages on the console.

Event ready

The event_ready() method is always executed after login.

Docs

Of course, this was just a small example. TwitchIO can do much more. You can find the full range of functions in the official documentation.


Could I help? Buy me a drink ! 💙