Connecting to twitch chat python

TheMagicalCake picture TheMagicalCake · Feb 18, 2014 · Viewed 10k times · Source
import time
import win32api, win32con
import socket #imports module allowing connection to IRC
import threading #imports module allowing timing functions

#sets variables for connection to twitch chat
bot_owner = 'TheMagicalCake'
nick = 'MagicalCakeBot'
channel = '#TheMagicalCake'
server = 'magicalcakebot.jtvirc.com'
password = '~redacted~'

irc = socket.socket()
irc.connect((server, 6667)) #connects to the server

#sends variables for connection to twitch chat
irc.send('PASS ' + password + '\r\n')
irc.send('USER ' + nick + ' 0 * :' + bot_owner + '\r\n')
irc.send('NICK ' + nick + '\r\n')
irc.send('JOIN ' + channel + '\r\n') 

I'm trying to make a bot for twitch chat but when I run this code I get the error I'm using someone elses code that works for them but not for me

Traceback (most recent call last):
  File "C:/Users/Owner/Desktop/TheMagicalCake", line 47, in <module>
    irc.connect((server, 6667)) #connects to the server
  File "C:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
gaierror: [Errno 11004] getaddrinfo failed

Answer

Sam van Kampen picture Sam van Kampen · Feb 18, 2014

getaddrinfo failed generally means that the hostname you are trying to connect to can not be resolved to an IP address. In this case, it probably means that it doesn't exist.

Why?

When you pass socket.connect() a hostname instead of an IP address, it first needs to find the IP address of said hostname. It does this using socket.getaddrinfo(), which asks DNS servers for information about the hostname. It turns out that no DNS server has this information, so the call to getaddrinfo fails, hence the error message.

How to connect to Twitch's IRC

The procedure of connecting to Twitch's IRC has changed a bit since your guide was made, it seems. Here's how I managed to do it.

  • Get an OAuth token from TwitchApps
  • Connect, with your twitch username, to irc.twitch.tv, port 6667. As password, use oauth: plus the oauth token you just got.
  • Join the channel you are streaming on.