botbrain.py 4.6 KB

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