locationbot.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. #!/usr/bin/env python
  2. # Location Bot
  3. #
  4. # Douglas Thrift
  5. #
  6. # $Id$
  7. from ConfigParser import NoOptionError, SafeConfigParser
  8. from datetime import datetime, timedelta
  9. import geojson
  10. import getpass
  11. import ircbot
  12. import irclib
  13. import os
  14. import psycopg2
  15. import pytz
  16. import sys
  17. import time
  18. import threading
  19. import urllib, urllib2
  20. import warnings
  21. class LocationBot(ircbot.SingleServerIRCBot):
  22. def __init__(self, bot = None):
  23. config = SafeConfigParser({'hostname': ''})
  24. config.read('locationbot.ini')
  25. try:
  26. nick = config.sections()[0]
  27. except IndexError:
  28. sys.exit('No nick configured')
  29. servers = []
  30. try:
  31. for server in config.get(nick, 'servers').split():
  32. server = server.split(':', 2)
  33. if len(server) == 1:
  34. servers.append((server[0], 6667))
  35. else:
  36. host = server[0]
  37. port = int(server[1])
  38. ssl = server[1].startswith('+')
  39. if len(server) == 3:
  40. servers.append((host, port, ssl, server[2]))
  41. else:
  42. servers.append((host, port, ssl))
  43. self.__admins = config.get(nick, 'admins').split()
  44. self.__channels = config.get(nick, 'channels').split()
  45. self.__dsn = config.get(nick, 'dsn')
  46. self.__hostname = config.get(nick, 'hostname')
  47. except NoOptionError, error:
  48. sys.exit(error)
  49. ircbot.SingleServerIRCBot.__init__(self, servers, nick, 'Location Bot')
  50. self.__latitude_timer_lock = threading.Lock()
  51. self.__latitude_timer = None
  52. self.__locations_lock = threading.Lock()
  53. if bot is None:
  54. self.__locations = []
  55. self.__logins = {}
  56. self.__reloading = False
  57. else:
  58. irclibobj = self.ircobj.connections[0].irclibobj
  59. self.ircobj.connections[0] = bot.ircobj.connections[0]
  60. self.ircobj.connections[0].irclibobj = irclibobj
  61. self.channels = bot.channels
  62. self.__locations = bot.__locations
  63. self.__logins = bot.__logins
  64. self.__reloading = True
  65. def __admin(self, nickmask):
  66. return _or(lambda admin: irclib.mask_matches(nickmask, admin), self.__admins)
  67. def __channel(self, nick, exclude = None):
  68. if exclude is not None:
  69. exclude = irclib.irc_lower(exclude)
  70. channels = map(lambda channel: channel[1], filter(lambda channel: irclib.irc_lower(channel[0]) == exclude, self.channels))
  71. else:
  72. channels = self.channels.values()
  73. return _or(lambda channel: channel.has_user(nick), channels)
  74. def __help(self, connection, nick, admin, login, arguments):
  75. command = arguments.split(None, 1)[0].lstrip('!') if arguments else None
  76. commands = {
  77. 'help': ('[command]', 'show this help message'),
  78. 'login': ('[nick] [secret]', 'log in as nick with secret or using masks'),
  79. 'register': ('[nick] secret', 'register as nick with secret'),
  80. 'status': ('[nick]', 'show where everybody or a nick is'),
  81. }
  82. if login:
  83. commands.update({
  84. 'latitude': ('[id]', 'shortcut for !set latitude [id]'),
  85. 'logout': ('', 'log out as nick'),
  86. 'set': ('[key [value]]', 'display or set variables'),
  87. 'unset': ('key', 'unset a variable'),
  88. })
  89. if admin:
  90. commands.update({
  91. 'reload': ('', 'reload with more up to date code'),
  92. 'restart': ('', 'quit and join running more up to date code'),
  93. 'say': ('nick|channel message', 'say message to nick or channel'),
  94. 'who': ('', 'show who is logged in'),
  95. })
  96. connection.privmsg(nick, 'Command Arguments Description')
  97. def help(command, arguments, description):
  98. connection.privmsg(nick, '!%-10s %-23s %s' % (command, arguments, description))
  99. if command in commands:
  100. help(command, *commands[command])
  101. else:
  102. for command, (arguments, description) in sorted(commands.iteritems()):
  103. help(command, arguments, description)
  104. def __latitude(self):
  105. now = datetime.utcnow()
  106. try:
  107. while now < self.__latitude_next:
  108. time.sleep((self.__latitude_next - now).seconds)
  109. now = datetime.utcnow()
  110. except AttributeError:
  111. pass
  112. self.__latitude_next = now.replace(minute = now.minute - now.minute % 5, second = 0, microsecond = 0) + timedelta(minutes = 5)
  113. db = psycopg2.connect(self.__dsn)
  114. cursor = db.cursor()
  115. cursor.execute('select nick, channels, location, latitude from locationbot.nick where latitude is not null order by latitude')
  116. locations = {}
  117. for nick, channels, old_location, latitude in cursor.fetchall():
  118. new_location = locations.get(latitude)
  119. if latitude not in locations:
  120. url = 'http://www.google.com/latitude/apps/badge/api?' + urllib.urlencode({'user': latitude, 'type': 'json'})
  121. try:
  122. response = urllib2.urlopen(url)
  123. except urllib2.URLError, error:
  124. print error
  125. continue
  126. try:
  127. geo = geojson.load(response, object_hook = geojson.GeoJSON.to_instance)
  128. except (TypeError, ValueError), error:
  129. print error
  130. continue
  131. if len(geo.features):
  132. properties = geo.features[0].properties
  133. new_location = properties['reverseGeocode']
  134. locations[latitude] = new_location
  135. updated = datetime.fromtimestamp(properties['timeStamp'], pytz.utc)
  136. cursor.execute('update locationbot.nick set location = %s, updated = %s where latitude = %s', (new_location, updated, latitude))
  137. db.commit()
  138. if channels and new_location and new_location != old_location:
  139. with self.__locations_lock:
  140. for channel in frozenset(channels).intersection(self.__channels):
  141. self.__locations.append((nick, channel, locations[latitude]))
  142. with self.__latitude_timer_lock:
  143. self.__latitude_timer = threading.Timer((self.__latitude_next - datetime.utcnow()).seconds, self.__latitude)
  144. self.__latitude_timer.start()
  145. def __login(self, connection, nickmask, nick, arguments = ''):
  146. login = nick
  147. if connection is not None:
  148. arguments = arguments.split(None, 1)
  149. if len(arguments) == 2:
  150. login, secret = arguments
  151. elif len(arguments) == 1:
  152. secret = arguments[0]
  153. else:
  154. secret = None
  155. else:
  156. secret = None
  157. if nick in self.__logins:
  158. login = self.__logins[nick][0]
  159. if connection is not None:
  160. return connection.privmsg(nick, 'already logged in as "%s"' % login)
  161. return login
  162. db = psycopg2.connect(self.__dsn)
  163. cursor = db.cursor()
  164. def success():
  165. connection.privmsg(nick, 'successfully logged in as "%s"' % login)
  166. if secret is not None:
  167. cursor.execute('select true from locationbot.nick where nick = %s and secret = md5(%s)', (login, secret))
  168. if cursor.rowcount == 1:
  169. self.__logins[nick] = (login, nickmask)
  170. return success()
  171. cursor.execute('select nick, masks from locationbot.nick where nick in (%s, %s)', (login, secret if len(arguments) != 2 else None))
  172. for login, masks in cursor.fetchall():
  173. if _or(lambda mask: irclib.mask_matches(nickmask, mask), masks):
  174. self.__logins[nick] = (login, nickmask)
  175. return success() if connection else login
  176. if connection is not None:
  177. return connection.privmsg(nick, 'failed to log in as "%s"' % login)
  178. return False
  179. def __logout(self, connection, nick):
  180. connection.privmsg(nick, 'logged out as "%s"' % self.__logins.pop(nick)[0])
  181. def __reload(self, connection, nick):
  182. self.__reloading = True
  183. connection.privmsg(nick, 'reloading')
  184. def __restart(self, connection):
  185. connection.disconnect('Restarting')
  186. os.execvp(sys.argv[0], sys.argv)
  187. def __say(self, connection, nick, arguments):
  188. try:
  189. nick_channel, message = arguments.split(None, 1)
  190. except ValueError:
  191. return self.__help(connection, nick, True, False, 'say')
  192. if irclib.is_channel(nick_channel):
  193. if nick_channel not in self.channels:
  194. return connection.privmsg(nick, 'not in channel ("%s")' % nick_channel)
  195. elif not self.__channel(nick_channel):
  196. return connection.privmsg(nick, 'nick ("%s") not in channel(s)' % nick_channel)
  197. elif nick_channel == connection.get_nickname():
  198. return connection.privmsg(nick, 'nice try')
  199. connection.privmsg(nick_channel, message)
  200. def __unknown(self, connection, nick, command):
  201. connection.privmsg(nick, 'unknown command ("!%s"); try "!help"' % command)
  202. def __who(self, connection, nick):
  203. connection.privmsg(nick, 'Login Nick Nick Mask')
  204. for login in sorted(self.__logins.values()):
  205. connection.privmsg(nick, '%-31s %s' % login)
  206. def _connect(self):
  207. password = None
  208. if len(self.server_list[0]) != 2:
  209. ssl = self.server_list[0][2]
  210. if len(self.server_list[0]) == 4:
  211. password = self.server_list[0][3]
  212. try:
  213. with warnings.catch_warnings():
  214. warnings.filterwarnings('ignore', r'socket\.ssl\(\) is deprecated\. Use ssl\.wrap_socket\(\) instead\.', DeprecationWarning)
  215. self.connect(self.server_list[0][0], self.server_list[0][1], self._nickname, password, getpass.getuser(), self._realname, localaddress = self.__hostname, ssl = ssl)
  216. except irclib.ServerConnectionError:
  217. pass
  218. def get_version(self):
  219. return 'locationbot ' + sys.platform
  220. def on_kick(self, connection, event):
  221. nick = event.arguments()[0]
  222. if not self.__channel(nick, event.target()):
  223. self.__logins.pop(nick, None)
  224. def on_nick(self, connection, event):
  225. nickmask = event.source()
  226. login = self.__logins.pop(irclib.nm_to_n(nickmask), (None,))[0]
  227. if login is not None:
  228. nick = event.target()
  229. self.__logins[nick] = (login, nick + '!' + nm_to_uh(nickmask))
  230. def on_nicknameinuse(self, connection, event):
  231. connection.nick(connection.get_nickname() + '_')
  232. def on_part(self, connection, event):
  233. nick = irclib.nm_to_n(event.source())
  234. if not self.__channel(nick, event.target()):
  235. self.__logins.pop(nick, None)
  236. def on_privmsg(self, connection, event):
  237. nickmask = event.source()
  238. nick = irclib.nm_to_n(nickmask)
  239. admin = self.__admin(nickmask)
  240. if not admin and not self.__channel(nick):
  241. return
  242. login = self.__login(None, nickmask, nick)
  243. try:
  244. command, arguments = event.arguments()[0].split(None, 1)
  245. except ValueError:
  246. command = event.arguments()[0].strip()
  247. arguments = ''
  248. if command.startswith('!'):
  249. command = command[1:]
  250. if command == 'help':
  251. self.__help(connection, nick, admin, login, arguments)
  252. elif command == 'login':
  253. self.__login(connection, nickmask, nick, arguments)
  254. elif login and command == 'logout':
  255. self.__logout(connection, nick)
  256. elif admin and command == 'reload':
  257. self.__reload(connection, nick)
  258. elif admin and command == 'restart':
  259. self.__restart(connection)
  260. elif admin and command == 'say':
  261. self.__say(connection, nick, arguments)
  262. elif admin and command == 'who':
  263. self.__who(connection, nick)
  264. else:
  265. self.__unknown(connection, nick, command)
  266. elif event.eventtype() == 'privmsg':
  267. self.__unknown(connection, nick, command)
  268. def on_quit(self, connection, event):
  269. self.__logins.pop(irclib.nm_to_n(event.source()), None)
  270. def on_welcome(self, connection, event):
  271. for channel in self.__channels:
  272. connection.join(channel)
  273. def start(self):
  274. self.__latitude_thread = threading.Thread(None, self.__latitude)
  275. self.__latitude_thread.daemon = True
  276. self.__latitude_thread.start()
  277. if not self.__reloading:
  278. self._connect()
  279. else:
  280. self.__reloading = False
  281. while not self.__reloading:
  282. if self.__locations_lock.acquire(False):
  283. if self.__locations and sorted(self.__channels) == sorted(self.channels.keys()):
  284. for nick, channel, location in self.__locations:
  285. self.connection.notice(channel, '%s is in %s' % (nick, location))
  286. self.__locations = []
  287. self.__locations_lock.release()
  288. self.ircobj.process_once(0.2)
  289. self.__latitude_thread.join()
  290. with self.__latitude_timer_lock:
  291. if self.__latitude_timer is not None:
  292. self.__latitude_timer.cancel()
  293. self.__latitude_timer.join()
  294. def _or(function, values):
  295. return reduce(lambda a, b: a or b, map(function, values) if values else [False])
  296. if __name__ == '__main__':
  297. import locationbot
  298. bot = None
  299. try:
  300. while True:
  301. bot = reload(locationbot).LocationBot(bot)
  302. bot.start()
  303. except KeyboardInterrupt:
  304. bot.connection.disconnect('Oh no!')