SHARE
TWEET

Untitled

a guest Jan 19th, 2020 208 in 148 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import time
  2. import socket
  3. import string
  4. import sys
  5. import threading
  6. import json # for loading json's for emoticons
  7. import urllib.request # more for loadings jsons from urls
  8. import collections # for deque
  9. from decimal import *
  10. import operator # for sorting dictionary by value
  11. from random import choice
  12. import os # to allow directory exists checking etc.
  13. import ssl # required for urllib certificates
  14. import requests
  15. import pymysql
  16. #import all secret parameters from parameters file
  17. from IRCBetBot_Parameters import parameters
  18. #import the GUI
  19. from tkinter import *
  20. import threading
  21. from threading import Thread
  22.  
  23.  
  24. #Because python floating point arthmatic is a nightmare
  25. TWOPLACES = Decimal(10) ** -2
  26.  
  27. #Here are the message lines held until sent
  28. messageDeque = collections.deque()
  29. toSend = False
  30.  
  31.  
  32.  
  33.  
  34. class IRCClient(threading.Thread):
  35.  
  36.     parameters = parameters()
  37.     parameters.load()
  38.  
  39.     adminUserName = parameters.privatedata['adminUserName']                         # This username will be able to use admin commands, exit the program and bypass some limits.
  40.     nick = parameters.privatedata['IRCnick']                                #This value is the username used to connect to IRC eg: "xcomreborn".
  41.     channel = "#" + parameters.data['channel']                              #The channel name for your channel eg: "#xcomreborn".
  42.     password = parameters.privatedata['IRCpassword']                        #alter this value with the password oauth:sting used to connect to IRC from the username above.
  43.     server = parameters.privatedata['IRCserver']
  44.     port = parameters.privatedata['IRCport']
  45.     relicServerProxy = parameters.privatedata['relicServerProxy']
  46.    
  47.     #create IRC socket
  48.     try:
  49.         irc = socket.socket()
  50.     except Exception as e:
  51.         print("A problem occurred trying to connect")
  52.         print(str(e))
  53.         irc.close()
  54.         sys.exit(0)
  55.    
  56.     #irc send message buffer
  57.     ircMessageBuffer = collections.deque()
  58.  
  59.    
  60.    
  61.     def __init__(self):
  62.  
  63.         Thread.__init__(self)
  64.  
  65.         self.running = True
  66.        
  67.         # Start checking send buffer every 2 seconds.
  68.         self.CheckIRCSendBufferEveryTwoSeconds() # only call this once.
  69.        
  70.  
  71.         self.irc.connect((self.server, self.port))
  72.  
  73.         #sends variables for connection to twitch chat
  74.         self.irc.send(('PASS ' + self.password + '\r\n').encode("utf8"))
  75.         self.irc.send(('USER ' + self.nick + '\r\n').encode("utf8"))
  76.         self.irc.send(('NICK ' + self.nick + '\r\n').encode("utf8"))
  77.         self.irc.send(('CAP REQ :twitch.tv/membership' + '\r\n').encode("utf8")) # sends a twitch specific request necessary to recieve mode messages
  78.         self.irc.send(('CAP REQ :twitch.tv/tags'+ '\r\n').encode("utf8")) # sends a twitch specific request for extra data contained in the PRIVMSG changes the way it is parsed
  79.         self.irc.send(('CAP REQ :twitch.tv/commands' + '\r\n').encode("utf8")) # supposidly adds whispers
  80.         self.irc.send(('JOIN ' + self.channel + '\r\n').encode("utf8"))
  81.  
  82.  
  83.        
  84.        
  85.     def run(self):
  86.  
  87.         self.running = True
  88.  
  89.         #create readbuffer to hold strings from IRC
  90.         readbuffer = ""    
  91.        
  92.         # This is the main loop
  93.         while self.running:
  94.             if (self.running == False):
  95.                 print("closing main loop of IRC")
  96.                 break
  97.             readbuffer= readbuffer+self.irc.recv(1024).decode("utf-8")
  98.             temp=str.split(readbuffer, "\n")
  99.             readbuffer=temp.pop( )
  100.            
  101.  
  102.             for line in temp:
  103.                 line=str.rstrip(line)
  104.                 line=str.split(line)
  105.                 print (str(line).encode('utf8'))
  106.                 if(line[0] == "CLOSE"):
  107.                     print("closing finally")
  108.                
  109.                 if (len(line) >= 4) and ("PRIVMSG" == line[2]) and not ("jtv" in line[0]):
  110.                     #call function to handle user message
  111.                     self.UserMessage(line)
  112.                 if (len(line) >= 3) and ("JOIN" == line[2]):
  113.                     pass
  114.                     # call function to handle join messages
  115.                     #self.UserJoined(line)
  116.                 if (len(line) >= 5) and ("MODE" == line[2]):
  117.                     pass
  118.                     # call function to assign and remove OPs
  119.                     #self.AssignOPs(line)
  120.                 if(line[0]=="PING"):
  121.                     self.irc.send(("PONG %s\r\n" % line[0]).encode("utf8"))
  122.                    
  123.     def close(self):
  124.         self.running = False
  125.         print("in close in thread")
  126.         self.irc.send(("PRIVMSG " + self.channel + " :" + str("closing opponent bot") + "\r\n").encode('utf8'))
  127.            
  128.     def AssurePathExists(self, path):
  129.         dir = os.path.dirname(path)
  130.         if not os.path.exists(dir):
  131.             os.makedirs(dir)
  132.            
  133.  
  134.        
  135.     def CheckIRCSendBufferEveryTwoSeconds(self):
  136.         self.running
  137.         if (self.running == True):
  138.             threading.Timer(3.0, self.CheckIRCSendBufferEveryTwoSeconds).start()
  139.         self.IRCSendCalledEveryTwoSeconds()
  140.     # above is the send to IRC timer loop that runs every two seconds
  141.    
  142.     def SendPrivateMessageToIRC(self, message):
  143.         self.ircMessageBuffer.append(message)   # removed this to stop message being sent to IRC
  144.  
  145.    
  146.  
  147.     def IRCSendCalledEveryTwoSeconds(self):
  148.         if (self.ircMessageBuffer):
  149.             try:
  150.                 self.irc.send(("PRIVMSG " + self.channel + " :" + str(self.ircMessageBuffer.popleft()) + "\r\n").encode('utf8'))
  151.             except Exception as e:
  152.                 print("IRC send error:")
  153.                 print(str(e))
  154.     #above is called by the timer every two seconds and checks for items in buffer to be sent, if there is one it'll send it
  155.  
  156.  
  157.    
  158.     def UserMessage(self, line):
  159.         self.running
  160.         # Dissect out the useful parts of the raw data line into username and message and remove certain characters
  161.         msgFirst = line[1]
  162.         msgUserName = msgFirst[1:]
  163.         msgUserName = msgUserName.split("!")[0]
  164.         msgType = line [1];
  165.         msgChannel = line [3]
  166.         msgMessage = " ".join(line [4:])
  167.         msgMessage = msgMessage[1:]
  168.         messageString = str(msgUserName) + " : " + str(msgMessage)
  169.         print (str(messageString).encode('utf8'))
  170.  
  171.         #Check for UserCommands
  172.         self.CheckForUserCommand(msgUserName, msgMessage)
  173.        
  174.    
  175.         if (msgMessage == "exit") and (msgUserName == self.adminUserName):
  176.             print("Exiting")
  177.             self.running = False
  178.             while (threading.active_count() > 1):
  179.                 pass
  180.             sys.exit(1)
  181.            
  182.     def CheckForUserCommand(self, userName, message):
  183.         try:
  184.             wordList = message.split()
  185.             if (message.lower() == "opponent") or (message.lower() == "place your bets") or (message.lower() == "!opponent"):
  186.                 myLoadLog = HandleCOHlogFile()
  187.                 returnedList = []
  188.                 returnedList =  myLoadLog.loadLog()
  189.                 if returnedList:
  190.                     self.SendPrivateMessageToIRC(str(returnedList[-1]))
  191.                     self.SendPrivateMessageToIRC(str(returnedList[-2]))
  192.  
  193.                
  194.                
  195.         except Exception as e:
  196.             print("Error in CheckForUserCommand")
  197.             print(e)
  198.  
  199.  
  200. class StatsRequest:
  201.     def __init__(self):
  202.         pass
  203.    
  204.     # return stats by name isn't in use anymore due to steam webpage changes
  205.     #def returnStatsName(self, name):
  206.     #   try:
  207.     #       print("got name : " + str(name))
  208.     #       steamURL = "https://steamcommunity.com/search/users/#filter=users&text=" + str (name)
  209.     #       if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)):
  210.     #           ssl._create_default_https_context = ssl._create_unverified_context
  211.     #       scrapedData =  urllib.request.urlopen(steamURL).read()
  212.     #       scrapedData = str(scrapedData.decode('utf-8'))  
  213.     #      
  214.     #       print(scrapedData)
  215.     #       steamNumber = self.find_between(scrapedData, "steamID64<h2 id=\"steamID64\">", "</h2>")
  216.     #       print(steamNumber)
  217.     #       return self.returnStats(steamNumber)
  218.     #      
  219.     #   except Exception as e:
  220.     #       print("Error in returnStatsName")
  221.     #       print(e)
  222.        
  223.    
  224.     def find_between(self, s, first, last ):
  225.         try:
  226.             start = s.index( first ) + len( first )
  227.             end = s.index( last, start )
  228.             return s[start:end]
  229.         except ValueError:
  230.             return ""  
  231.    
  232.    
  233.     def returnStats(self, statnumber):
  234.         try:
  235.             print ("got statnumber : " + str(statnumber))
  236.             statString = "/steam/" + str(statnumber)
  237.             if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)):
  238.                 ssl._create_default_https_context = ssl._create_unverified_context
  239.             response = urllib.request.urlopen(self.relicServerProxy+str(statnumber)).read()
  240.             statdata = json.loads(response.decode('utf-8'))
  241.             print(statdata)
  242.             if (statdata['result']['message'] == "SUCCESS"):
  243.                 print ("statdata load succeeded")
  244.                 if statdata['statGroups'][0]['members'][0]['alias']:
  245.                     for item in statdata['statGroups']:
  246.                         for value in item['members']:
  247.                             if (value['name'] == statString):
  248.                                 userName = value['alias']
  249.                 else:
  250.                     userName = ""
  251.                    
  252.                 if statdata['leaderboardStats']:
  253.                     American1v1rank = ""
  254.                     Wehrmacht1v1rank = ""
  255.                     PE1v1rank = ""
  256.                     CommonWealth1v1rank = ""
  257.                     for idx, item in enumerate(statdata['leaderboardStats']):
  258.                         if item['leaderboard_id'] == 4:
  259.                             American1v1rank = item['rank']
  260.                             if American1v1rank == -1:
  261.                                 American1v1rank = "None"
  262.                            
  263.                         if item['leaderboard_id'] == 5:
  264.                             Wehrmacht1v1rank = item['rank']
  265.                             if Wehrmacht1v1rank == -1:
  266.                                 Wehrmacht1v1rank = "None"
  267.                    
  268.                         if item['leaderboard_id'] == 7:
  269.                             PE1v1rank = item['rank']
  270.                             if PE1v1rank == -1:
  271.                                 PE1v1rank = "None"
  272.                            
  273.                         if item['leaderboard_id'] == 6:
  274.                             CommonWealth1v1rank = item['rank']
  275.                             if CommonWealth1v1rank == -1:
  276.                                 CommonWealth1v1rank = "None"
  277.                          
  278.                        
  279.                     str1 = " UserName : " + str(userName)
  280.                     str2 = ' : 1v1 ranks '
  281.                     str3 = " : American : " + str(American1v1rank)
  282.                     str4 = " : Wehrmacht : " + str(Wehrmacht1v1rank)
  283.                     str5 = " : PE : " + str(PE1v1rank)
  284.                     str6 =" : CommonWealth : " + str(CommonWealth1v1rank)
  285.                     catString = str1 + str2 + str3 +str4 + str5 + str6
  286.                    
  287.                     return catString
  288.        
  289.            
  290.         except Exception as e:
  291.             print("Error in returnStats")
  292.             print(e)
  293.  
  294.  
  295.  
  296. class HandleCOHlogFile:
  297.    
  298.  
  299.     def __init__(self):
  300.         self.parameters = parameters()
  301.         self.logPath = self.parameters.data['logPath']
  302.         self.data = []
  303.    
  304.     def loadLog(self):
  305.         print("In loadLog")
  306.         try:
  307.             with open(self.logPath, encoding='ISO-8859-1') as file:
  308.                 content = file.readlines()
  309.            
  310.            
  311.             print(self.parameters.data['steamNumber'])
  312.             steamNumberList = []
  313.             for item in content:
  314.                 if ("match started") in item.lower():
  315.                     print (item)
  316.                     steamNumber = self.find_between(item, "steam/", "]")
  317.                     ranking = self.find_between(item, "ranking =","\n")
  318.                     if (str(steamNumber) == str(self.parameters.data['steamNumber'])):
  319.                         pass
  320.                     else:
  321.                         steamNumberList.append(steamNumber)
  322.             if (steamNumberList):
  323.                 print(steamNumberList)
  324.                 # if this list exists get the last number in it then perform a stat request
  325.                 steamURL = "http://steamcommunity.com/profiles/" + str(steamNumberList[-1])
  326.                 self.data.append("Steam profile " + str(steamURL))     
  327.                 myStatRequest = StatsRequest()
  328.                 try:
  329.                     statNumber = int(steamNumberList[-1])
  330.                     self.data.append(str(myStatRequest.returnStats(statNumber)))
  331.                 except ValueError:
  332.                     print ("got a value error")                    
  333.  
  334.            
  335.             if self.data:
  336.                 return self.data
  337.             else:
  338.                 return None
  339.                    
  340.         except Exception as e:
  341.             print ("Error in LoadLog")
  342.             print (str(e))
  343.            
  344.    
  345.     def find_between(self, s, first, last ):
  346.         try:
  347.             start = s.index( first ) + len( first )
  348.             end = s.index( last, start )
  349.             return s[start:end]
  350.         except ValueError:
  351.             return ""
  352.  
  353. # to use this file without the GUI be sure to have the parameters file in the same directory and uncomment below
  354. #myIRC = IRCClient()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top