Advertisement
Guest User

Python Twitch Chatbot

a guest
Oct 23rd, 2016
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.31 KB | None | 0 0
  1. import requests
  2. import socket
  3. import string
  4. import time
  5.  
  6.  
  7. # EXAMPLE USAGE
  8. #
  9. # from TwitchBot import TwitchBot
  10. #
  11. # ChatBot = TwitchBot("yourchannelname", "yourbotname", "yourbotpassword")
  12. #
  13. # while True:
  14. #     ChatBot.update()
  15. #     print(ChatBot.user + ": " + ChatBot.message)
  16.  
  17.  
  18. class TwitchBot:
  19.  
  20.     def __init__(self,channelName="",botName="",botPassword="",host="irc.twitch.tv",port=6667):
  21.    
  22.         # Setting up class variables
  23.         self.channelName = channelName
  24.         self.botName = botName
  25.         self.botPassword = botPassword
  26.         self.host = host
  27.         self.port = port  
  28.         self.message  = ""
  29.         self.user = ""
  30.         self.modList = []
  31.         self.usrList = []
  32.        
  33.         # Setting up the connection
  34.         self.socket = self.openSocket(self.channelName,self.botName,self.botPassword,self.host,self.port)
  35.         if self.joinRoom(self.socket) == True:
  36.             print("Successful connection to " + "www.twitch.tv/" + self.channelName + " as " + self.botName)
  37.  
  38.            
  39.     def openSocket(self,CHAN,USER,PASS,HOST,PORT):
  40.  
  41.         s = socket.socket()
  42.         s.connect((HOST, PORT))
  43.  
  44.         message = "PASS " + PASS + "\r\n"
  45.         s.send(message.encode('utf-8'))
  46.         message = "NICK " + USER + "\r\n"
  47.         s.send(message.encode('utf-8'))
  48.         message = "JOIN #" + CHAN + "\r\n"
  49.         s.send(message.encode('utf-8'))
  50.  
  51.         return s    
  52.        
  53.        
  54.     def joinRoom(self, s):
  55.    
  56.         readbuffer = ""
  57.         Loading = True
  58.  
  59.         while Loading:
  60.             readbuffer = readbuffer + s.recv(1024).decode()
  61.             temp = readbuffer.split('\n')
  62.  
  63.             readbuffer = temp.pop()
  64.  
  65.             for line in temp:
  66.                 Loading = self.loadingComplete(line)
  67.        
  68.         return True
  69.  
  70.        
  71.     def loadingComplete(self, line):
  72.    
  73.         if("End of /NAMES list" in line):
  74.             return False;
  75.         else: return True
  76.  
  77.        
  78.     def getUser(self, line):
  79.    
  80.         separate = line.split(":", 2)
  81.         user = separate[1].split("!", 1)[0]
  82.  
  83.         return user
  84.        
  85.        
  86.     def getMessage(self, line):
  87.    
  88.         separate = line.split(":", 2)
  89.         if(separate[0] == 'PING '):
  90.             message = self.getPing(line)
  91.         else:
  92.             message = separate[2]
  93.        
  94.         return message
  95.  
  96.        
  97.     def getPing(self, line):
  98.    
  99.         separate = line.split(":", 2)
  100.         message = separate[1]
  101.        
  102.         return message
  103.        
  104.        
  105.     def sendMessage(self, message):
  106.    
  107.         messageTemp = "PRIVMSG #" + self.channelName + " :" + message + "\r\n"
  108.         self.socket.send(messageTemp.encode('utf-8'))
  109.        
  110.        
  111.     def update(self):
  112.  
  113.         # Read the next chat message, if any
  114.         readbuffer = ""
  115.         try:
  116.             readbuffer = readbuffer + s.recv(1024).decode("utf-8")
  117.         except:
  118.             self.socket = self.openSocket(self.channelName,self.botName,self.botPassword,self.host,self.port)
  119.             self.joinRoom(self.socket)
  120.             readbuffer = readbuffer + self.socket.recv(1024).decode("utf-8")
  121.  
  122.         temp = readbuffer.split('\n')
  123.         readbuffer = temp.pop()
  124.  
  125.         for line in temp:
  126.             if line.startswith("PING "):
  127.                 strSend = "PONG :tmi.twitch.tv\r\n".encode('utf-8')
  128.                 self.socket.send(strSend)
  129.  
  130.             lastMsg = self.message
  131.             usr = self.getUser(line)
  132.             msg = self.getMessage(line)
  133.        
  134.         # Do some maintenance on the data
  135.         self.message = msg.strip("\n")
  136.         self.message = self.message.strip("\r")
  137.         self.user = usr.strip("\n")
  138.         self.user = self.user.strip("\r")
  139.  
  140. # Everything below here is optional. Used only if you want the ability to grab the list of viewers/mods
  141.  
  142.     def updateLists(self):
  143.    
  144.         response = requests.get("https://tmi.twitch.tv/group/user/" + self.channelName + "/chatters")
  145.         findStr = response.text
  146.  
  147.         splitList = []
  148.         modListTmp = []
  149.         usrListTmp = []
  150.  
  151.         # Sloppy web scraping
  152.         for i in range(0,5):
  153.             begin = findStr.find("[")
  154.             end = findStr.find("]")
  155.             subStr = findStr[begin+1:end]          
  156.             subStrTokens = subStr.split("\"")  
  157.  
  158.             for val in subStrTokens:
  159.                 subStrTokens[val.find(val)] = val.strip(",")
  160.  
  161.             if i == 0:
  162.                 for token in subStrTokens:
  163.                     if token != "" and token[0].isalnum():
  164.                         modListTmp.append(token)
  165.             if i == 4:
  166.                 for token in subStrTokens:
  167.                     try:
  168.                         if token[0].isalnum():
  169.                             usrListTmp.append(token)        
  170.                     except: pass
  171.                
  172.             findStr = findStr[end+1:]  
  173.        
  174.         # Update the lists all at once
  175.         self.usrList = usrListTmp[:]
  176.         self.modList = modListTmp[:]
  177.  
  178.        
  179.     def getUsers(self):
  180.    
  181.         self.updateLists()
  182.         return self.usrList
  183.  
  184.        
  185.     def getMods(self):
  186.    
  187.         self.updateLists()
  188.         return self.modList
  189.        
  190.        
  191.     def getNumViewers(self):
  192.         self.updateLists()
  193.         return len(self.usrList) + len(self.modList)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement