DEV Community

Discussion on: Let's make a Twitch bot with Python!

Collapse
 
cgusb profile image
Gus Becker

Hi all! After some headaches with this yesterday, I wanted to make some clarifications that would have helped me when I started trying to make my bot!
1) The TMI token and Client ID should both be generated using the Twitch account you set up for your bot. If you are having the "channel does not exist" error, try re-registering your app with Twitch dev and make sure you save the changes and get the updated Client ID! If you are using a personal computer as opposed to a web server, make sure for the entry box "OAuth Redirect URLs" you are entering "localhost" (no quotes).
2) The .env file is a way to keep your TMI token and Client ID secret even if you use version control software like Git to store your code somewhere like GitHub. You need to have a Python package called dotenv to load these variables into your bot.py file. To download this package, you can do it using pip with the command pip install python-dotenv. You then need to import the function load_dotenv() from the package at the top of your file. This can be done by including from dotenv import load_dotenv with all your other package imports at the top of the file. Then you need to call the load_dotenv() function at the top of your bot.py file (below the imports but above the os.environ calls. This allows os to properly import those variable from the .env file. If you don't want to download dotenv, you can list these variables directly in bot.commands(), but realize that if you do this, you shouldn't share this code publicly because someone else getting their hands on the TMI token and Client ID would allow them to control your bot.
3) The variables in the .env file should be as follows:
TMI_TOKEN=oauth:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
BOT_NICK=BotChannelName
BOT_PREFIX=!
CHANNEL=ChannelNameOfChatToEnter
Important note: BOT_PREFIX refers to the prefix of the commands that the bot will respond to. Most Twitch bots use "! " (e.g. !discord), so it's probably a good idea to keep it as a single exclamation mark. A lot of comments say to use you bot's channel name, but this will make it so that your bot doesn't respond to commands!
4) When testing your bot, you may want to edit the code in your bot.py file. To do this, you must stop the code from executing and re-execute the code to update the bot with the new info in the saved bot.py file. To do this, go to the command line that your prompts are run from and hit Crtl + C. This will stop the execution and allow you to re-execute.

I hope this helps anybody that might be confused in ways similar to how I was!