CODE WITH MARTIN

Twitch Chat Bot


Introduction

Creating a Twitch.tv chat bot with Python is very easy. Thanks to Twitch using a common chat protocol known as IRC, we can simply connect to its chat servers over TCP and use the IRC protocol to operate the chat for a stream.

This article will show you how to write your first Twitch bot in just 24 lines of code!

Create Bot Account

To be able to create your own bot, I suggest creating a new Twitch account with the desired name of your bot. You will then need to generate an auth token, which is a special generated password used for bots that don't compromise the security of your entire account, since we don't use the real account password.

Create Auth Token

After you've created your new account, make sure you're logged in to it in your browser. Then click this link to generate your auth token: Generate Token

After clicking "Connect", you will see a token that reads something like "oauth:os0xdav29710b2abstbpl125noaeka". Save this, as we're going to use this to connect to Twitch using Python. Also, this token is like a second password for your twitch account, it's a very good idea not to share it with anyone or accidentally save this in a public project where people can see it.

Required Packages

As mentioned, Twitch chat uses the IRC protocol. We don't need to write any code to work with that protocol as someone has already done that for us. Install the package 'irc' using 'pip install irc'.

The Code

Let's dive straight in and write the bot code, and explain after:

import irc.bot
import datetime
server = 'irc.chat.twitch.tv'
port = 6667

class MyBot(irc.bot.SingleServerIRCBot):
    def __init__(self, username, password, channel):
        self.channel = '#' + channel
        super().__init__([(server, port, password)], username, username)

    def on_welcome(self, client, _):
      client.join(self.channel)

    def on_pubmsg(self, client, message):
      chat_message = message.arguments[0]
      username = message.source.nick
      timestamp = datetime.datetime.now().strftime("[%d/%m/%Y %X] ")
      print(timestamp + "<" + username + ">: " + chat_message)
      
      if chat_message == "!heybot":
        client.privmsg(self.channel, "Hello, I'm your bot!")

bot = MyBot("<username>", "<oauth_token>", "mizkif")
bot.start()

To run this, you first need to enter your bots twitch account username in place of the "<username>" parameter on line 23. Remember that auth token you saved? Put that in the 2nd parameter in place of "<oauth_token>". And lastly, the 3rd parameter is the channel name your bot will join when it connects to Twitch.

Most code from lines 1 to 14 is boiler plate. The functions in this class are called in response to events from the IRC server, such as on connecting (line 11) and receiving a chat message (line 14).

Line 18 will display every incoming message in the terminal. You could choose to write this away to a local text file if you wanted.

Lines 20-21 show you how to check the received chat message and respond with a chat message from the bot account if a user in the chat types "!heybot".

Happy bot coding!