Advertisement
Guest User

Untitled

a guest
Oct 14th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.94 KB | None | 0 0
  1. import time
  2. import re
  3. import socket
  4. import string
  5. import sys
  6. import threading
  7. import json # for loading json's for emoticons
  8. import urllib.request # more for loadings jsons from urls
  9. import collections # for deque
  10. from decimal import *
  11. import operator # for sorting dictionary by value
  12. from random import choice
  13. import os # to allow directory exists checking etc.
  14. import requests
  15. import pymysql
  16.  
  17.  
  18. #Because python floating point arthmatic is a nightmare
  19. TWOPLACES = Decimal(10) ** -2
  20.  
  21.  
  22. #Define Global Variables
  23. running = True;
  24. #Here are the message lines held until sent
  25. messageDeque = collections.deque()
  26. toSend = False
  27.  
  28.  
  29.  
  30.  
  31. class IRCClient:
  32.  
  33.  
  34. AdminUserName = "statementcoh" # This username will be able to use admin commands and bypass some limits.
  35. nick = 'statementbot' #alter this value with the username used to connect to IRC eg: "xcomreborn".
  36. channel = '#statementcoh' #alter this value with the channel name for your channel eg: "#xcomreborn".
  37. password = "oauth:e3cm63kjau8918hd3ewu26jgqkimzo" #alter this value with the password used to connect to IRC from the username above.
  38. server = 'irc.twitch.tv'
  39. port = 6667
  40.  
  41. #create IRC socket
  42. irc = socket.socket()
  43.  
  44. #irc send message buffer
  45. ircMessageBuffer = collections.deque()
  46.  
  47.  
  48.  
  49. def __init__(self):
  50. global running
  51.  
  52. # Start checking send buffer every 2 seconds.
  53. self.CheckIRCSendBufferEveryTwoSeconds() # only call this once.
  54.  
  55.  
  56. self.irc.connect((self.server, self.port))
  57.  
  58. #sends variables for connection to twitch chat
  59. self.irc.send(('PASS ' + self.password + '\r\n').encode("utf8"))
  60. self.irc.send(('USER ' + self.nick + '\r\n').encode("utf8"))
  61. self.irc.send(('NICK ' + self.nick + '\r\n').encode("utf8"))
  62. self.irc.send(('JOIN ' + self.channel + '\r\n').encode("utf8"))
  63.  
  64. #create readbuffer to hold strings from IRC
  65. readbuffer = ""
  66.  
  67. #self.SendPrivateMessageToIRC("/mod xcoinbetbot")
  68.  
  69. # This is the main loop
  70. while 1:
  71. readbuffer= readbuffer+self.irc.recv(1024).decode("utf-8")
  72. temp=str.split(readbuffer, "\n")
  73. readbuffer=temp.pop( )
  74.  
  75. for line in temp:
  76. line=str.rstrip(line)
  77. line=str.split(line)
  78. print (str(line).encode('utf8'))
  79.  
  80. if (len(line) >= 4) and ("PRIVMSG" == line[1]) and not ("jtv" in line[0]):
  81. #call function to handle user message
  82. self.UserMessage(line)
  83. if (len(line) >= 3) and ("JOIN" == line[1]):
  84. pass
  85. # call function to handle join messages
  86. #self.UserJoined(line)
  87. if (len(line) >= 5) and ("MODE" == line[1]):
  88. pass
  89. # call function to assign and remove OPs
  90. #self.AssignOPs(line)
  91. if(line[0]=="PING"):
  92. self.irc.send(("PONG %s\r\n" % line[0]).encode("utf8"))
  93.  
  94.  
  95.  
  96. def AssurePathExists(self, path):
  97. dir = os.path.dirname(path)
  98. if not os.path.exists(dir):
  99. os.makedirs(dir)
  100.  
  101.  
  102.  
  103. def CheckIRCSendBufferEveryTwoSeconds(self):
  104. global running
  105. if (running == True):
  106. threading.Timer(2.0, self.CheckIRCSendBufferEveryTwoSeconds).start()
  107. self.IRCSendCalledEveryTwoSeconds()
  108. # above is the send to IRC timer loop that runs every two seconds
  109.  
  110.  
  111.  
  112. def SendPrivateMessageToIRC(self, message):
  113. self.ircMessageBuffer.append(message) # removed this to stop message being sent to IRC
  114.  
  115.  
  116.  
  117. def IRCSendCalledEveryTwoSeconds(self):
  118. if (self.ircMessageBuffer):
  119. try:
  120. self.irc.send(("PRIVMSG " + self.channel + " :" + str(self.ircMessageBuffer.popleft()) + "\r\n").encode('utf8'))
  121. except Exception as e:
  122. print("IRC send error:")
  123. print(str(e))
  124. #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
  125.  
  126.  
  127.  
  128. def UserMessage(self, line):
  129. global running
  130. # Dissect out the useful parts of the raw data line into username and message and remove certain characters
  131. msgFirst = line[0]
  132. msgUserName = msgFirst[1:]
  133. msgUserName = msgUserName.split("!")[0]
  134. msgType = line [1];
  135. msgChannel = line [2]
  136. msgMessage = " ".join(line [3:])
  137. msgMessage = msgMessage[1:]
  138. messageString = str(msgUserName) + " : " + str(msgMessage)
  139. print (str(messageString).encode('utf8'))
  140.  
  141. #Check for UserCommands
  142. self.CheckForUserCommand(msgUserName, msgMessage)
  143.  
  144.  
  145. if (msgMessage == "exit") and (msgUserName == self.AdminUserName):
  146. running = False
  147. self.IRC.close()
  148. while (threading.active_count() > 1):
  149. pass
  150. sys.exit(1)
  151.  
  152. if (msgMessage == "!flak") or (msgMessage == "!Flak") or (msgMessage == "!FLAK"):
  153.  
  154. self.SendPrivateMessageToIRC(str("FLAK LOCATION Kreygasm Kreygasm"))
  155.  
  156. def CheckForUserCommand(self, userName, message):
  157. try:
  158. wordList = message.split()
  159. if (message.lower() == "opponent") or (message.lower() == "place your bets") or (message.lower() == "!opponent"):
  160. myLoadLog = HandleCOHlogFile()
  161. returnedList = []
  162. returnedList = myLoadLog.loadLog()
  163. if returnedList:
  164.  
  165. self.SendPrivateMessageToIRC(str(returnedList[-1]))
  166. self.SendPrivateMessageToIRC(str(returnedList[-2]))
  167.  
  168.  
  169.  
  170. except Exception as e:
  171. print("Error in check for user command")
  172. print(e)
  173.  
  174.  
  175.  
  176.  
  177.  
  178.  
  179.  
  180. # Here goes code outside the class
  181.  
  182. class StatsRequest:
  183. def __init__(self):
  184. pass
  185.  
  186.  
  187. def returnStatsName(self, name):
  188. try:
  189. print("got name : " + str(name))
  190. steamURL = "http://xcoins.co.uk/secreturl.php?steamUserID=" + str (name)
  191. scrapedData = urllib.request.urlopen(steamURL).read()
  192. scrapedData = str(scrapedData.decode('utf-8'))
  193.  
  194. steamNumber = self.find_between(scrapedData, "steamID64<h2 id=\"steamID64\">", "</h2>")
  195. return self.returnStats(steamNumber)
  196.  
  197. except Exception as e:
  198. print("error in returnstats name")
  199. print(e)
  200.  
  201.  
  202. def find_between(self, s, first, last ):
  203. try:
  204. start = s.index( first ) + len( first )
  205. end = s.index( last, start )
  206. return s[start:end]
  207. except ValueError:
  208. return ""
  209.  
  210.  
  211. def returnStats(self, statnumber):
  212. try:
  213. statString = "/steam/" + str(statnumber)
  214. response = urllib.request.urlopen('http://xcoins.co.uk/secreturl.php?steamUserID='+str(statnumber)).read()
  215. statdata = json.loads(response.decode('utf-8'))
  216. if (statdata['result']['message'] == "SUCCESS"):
  217. if statdata['statGroups'][0]['members'][0]['alias']:
  218. for item in statdata['statGroups']:
  219. for value in item['members']:
  220. if (value['name'] == statString):
  221. userName = value['alias']
  222. else:
  223. userName = ""
  224.  
  225. if statdata['leaderboardStats']:
  226. American1v1rank = ""
  227. Wehrmacht1v1rank = ""
  228. PE1v1rank = ""
  229. CommonWealth1v1rank = ""
  230. for idx, item in enumerate(statdata['leaderboardStats']):
  231. if item['leaderboard_id'] == 4:
  232. American1v1rank = item['rank']
  233. if American1v1rank == -1:
  234. American1v1rank = "N/A"
  235.  
  236. if item['leaderboard_id'] == 5:
  237. Wehrmacht1v1rank = item['rank']
  238. if Wehrmacht1v1rank == -1:
  239. Wehrmacht1v1rank = "N/A"
  240.  
  241. if item['leaderboard_id'] == 7:
  242. PE1v1rank = item['rank']
  243. if PE1v1rank == -1:
  244. PE1v1rank = "N/A"
  245.  
  246. if item['leaderboard_id'] == 6:
  247. CommonWealth1v1rank = item['rank']
  248. if CommonWealth1v1rank == -1:
  249. CommonWealth1v1rank = "N/A"
  250.  
  251.  
  252. str1 = "Username: " + str(userName)
  253. str2 = ", Ranks: "
  254. str3 = " US: " + str(American1v1rank)
  255. str4 = " || WM: " + str(Wehrmacht1v1rank)
  256. str5 = " || PE: " + str(PE1v1rank)
  257. str6 = " || CW: " + str(CommonWealth1v1rank)
  258. catString = str1 + str2 + str3 +str6 + str4 + str5
  259.  
  260. return catString
  261.  
  262.  
  263. except Exception as e:
  264. print("An Error occurred")
  265. print(e)
  266.  
  267.  
  268.  
  269. class HandleCOHlogFile:
  270.  
  271.  
  272. def __init__(self):
  273. self.logPath = "C:\\Users\\Django\\Documents\\My Games\\Company of Heroes Relaunch\\warnings.log"
  274. self.data = []
  275.  
  276. def loadLog(self):
  277. print("In loadLog")
  278. try:
  279. with open(self.logPath, encoding='ISO-8859-1') as file:
  280. content = file.readlines()
  281.  
  282.  
  283. for item in content:
  284. if ("match started") in item.lower():
  285. print (item)
  286. steamNumber = self.find_between(item, "steam/", "]")
  287. ranking = self.find_between(item, "ranking =","\n")
  288. if (steamNumber == "76561198831907666"):
  289. pass
  290. else:
  291. steamURL = "http://steamcommunity.com/profiles/" + str(steamNumber)
  292. self.data.append("")#("Steam profile " + str(steamURL))
  293.  
  294. myStatRequest = StatsRequest()
  295. try:
  296. statNumber = int(steamNumber)
  297. self.data.append(str(myStatRequest.returnStats(statNumber)))
  298. except ValueError:
  299. print ("got a value error")
  300.  
  301.  
  302. if self.data:
  303. return self.data
  304. else:
  305. return None
  306.  
  307. except Exception as e:
  308. print ("Problem in loadlog")
  309. print (str(e))
  310.  
  311.  
  312. def find_between(self, s, first, last ):
  313. try:
  314. start = s.index( first ) + len( first )
  315. end = s.index( last, start )
  316. return s[start:end]
  317. except ValueError:
  318. return ""
  319.  
  320.  
  321.  
  322. myIRC = IRCClient()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement