Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import re
- import socket
- import string
- import sys
- import threading
- import json # for loading json's for emoticons
- import urllib.request # more for loadings jsons from urls
- import collections # for deque
- from decimal import *
- import operator # for sorting dictionary by value
- from random import choice
- import os # to allow directory exists checking etc.
- import requests
- import pymysql
- #Because python floating point arthmatic is a nightmare
- TWOPLACES = Decimal(10) ** -2
- #Define Global Variables
- running = True;
- #Here are the message lines held until sent
- messageDeque = collections.deque()
- toSend = False
- class IRCClient:
- AdminUserName = "statementcoh" # This username will be able to use admin commands and bypass some limits.
- nick = 'statementbot' #alter this value with the username used to connect to IRC eg: "xcomreborn".
- channel = '#statementcoh' #alter this value with the channel name for your channel eg: "#xcomreborn".
- password = "oauth:e3cm63kjau8918hd3ewu26jgqkimzo" #alter this value with the password used to connect to IRC from the username above.
- server = 'irc.twitch.tv'
- port = 6667
- #create IRC socket
- irc = socket.socket()
- #irc send message buffer
- ircMessageBuffer = collections.deque()
- def __init__(self):
- global running
- # Start checking send buffer every 2 seconds.
- self.CheckIRCSendBufferEveryTwoSeconds() # only call this once.
- self.irc.connect((self.server, self.port))
- #sends variables for connection to twitch chat
- self.irc.send(('PASS ' + self.password + '\r\n').encode("utf8"))
- self.irc.send(('USER ' + self.nick + '\r\n').encode("utf8"))
- self.irc.send(('NICK ' + self.nick + '\r\n').encode("utf8"))
- self.irc.send(('JOIN ' + self.channel + '\r\n').encode("utf8"))
- #create readbuffer to hold strings from IRC
- readbuffer = ""
- #self.SendPrivateMessageToIRC("/mod xcoinbetbot")
- # This is the main loop
- while 1:
- readbuffer= readbuffer+self.irc.recv(1024).decode("utf-8")
- temp=str.split(readbuffer, "\n")
- readbuffer=temp.pop( )
- for line in temp:
- line=str.rstrip(line)
- line=str.split(line)
- print (str(line).encode('utf8'))
- if (len(line) >= 4) and ("PRIVMSG" == line[1]) and not ("jtv" in line[0]):
- #call function to handle user message
- self.UserMessage(line)
- if (len(line) >= 3) and ("JOIN" == line[1]):
- pass
- # call function to handle join messages
- #self.UserJoined(line)
- if (len(line) >= 5) and ("MODE" == line[1]):
- pass
- # call function to assign and remove OPs
- #self.AssignOPs(line)
- if(line[0]=="PING"):
- self.irc.send(("PONG %s\r\n" % line[0]).encode("utf8"))
- def AssurePathExists(self, path):
- dir = os.path.dirname(path)
- if not os.path.exists(dir):
- os.makedirs(dir)
- def CheckIRCSendBufferEveryTwoSeconds(self):
- global running
- if (running == True):
- threading.Timer(3.0, self.CheckIRCSendBufferEveryTwoSeconds).start()
- self.IRCSendCalledEveryTwoSeconds()
- # above is the send to IRC timer loop that runs every two seconds
- def SendPrivateMessageToIRC(self, message):
- self.ircMessageBuffer.append(message) # removed this to stop message being sent to IRC
- def IRCSendCalledEveryTwoSeconds(self):
- if (self.ircMessageBuffer):
- try:
- self.irc.send(("PRIVMSG " + self.channel + " :" + str(self.ircMessageBuffer.popleft()) + "\r\n").encode('utf8'))
- except Exception as e:
- print("IRC send error:")
- print(str(e))
- #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
- def UserMessage(self, line):
- global running
- # Dissect out the useful parts of the raw data line into username and message and remove certain characters
- msgFirst = line[0]
- msgUserName = msgFirst[1:]
- msgUserName = msgUserName.split("!")[0]
- msgType = line [1];
- msgChannel = line [2]
- msgMessage = " ".join(line [3:])
- msgMessage = msgMessage[1:]
- messageString = str(msgUserName) + " : " + str(msgMessage)
- print (str(messageString).encode('utf8'))
- #Check for UserCommands
- self.CheckForUserCommand(msgUserName, msgMessage)
- if (msgMessage == "exit") and (msgUserName == self.AdminUserName):
- running = False
- self.IRC.close()
- while (threading.active_count() > 1):
- pass
- sys.exit(1)
- if (msgMessage == "flak") and (msgUserName == "alfredjodocusquack"):
- return "Alfred Jodocus Flak Kreygasm Kreygasm"
- if(msg_split[0] == "flak"):
- sendmsg(channel, "FLAK LOCATION Kreygasm Kreygasm Kreygasm")
- def CheckForUserCommand(self, userName, message):
- try:
- wordList = message.split()
- if (message.lower() == "opponent") or (message.lower() == "place your bets") or (message.lower() == "!opponent"):
- myLoadLog = HandleCOHlogFile()
- returnedList = []
- returnedList = myLoadLog.loadLog()
- if returnedList:
- self.SendPrivateMessageToIRC(str(returnedList[-1]))
- self.SendPrivateMessageToIRC(str(returnedList[-2]))
- except Exception as e:
- print("Error in check for user command")
- print(e)
- # Here goes code outside the class
- class StatsRequest:
- def __init__(self):
- pass
- def returnStatsName(self, name):
- try:
- print("got name : " + str(name))
- steamURL = "http://xcoins.co.uk/secreturl.php?steamUserID=" + str (name)
- scrapedData = urllib.request.urlopen(steamURL).read()
- scrapedData = str(scrapedData.decode('utf-8'))
- steamNumber = self.find_between(scrapedData, "steamID64<h2 id=\"steamID64\">", "</h2>")
- return self.returnStats(steamNumber)
- except Exception as e:
- print("error in returnstats name")
- print(e)
- def find_between(self, s, first, last ):
- try:
- start = s.index( first ) + len( first )
- end = s.index( last, start )
- return s[start:end]
- except ValueError:
- return ""
- def returnStats(self, statnumber):
- try:
- statString = "/steam/" + str(statnumber)
- response = urllib.request.urlopen('http://xcoins.co.uk/secreturl.php?steamUserID='+str(statnumber)).read()
- statdata = json.loads(response.decode('utf-8'))
- if (statdata['result']['message'] == "SUCCESS"):
- if statdata['statGroups'][0]['members'][0]['alias']:
- for item in statdata['statGroups']:
- for value in item['members']:
- if (value['name'] == statString):
- userName = value['alias']
- else:
- userName = ""
- if statdata['leaderboardStats']:
- American1v1rank = ""
- Wehrmacht1v1rank = ""
- PE1v1rank = ""
- CommonWealth1v1rank = ""
- for idx, item in enumerate(statdata['leaderboardStats']):
- if item['leaderboard_id'] == 4:
- American1v1rank = item['rank']
- if American1v1rank == -1:
- American1v1rank = "N/A"
- if item['leaderboard_id'] == 5:
- Wehrmacht1v1rank = item['rank']
- if Wehrmacht1v1rank == -1:
- Wehrmacht1v1rank = "N/A"
- if item['leaderboard_id'] == 7:
- PE1v1rank = item['rank']
- if PE1v1rank == -1:
- PE1v1rank = "N/A"
- if item['leaderboard_id'] == 6:
- CommonWealth1v1rank = item['rank']
- if CommonWealth1v1rank == -1:
- CommonWealth1v1rank = "N/A"
- str1 = "Username: " + str(userName)
- str2 = ", Ranks: "
- str3 = " US: " + str(American1v1rank)
- str4 = " || WM: " + str(Wehrmacht1v1rank)
- str5 = " || PE: " + str(PE1v1rank)
- str6 = " || CW: " + str(CommonWealth1v1rank)
- catString = str1 + str2 + str3 +str6 + str4 + str5
- return catString
- except Exception as e:
- print("An Error occurred")
- print(e)
- class HandleCOHlogFile:
- def __init__(self):
- self.logPath = "C:\\Users\\Django\\Documents\\My Games\\Company of Heroes Relaunch\\warnings.log"
- self.data = []
- def loadLog(self):
- print("In loadLog")
- try:
- with open(self.logPath, encoding='ISO-8859-1') as file:
- content = file.readlines()
- for item in content:
- if ("match started") in item.lower():
- print (item)
- steamNumber = self.find_between(item, "steam/", "]")
- ranking = self.find_between(item, "ranking =","\n")
- if (steamNumber == "76561198831907666"):
- pass
- else:
- steamURL = "http://steamcommunity.com/profiles/" + str(steamNumber)
- self.data.append("")#("Steam profile " + str(steamURL))
- myStatRequest = StatsRequest()
- try:
- statNumber = int(steamNumber)
- self.data.append(str(myStatRequest.returnStats(statNumber)))
- except ValueError:
- print ("got a value error")
- if self.data:
- return self.data
- else:
- return None
- except Exception as e:
- print ("Problem in loadlog")
- print (str(e))
- def find_between(self, s, first, last ):
- try:
- start = s.index( first ) + len( first )
- end = s.index( last, start )
- return s[start:end]
- except ValueError:
- return ""
- myIRC = IRCClient()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement