Advertisement
Guest User

Twitch Bot Python Code

a guest
Dec 19th, 2017
584
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.94 KB | None | 0 0
  1. # import functions/scripts
  2. import socket
  3. import threading
  4. import os
  5. import traceback
  6. import requests
  7. import sqlite3
  8. import time
  9.  
  10. ### connecting to Twitch IRC // DO NOT CHANGE THIS VALUE
  11. HOST = "irc.chat.twitch.tv"
  12. PORT = 6667
  13.  
  14. ### User Editable Settings
  15. NICK = "sp4wnytv"  # Bots nickname
  16. CHAN = "sp4wnyuk"  # Channel bot is joining
  17. PASS = "oauth:3ey8xr1z5xe98j9re2jfdlfomdag1o"  #Twitch OAuth
  18.  
  19. readbuffer = ""
  20. MODT = False
  21.  
  22. ### DO NOT EDIT THESE VALUES
  23. CHANNEL_NAME = CHAN
  24. CHANNEL_NAME = CHANNEL_NAME.lower()
  25. SLEEP_TIME = 120
  26. #IRC_CHANNEL = "#" + CHANNEL_NAME
  27. #APIKey = "RGAPI-c2b5b567-5229-46e9-b7b8-7eb218c1ea8f"
  28. #HOST2 = "199.9.253.119"
  29.  
  30.  
  31. # Connecting to Twitch IRC by passing credentials and joining a certain channel
  32. s = socket.socket()
  33. s.connect((HOST, PORT))
  34. s.send(bytes("PASS %s\r\n" % PASS, "UTF-8"))
  35. s.send(bytes("NICK %s\r\n" % NICK, "UTF-8"))
  36. s.send(bytes("JOIN #%s\r\n" % CHAN, "UTF-8"))
  37. s.send(bytes("CAP REQ :twitch.tv/membership\r\n", "UTF-8"))
  38. s.send(bytes("CAP REQ :twitch.tv/commands\r\n", "UTF-8"))
  39. s.send(bytes("CAP REQ :twitch.tv/tags\r\n", "UTF-8"))
  40.  
  41.  
  42. def socketconnection():
  43.     global s, HOST, PORT, NICK, CHAN
  44.     try:
  45.         s.close()
  46.         s.socket.socket()
  47.         s.connect((HOST, PORT))
  48.         s.send(bytes("PASS %s\r\n" % PASS, "UTF-8"))
  49.         s.send(bytes("NICK %s\r\n" % NICK, "UTF-8"))
  50.         s.send(bytes("JOIN #%s\r\n" % CHAN, "UTF-8"))
  51.         s.send(bytes("CAP REQ :twitch.tv/membership\r\n", "UTF-8"))
  52.         s.send(bytes("CAP REQ :twitch.tv/commands\r\n", "UTF-8"))
  53.         s.send(bytes("CAP REQ :twitch.tv/tags\r\n", "UTF-8"))
  54.     except:
  55.         print(traceback.format_exc())
  56.  
  57. #opens channel database or creates new database if one does not already exist
  58. if os.path.exists("{}DB".format(CHAN)):
  59.     dbcon = sqlite3.connect("{}DB".format(CHAN))
  60.     cursor = dbcon.cursor()
  61. else:
  62.     dbcon = sqlite3.connect("{}DB".format(CHAN))
  63.     cursor = dbcon.cursor()
  64.     cursor.execute('CREATE TABLE channelPoints(username text PRIMARY KEY,points INT DEFAULT 0)')
  65.     dbcon.commit()
  66.  
  67. ### Functions
  68.  
  69.  
  70. def tablereport():
  71.     global dbcon
  72.     global cursor
  73.  
  74.     for x in cursor.execute('SELECT * from channelPoints ORDER BY points'):
  75.         sendmessage(x)
  76.  
  77.  
  78. def requestpoints(message, username):
  79.     global dbcon
  80.     global cursor
  81.  
  82.     messagelist = message.split()
  83.     index = messagelist.index('!points')
  84.     try:
  85.         if len(messagelist) == 1:
  86.             u = username
  87.         elif len(messagelist) == 2:
  88.             u = messagelist[index + 1]
  89.         cursor.execute('SELECT points FROM channelPoints WHERE username=?', ((u,)))
  90.         sendmessage('{} currently has {} point(s)'.format(username, cursor.fetchone()[0]))
  91.     except:
  92.         print(traceback.format_exc())
  93.  
  94.  
  95. def givepoints(username, points):
  96.     global dbcon
  97.     global cursor
  98.     try:
  99.         cursor.execute('UPDATE channelPoints SET points=points+? WHERE username=?', (points, username))
  100.         dbcon.commit()
  101.     except:
  102.         print(traceback.format_exc())
  103.  
  104.  
  105. def getuser(line):
  106.     separate = line.split(":", 2)
  107.     user = separate[1].split("!", 1)[0]
  108.     return user
  109.  
  110.  
  111. def sendmessage(text):
  112.     # Method for sending a message
  113.     # message = "PRIVMSG #" + CHAN + " :" + str(text)
  114.     s.send(bytes("PRIVMSG #" + CHAN + " :" + str(text) + "\r\n", "UTF-8"))
  115.     # print("Sent Msg: " + message)
  116.  
  117.  
  118. def console(line):
  119.     # Gets if it is a user or twitch server
  120.     if "PRIVMSG" in line:
  121.         return False
  122.     else:
  123.         return True
  124.  
  125.  
  126. def timeout(user, secs):
  127.     timeout_message = "PRIVMSG #" + CHAN + ": /timeout %s %s\r\n" % (user, secs)
  128.     s.send(bytes(timeout_message), "UTF-8")
  129.  
  130.  
  131. def uptime():
  132.     global CHAN
  133.     url = "https://decapi.me/twitch/uptime?channel={}".format(CHAN)
  134.     page = requests.get(url)
  135.     for x in page:
  136.         if ('is offline' not in x.strip().decode('UTF-8')):
  137.             sendmessage("{} has been online for {}".format(CHAN, x.strip().decode('UTF-8')))
  138.         else:
  139.             sendmessage(x.strip().decode('UTF-8'))
  140.  
  141.  
  142. def followage(username):
  143.     global CHAN
  144.     url = "https://decapi.me/twitch/followage/{}/{}?precision=4".format(CHAN, username)
  145.     page = requests.get(url)
  146.     for x in page:
  147.         # sendmessage(x.decode('UTF-8')) ## output just the value
  148.         if('cannot follow themself' in x.strip().decode('UTF-8')):
  149.             sendmessage("{} you cannot follow yourself.".format(username, x.strip().decode('UTF-8')))
  150.         else:
  151.             sendmessage("{} has been following for {}".format(username, x.strip().decode('UTF-8')))
  152.  
  153.  
  154. def followcount():
  155.     global CHAN
  156.     url = "https://decapi.me/twitch/followcount/{}".format(CHAN)
  157.     page = requests.get(url)
  158.     for x in page:
  159.         #sendmessage(x.decode('UTF-8')) ## output just the value
  160.         sendmessage("{} has {} savages following the channel!".format(CHAN, x.strip().decode('UTF-8')))
  161.  
  162.  
  163. def puppet():
  164.     try:
  165.         while True:
  166.             message = input(' assuming direct control: ')
  167.             sendmessage(message)
  168.             commands(message, 'sp4wnybot')
  169.     except BrokenPipeError:
  170.         socketconnection()
  171.  
  172.  
  173. def commands(message, username):
  174.  
  175.     if message == "!meme":
  176.         sendmessage("EleGiggle")
  177.  
  178.     if message == "!sliced":
  179.         sendmessage("**unsheathes katana**")
  180.  
  181.     if message == "!whoami":
  182.         sendmessage(username)
  183.  
  184.     if '!test' in message and username == 'sp4wnyuk':
  185.         tablereport()
  186.  
  187.     if '!points' in message and username == 'sp4wnyuk':
  188.         requestpoints(message, username)
  189.  
  190.     if '!givepoints' in message and username == 'sp4wnyuk':
  191.         messagelist = message.split()
  192.         index = messagelist.index('!givepoints')
  193.         u = str(messagelist[index + 1])  # username
  194.         p = messagelist[index + 2]  # points
  195.         givepoints(u, p)
  196.  
  197.     if message == '!uptimet':
  198.         uptime()
  199.  
  200.     if message == '!followage':
  201.         followage(username)
  202.  
  203.     if message == '!followers':
  204.         followcount()
  205.  
  206.  
  207. sendmessage('sp4wnys bot has joined the channel')
  208. t = threading.Thread(target=puppet).start()
  209.  
  210.  
  211. def messageloop():
  212.     while True:
  213.         global s, readbuffer, dbcon, cursor
  214.  
  215.         try:
  216.             readbuffer = readbuffer + s.recv(1024).decode("UTF-8")
  217.         except KeyboardInterrupt:
  218.             raise
  219.         except:
  220.             print(traceback.format_exc())
  221.  
  222.         temp = str.split(readbuffer, "\r\n")
  223.         # temp = [ str(e.encode('UTF-8')).rstrip() for e in temp ]
  224.         readbuffer = temp.pop()
  225.  
  226.         for line in temp:
  227.             if line == "":
  228.                 break
  229.             if line[0] and console(line) == "PING":
  230.                 #hellotwitch = "PONG :tmi.twitch.tv\r\n".encode("UTF-8")
  231.                 #s.send(bytes(hellotwitch))
  232.                 s.send(line.replace("PING", "PONG").encode("UTF-8"))
  233.                 print("PONG")
  234.                 break
  235.             if "PRIVMSG" in line:
  236.                 parts = str.split(line, ":")
  237.                 message = parts[2][:len(parts[2])]
  238.                 usernamesplit = str.split(parts[1], "!")
  239.                 username = usernamesplit[0]
  240.                 print("Chat | " + username + ": " + message)
  241.             else:
  242.                 parts = str.split(line, ":")
  243.  
  244.                 try:
  245.                     message = parts[2][:len(parts[2`])]
  246.  
  247.                 except:
  248.                     message = ""
  249.  
  250.                 usernamesplit = str.split(parts[1], "!")
  251.                 username = usernamesplit[0]
  252.  
  253.                 cursor.execute('INSERT OR IGNORE INTO channelPoints (username, points) VALUES (?,?)', (username, '0'))
  254.                 givepoints(username, 1)
  255.                 dbcon.commit()
  256.  
  257.                 print("Bot | " + username + ": " + message)
  258.                 commands(message.lower(), username.lower())
  259.  
  260.  
  261. while True:
  262.     try:
  263.         messageloop()
  264.     except KeyboardInterrupt:
  265.         raise
  266.     except:
  267.         print(traceback.format_exc())
  268.         socketconnection()
  269.         messageloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement