botbrain.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. from collections import defaultdict
  2. import webwriter
  3. import time
  4. import logger
  5. import datetime
  6. import urllib2
  7. import json
  8. from urlparse import urlparse, parse_qsl
  9. import re
  10. from xml.dom.minidom import parseString
  11. import db
  12. from datetime import datetime, timedelta
  13. import sys
  14. import os
  15. class BotBrain:
  16. BRAINDEBUG = False
  17. def __init__(self, microphone, bot=None):
  18. # get time for uptime start
  19. self.starttime = time.time()
  20. # get time for current length of uptime
  21. self.localtime = time.localtime()
  22. # get handle on output
  23. self.microphone = microphone
  24. self.bot = bot
  25. yth = dict()
  26. self.db = db.DB(self.bot)
  27. self.ww = webwriter.WebWriter()
  28. def _isAdmin(self, username):
  29. if self.bot.conf.getOwner(self.bot.network) == username:
  30. return True
  31. if self.db._isAdmin(username):
  32. return True
  33. return False
  34. def getMicrophone(self):
  35. return self.microphone
  36. def _updateSeen(self, user, statement, event):
  37. self.db.updateSeen(user, statement, event)
  38. def _insertImg(self, user, url, channel):
  39. self.db._insertImg(user, url, channel)
  40. def __bareSay(self, thing):
  41. self.microphone(thing + '\n')
  42. def say(self, channel, thing):
  43. try:
  44. s = thing.encode('utf-8', 'ignore')
  45. except UnicodeEncodeError as e:
  46. print e
  47. print thing
  48. return None
  49. except UnicodeDecodeError as d:
  50. print d
  51. print thing
  52. return None
  53. outstring = 'PRIVMSG ' + channel + ' :' + s.decode('utf-8','ignore') + '\n'
  54. self.microphone(outstring)
  55. def notice(self, channel, thing):
  56. self.microphone('NOTICE ' + channel + ' :' + str(thing) + '\n')
  57. # now implemented as a module
  58. #def _weather(self, channel, zipcode):
  59. # now implemented as a module
  60. # def _getyoutubetitle(self, line, channel):
  61. def _ctof(self, channel, c_temp):
  62. c = float(c_temp)
  63. f = (c * 1.8)+32
  64. self.say(channel, str(f) + "* F")
  65. def _ftoc(self, channel, f_temp):
  66. f = float(f_temp)
  67. c = (f - 32)*(.5555)
  68. self.say(channel, str(c) + "* C")
  69. def _uptime(self, channel):
  70. 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))
  71. def _speak(self, user, target, message):
  72. if target.startswith("#"):
  73. self.say(target, message)
  74. else:
  75. target = "#" + target
  76. self.say(target, message)
  77. def _onstat(self, channel):
  78. self.say(channel, "Yep, I'm on. Idiot.")
  79. def _help(self, user):
  80. self.microphone('PRIVMSG ' + user + ' :' + ".uptime,\n")
  81. self.microphone('PRIVMSG ' + user + ' :' + ".imgs,\n")
  82. self.microphone('PRIVMSG ' + user + ' :' + ".ctof [celsius],\n")
  83. self.microphone('PRIVMSG ' + user + ' :' + ".ftoc [fahrenheit],\n")
  84. def _join(self, usr, message):
  85. if self._isAdmin(usr):
  86. if len(message.split()) is 3:
  87. channel = message.split()[1]
  88. extraArg = message.split()[-1]
  89. self.__bareSay("JOIN " + channel + " " + extraArg)
  90. else:
  91. channel = message.split()[-1] # second word (join #channel password)
  92. self.__bareSay("JOIN " + channel)
  93. def __quit(self, usr):
  94. if self._isAdmin(usr):
  95. self.__bareSay("QUIT :quitting")
  96. print "quitting as per " + usr
  97. sys.exit()
  98. def respond(self, usr, channel, message):
  99. # this bit is not a command
  100. 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):
  101. url = re.search("(?P<url>https?://[^\s]+)", message).group("url")
  102. if url:
  103. self._insertImg(usr, url, channel)
  104. # this bit is
  105. if message.startswith(".join"):
  106. self._join(usr, message)
  107. if message.strip() == ".quit":
  108. self.__quit(usr)
  109. if message.startswith(".imgs"):
  110. self.ww._generate(self.db._getImgs())
  111. # hackish TODO
  112. if os.getenv('USER') == 'pybot':
  113. self.say(channel, "http://pybot.zero9f9.com/img/")
  114. else:
  115. self.say(channel, "http://zero9f9.com/~"+os.getenv('USER')+"/img/")
  116. #if message.startswith(".seen"):
  117. # self._seen(message.split()[-1], channel)
  118. if message.startswith(".ctof"):
  119. last = message.split()
  120. if last[-1] != "":
  121. self._ctof(channel, last[-1])
  122. if message.startswith(".ftoc"):
  123. last = message.split()
  124. if last[-1] != "":
  125. self._ftoc(channel, last[-1])
  126. if message.startswith(".help"):
  127. self._help(usr)
  128. if message.startswith(".onstat"):
  129. self._onstat(channel)
  130. if message.startswith(".speak"):
  131. tmp = message.split(" ",2)
  132. chnl = tmp[1]
  133. msg = tmp[2]
  134. self._speak(usr, chnl, msg)