botbrain.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. from collections import defaultdict
  2. import webwriter
  3. #import bf3api
  4. import time
  5. import logger
  6. import datetime
  7. import battlelog
  8. import urllib2
  9. import json
  10. from urlparse import urlparse, parse_qsl
  11. import re
  12. from xml.dom.minidom import parseString
  13. import db
  14. from datetime import datetime, timedelta
  15. import sys
  16. import os
  17. #api = bf3api.API(None, '360')
  18. #
  19. #bf3players = {'tarehart': ('tarehart', '360'),
  20. # #'hlmtre': ('hellmitre', '360'),
  21. # 'willfro': ('fro4thought', '360'),
  22. # 'BoneKin': ('BoneKin', '360'),
  23. # 'Lucifer7': ('Lucifer7', '360'),
  24. # 'i7': ('Infinite Se7en', '360')}
  25. #def getbf3stats(message, platform):
  26. ## global bf3players
  27. # global api
  28. #
  29. # gt = message.split(None, 2)[2].strip() # grab gamertag off the end and strip it of terminators
  30. # command = message.split(None, 2)[1].strip()
  31. #
  32. # data = api.player(gt, platform, "clear,ranking")
  33. #
  34. # l = logger.Logger()
  35. # date = str(time.strftime("%Y-%m-%d %H:%M:%S"))
  36. # string = "getting " + command + " for player " + gt + " at " + date + '\n'
  37. # l.write(string)
  38. #
  39. # return formatbf3data(gt, command, data)
  40. #
  41. #def formatbf3data(player, command, data):
  42. # if data.status == "data":
  43. # if command == "spm":
  44. # return [player + "'s SPM: " + str(data.Stats.Ranking.Spm.v)[:6]]
  45. # elif command == "kdr":
  46. # return [player + "'s KDR: " + str(data.Stats.Ranking.Kdr.v)[:6]]
  47. # elif command == "wlr":
  48. # return [player + "'s WLR: " + str(data.Stats.Ranking.Wlr.v)[:6]]
  49. # elif command == "stats":
  50. # l = [player+"'s stats: ", "KDR: "+str(data.Stats.Ranking.Kdr.v)[:6], "SPM: "+str(data.Stats.Ranking.Spm.v)[:6], "Headshots/kill: "+str(data.Stats.Ranking.Hskillperc.v)[:6], "win/loss: "+str(data.Stats.Ranking.Wlr.v)[:6]]
  51. # return l
  52. #
  53. # elif data.status == "notfound":
  54. # return [player + " not found "]
  55. # else:
  56. # return ["ERROR"]
  57. #
  58. #
  59. #def getbf3last(message):
  60. # global api
  61. #
  62. # command = message.split(None, 2)[1].strip()
  63. # gt = message.split(None, 2)[2].strip() # grab gamertag off the end and strip it of terminators
  64. # fact = battlelog.getLatestGameFact(api, gt, command)
  65. # return gt + "'s latest " + command + " is " + str(fact)[:6]
  66. class BotBrain:
  67. BRAINDEBUG = False
  68. def __init__(self, microphone, bot=None):
  69. # get time for uptime start
  70. self.starttime = time.time()
  71. # get time for current length of uptime
  72. self.localtime = time.localtime()
  73. # get handle on output
  74. self.microphone = microphone
  75. self.bot = bot
  76. yth = dict()
  77. self.db = db.DB(self.bot)
  78. self.ww = webwriter.WebWriter()
  79. def _isAdmin(self, username):
  80. if self.bot.conf.getOwner(self.bot.network) == username:
  81. return True
  82. if self.db._isAdmin(username):
  83. return True
  84. return False
  85. def getMicrophone(self):
  86. return self.microphone
  87. def _updateSeen(self, user, statement, event):
  88. self.db.updateSeen(user, statement, event)
  89. def _insertImg(self, user, url, channel):
  90. self.db._insertImg(user, url, channel)
  91. def __bareSay(self, thing):
  92. self.microphone(thing + '\n')
  93. def say(self, channel, thing):
  94. try:
  95. s = thing.encode('utf-8', 'ignore')
  96. except UnicodeEncodeError as e:
  97. print e
  98. print thing
  99. return None
  100. except UnicodeDecodeError as d:
  101. print d
  102. print thing
  103. return None
  104. outstring = 'PRIVMSG ' + channel + ' :' + s.decode('utf-8','ignore') + '\n'
  105. self.microphone(outstring)
  106. def notice(self, channel, thing):
  107. self.microphone('NOTICE ' + channel + ' :' + str(thing) + '\n')
  108. # now implemented as a module
  109. #def _weather(self, channel, zipcode):
  110. # now implemented as a module
  111. # def _getyoutubetitle(self, line, channel):
  112. def _ctof(self, channel, c_temp):
  113. c = float(c_temp)
  114. f = (c * 1.8)+32
  115. self.say(channel, str(f) + "* F")
  116. def _ftoc(self, channel, f_temp):
  117. f = float(f_temp)
  118. c = (f - 32)*(.5555)
  119. self.say(channel, str(c) + "* C")
  120. def _uptime(self, channel):
  121. self.say(channel,"I've been up " +str(timedelta(seconds=time.time() - self.starttime))[:7] + ", since "+time.strftime("%a, %d %b %Y %H:%M:%S -0800", self.localtime))
  122. def _speak(self, user, target, message):
  123. if target.startswith("#"):
  124. self.say(target, message)
  125. else:
  126. target = "#" + target
  127. self.say(target, message)
  128. def _onstat(self, channel):
  129. self.say(channel, "Yep, I'm on. Idiot.")
  130. def _help(self, user):
  131. #self.microphone('PRIVMSG ' + user + ' :' + ".bf3 [spm, kdr, wlr, stats],\n")
  132. self.microphone('PRIVMSG ' + user + ' :' + ".uptime,\n")
  133. self.microphone('PRIVMSG ' + user + ' :' + ".imgs,\n")
  134. self.microphone('PRIVMSG ' + user + ' :' + ".ctof [celsius],\n")
  135. self.microphone('PRIVMSG ' + user + ' :' + ".ftoc [fahrenheit],\n")
  136. def _join(self, usr, message):
  137. if self._isAdmin(usr):
  138. if len(message.split()) is 3:
  139. channel = message.split()[1]
  140. extraArg = message.split()[-1]
  141. self.__bareSay("JOIN " + channel + " " + extraArg)
  142. else:
  143. channel = message.split()[-1] # second word (join #channel password)
  144. self.__bareSay("JOIN " + channel)
  145. def __quit(self, usr):
  146. if self._isAdmin(usr):
  147. self.__bareSay("QUIT :quitting")
  148. print "quitting as per " + usr
  149. sys.exit()
  150. def respond(self, usr, channel, message):
  151. # this bit is not a command
  152. if (".png" in message or ".gif" in message or ".jpg" in message or ".jpeg" in message) and ("http:" in message) or ("imgur.com" in message and "gallery" in message):
  153. url = re.search("(?P<url>https?://[^\s]+)", message).group("url")
  154. if url:
  155. self._insertImg(usr, url, channel)
  156. # this bit is
  157. if message.startswith(".join"):
  158. self._join(usr, message)
  159. if message.strip() == ".quit":
  160. self.__quit(usr)
  161. if message.startswith(".imgs"):
  162. self.ww._generate(self.db._getImgs())
  163. # hackish TODO
  164. if os.getenv('USER') == 'pybot':
  165. self.say(channel, "http://pybot.zero9f9.com/img/")
  166. else:
  167. self.say(channel, "http://zero9f9.com/~"+os.getenv('USER')+"/img/")
  168. #if message.startswith(".seen"):
  169. # self._seen(message.split()[-1], channel)
  170. if message.startswith(".ctof"):
  171. last = message.split()
  172. if last[-1] != "":
  173. self._ctof(channel, last[-1])
  174. if message.startswith(".ftoc"):
  175. last = message.split()
  176. if last[-1] != "":
  177. self._ftoc(channel, last[-1])
  178. if message.startswith(".help"):
  179. self._help(usr)
  180. #if message.startswith(".bf3pc"):
  181. # stats = getbf3stats(message, 'pc')
  182. # try:
  183. # for line in stats:
  184. # self.say(channel, line)
  185. # except TypeError:
  186. # self.say(channel, "WOOPS")
  187. #elif message.startswith(".bf3"):
  188. # stats = getbf3stats(message, '360')
  189. # try:
  190. # for line in stats:
  191. # self.say(channel, line)
  192. # except TypeError:
  193. # self.say(channel, "WOOPS")
  194. #if message.startswith(".lastbf3"):
  195. # last = getbf3last(message)
  196. # self.say(channel, last)
  197. #if message.startswith(".uptime"):
  198. # self._uptime(channel)
  199. if message.startswith(".onstat"):
  200. self._onstat(channel)
  201. if message.startswith(".speak"):
  202. tmp = message.split(" ",2)
  203. chnl = tmp[1]
  204. msg = tmp[2]
  205. self._speak(usr, chnl, msg)
  206. # utility function
  207. # def __prettyDate(self,time):
  208. # now = datetime.now()
  209. # if type(time) is int:
  210. # diff = now - datetime.fromtimestamp(time)
  211. # elif isinstance(time,datetime):
  212. # diff = now - time
  213. # elif not time:
  214. # diff = now - now
  215. # second_diff = diff.seconds
  216. # day_diff = diff.days
  217. #
  218. # if day_diff < 0:
  219. # return ''
  220. #
  221. # if day_diff == 0:
  222. # if second_diff < 10:
  223. # return "just now"
  224. # if second_diff < 60:
  225. # return str(second_diff) + " seconds ago"
  226. # if second_diff < 120:
  227. # return "a minute ago"
  228. # if second_diff < 3600:
  229. # return str( second_diff / 60 ) + " minutes ago"
  230. # if second_diff < 7200:
  231. # return "an hour ago"
  232. # if second_diff < 86400:
  233. # return str( second_diff / 3600 ) + " hours ago"
  234. # if day_diff == 1:
  235. # return "Yesterday"
  236. # if day_diff < 7:
  237. # return str(day_diff) + " days ago"
  238. # if day_diff < 31:
  239. # return str(day_diff/7) + " weeks ago"
  240. # if day_diff < 365:
  241. # return str(day_diff/30) + " months ago"
  242. # return str(day_diff/365) + " years ago"