locationbot.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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.connection = bot.connection
  63. self.__locations = bot.__locations
  64. self.__logins = bot.__logins
  65. self.__reloading = True
  66. self.__variables = frozenset(['nick', 'secret', 'masks', 'channels', 'timezone', 'location', 'latitude'])
  67. self.__unsetable = self.__variables.difference(['nick', 'secret'])
  68. def __admin(self, nickmask):
  69. return _or(lambda admin: irclib.mask_matches(nickmask, admin), self.__admins)
  70. def __db(self):
  71. db = psycopg2.connect(self.__dsn)
  72. return db, db.cursor()
  73. def __channel(self, nick, exclude = None):
  74. if exclude is not None:
  75. exclude = irclib.irc_lower(exclude)
  76. channels = map(lambda channel: channel[1], filter(lambda channel: irclib.irc_lower(channel[0]) == exclude, self.channels))
  77. else:
  78. channels = self.channels.values()
  79. return _or(lambda channel: channel.has_user(nick), channels)
  80. def __help(self, connection, nick, admin, login, arguments):
  81. command = arguments.split(None, 1)[0].lstrip('!') if arguments else None
  82. commands = {
  83. 'help': ('[command]', 'show this help message'),
  84. 'login': ('[nick] [secret]', 'log in as nick with secret or using masks'),
  85. 'register': ('[nick] secret', 'register as nick with secret'),
  86. 'status': ('[nick]', 'show where everybody or a nick is'),
  87. }
  88. if login:
  89. commands.update({
  90. 'logout': ('', 'log out as nick'),
  91. 'set': ('[key [value]]', 'display or set variables'),
  92. 'unset': ('key', 'unset a variable'),
  93. })
  94. if admin:
  95. commands.update({
  96. 'reload': ('', 'reload with more up to date code'),
  97. 'restart': ('', 'quit and join running more up to date code'),
  98. 'say': ('nick|channel message', 'say message to nick or channel'),
  99. 'who': ('', 'show who is logged in'),
  100. })
  101. connection.privmsg(nick, 'Command Arguments Description')
  102. def help(command, arguments, description):
  103. connection.privmsg(nick, '!%-10s %-23s %s' % (command, arguments, description))
  104. if command in commands:
  105. help(command, *commands[command])
  106. else:
  107. for command, (arguments, description) in sorted(commands.iteritems()):
  108. help(command, arguments, description)
  109. def __latitude(self):
  110. now = datetime.utcnow()
  111. try:
  112. while now < self.__latitude_next:
  113. time.sleep((self.__latitude_next - now).seconds)
  114. now = datetime.utcnow()
  115. except AttributeError:
  116. pass
  117. self.__latitude_next = now.replace(minute = now.minute - now.minute % 5, second = 0, microsecond = 0) + timedelta(minutes = 5)
  118. db, cursor = self.__db()
  119. cursor.execute('select nick, channels, location, latitude from locationbot.nick where latitude is not null order by latitude')
  120. locations = {}
  121. for nick, channels, old_location, latitude in cursor.fetchall():
  122. new_location = locations.get(latitude)
  123. if latitude not in locations:
  124. url = 'http://www.google.com/latitude/apps/badge/api?' + urllib.urlencode({'user': latitude, 'type': 'json'})
  125. try:
  126. response = urllib2.urlopen(url)
  127. except urllib2.URLError, error:
  128. print error
  129. continue
  130. try:
  131. geo = geojson.load(response, object_hook = geojson.GeoJSON.to_instance)
  132. except (TypeError, ValueError), error:
  133. print error
  134. continue
  135. if len(geo.features):
  136. properties = geo.features[0].properties
  137. new_location = properties['reverseGeocode']
  138. locations[latitude] = new_location
  139. updated = datetime.fromtimestamp(properties['timeStamp'], pytz.utc)
  140. cursor.execute('update locationbot.nick set location = %s, updated = %s where latitude = %s', (new_location, updated, latitude))
  141. db.commit()
  142. if channels and new_location and new_location != old_location:
  143. with self.__locations_lock:
  144. for channel in frozenset(channels).intersection(self.__channels):
  145. self.__locations.append((nick, channel, locations[latitude]))
  146. with self.__latitude_timer_lock:
  147. self.__latitude_timer = threading.Timer((self.__latitude_next - datetime.utcnow()).seconds, self.__latitude)
  148. self.__latitude_timer.start()
  149. def __login(self, connection, nickmask, nick, arguments = ''):
  150. login = nick
  151. if connection is not None:
  152. arguments = arguments.split(None, 1)
  153. if len(arguments) == 2:
  154. login, secret = arguments
  155. elif len(arguments) == 1:
  156. secret = arguments[0]
  157. else:
  158. secret = None
  159. else:
  160. secret = None
  161. if nick in self.__logins:
  162. login = self.__logins[nick][0]
  163. if connection is not None:
  164. return connection.privmsg(nick, 'already logged in as "%s"' % login)
  165. return login
  166. db, cursor = self.__db()
  167. def success():
  168. connection.privmsg(nick, 'successfully logged in as "%s"' % login)
  169. if secret is not None:
  170. cursor.execute('select true from locationbot.nick where nick = %s and secret = md5(%s)', (login, secret))
  171. if cursor.rowcount == 1:
  172. self.__logins[nick] = (login, nickmask)
  173. return success()
  174. cursor.execute('select nick, masks from locationbot.nick where nick in (%s, %s)', (login, secret if len(arguments) != 2 else None))
  175. for login, masks in cursor.fetchall():
  176. if _or(lambda mask: irclib.mask_matches(nickmask, mask), masks):
  177. self.__logins[nick] = (login, nickmask)
  178. return success() if connection else login
  179. if connection is not None:
  180. return connection.privmsg(nick, 'failed to log in as "%s"' % login)
  181. def __logout(self, connection, nick):
  182. connection.privmsg(nick, 'logged out as "%s"' % self.__logins.pop(nick)[0])
  183. def __reload(self, connection, nick):
  184. self.__reloading = True
  185. connection.privmsg(nick, 'reloading')
  186. def __restart(self, connection):
  187. connection.disconnect('restarting')
  188. os.execvp(sys.argv[0], sys.argv)
  189. def __say(self, connection, nick, arguments):
  190. try:
  191. nick_channel, message = arguments.split(None, 1)
  192. except ValueError:
  193. return self.__help(connection, nick, True, False, 'say')
  194. if irclib.is_channel(nick_channel):
  195. if nick_channel not in self.channels:
  196. return connection.privmsg(nick, 'not in channel ("%s")' % nick_channel)
  197. elif not self.__channel(nick_channel):
  198. return connection.privmsg(nick, 'nick ("%s") not in channel(s)' % nick_channel)
  199. elif nick_channel == connection.get_nickname():
  200. return connection.privmsg(nick, 'nice try')
  201. connection.privmsg(nick_channel, message)
  202. def __status(self, connection, nick, login, arguments):
  203. _nick = arguments.split(None, 1)[0] if arguments else None
  204. db, cursor = self.__db()
  205. cursor.execute('select nick, location, updated from locationbot.nick where ' + ('nick = %s and ' if _nick is not None else '') + 'location is not null order by updated desc', (_nick,))
  206. if cursor.rowcount == 0:
  207. return connection.privmsg(nick, 'no location information for ' + ('"%s"' % _nick if _nick is not None else 'anybody'))
  208. locations = cursor.fetchall()
  209. if login is not None:
  210. cursor.execute('select timezone from locationbot.nick where nick = %s and timezone is not null', (login,))
  211. timezone = pytz.timezone(cursor.fetchone()[0]) if cursor.rowcount == 1 else pytz.utc
  212. else:
  213. timezone = pytz.utc
  214. connection.privmsg(nick, 'Nick Location When')
  215. for _nick, location, updated in locations:
  216. connection.privmsg(nick, '%-23s %-36s %s' % (_nick, location, timezone.normalize(updated.astimezone(timezone)).strftime('%Y-%m-%d %H:%M %Z')))
  217. def __unknown(self, connection, nick, command):
  218. connection.privmsg(nick, 'unknown command ("!%s"); try "!help"' % command)
  219. def __unknown_variable(self, connection, nick, variable):
  220. connection.privmsg(nick, 'unknown variable ("%s")' % variable)
  221. def __unset(self, connection, nick, login, arguments):
  222. try:
  223. variable = arguments.split(None, 1)[0]
  224. except IndexError:
  225. return self.__help(connection, nick, False, login, 'unset')
  226. if variable not in self.__unsetable:
  227. if variable in self.__variables:
  228. return connection.privmsg(nick, 'variable ("%s") is not unsetable' % variable)
  229. return self.__unknown_variable(connection, nick, variable)
  230. db, cursor = self.__db()
  231. cursor.execute('update locationbot.nick set ' + variable + ' = null' + (', updated = null' if variable == 'location' else '') + ' where nick = %s and ' + variable + ' is not null', (login,))
  232. db.commit()
  233. connection.privmsg(nick, 'variable ("' + variable + '") ' + ('' if cursor.rowcount == 1 else 'already ') + 'unset')
  234. def __who(self, connection, nick):
  235. connection.privmsg(nick, 'Login Nick Nick Mask')
  236. for login in sorted(self.__logins.values()):
  237. connection.privmsg(nick, '%-23s %s' % login)
  238. def _connect(self):
  239. password = None
  240. if len(self.server_list[0]) != 2:
  241. ssl = self.server_list[0][2]
  242. if len(self.server_list[0]) == 4:
  243. password = self.server_list[0][3]
  244. try:
  245. with warnings.catch_warnings():
  246. warnings.filterwarnings('ignore', r'socket\.ssl\(\) is deprecated\. Use ssl\.wrap_socket\(\) instead\.', DeprecationWarning)
  247. self.connect(self.server_list[0][0], self.server_list[0][1], self._nickname, password, getpass.getuser(), self._realname, localaddress = self.__hostname, ssl = ssl)
  248. except irclib.ServerConnectionError:
  249. pass
  250. def get_version(self):
  251. return 'locationbot ' + sys.platform
  252. def on_kick(self, connection, event):
  253. nick = event.arguments()[0]
  254. if not self.__channel(nick, event.target()):
  255. self.__logins.pop(nick, None)
  256. def on_nick(self, connection, event):
  257. nickmask = event.source()
  258. login = self.__logins.pop(irclib.nm_to_n(nickmask), (None,))[0]
  259. if login is not None:
  260. nick = event.target()
  261. self.__logins[nick] = (login, nick + '!' + nm_to_uh(nickmask))
  262. def on_nicknameinuse(self, connection, event):
  263. connection.nick(connection.get_nickname() + '_')
  264. def on_part(self, connection, event):
  265. nick = irclib.nm_to_n(event.source())
  266. if not self.__channel(nick, event.target()):
  267. self.__logins.pop(nick, None)
  268. def on_privmsg(self, connection, event):
  269. nickmask = event.source()
  270. nick = irclib.nm_to_n(nickmask)
  271. admin = self.__admin(nickmask)
  272. if not admin and not self.__channel(nick):
  273. return
  274. login = self.__login(None, nickmask, nick)
  275. try:
  276. command, arguments = event.arguments()[0].split(None, 1)
  277. except ValueError:
  278. command = event.arguments()[0].strip()
  279. arguments = ''
  280. if command.startswith('!'):
  281. command = command[1:]
  282. if command == 'help':
  283. self.__help(connection, nick, admin, login, arguments)
  284. elif command == 'login':
  285. self.__login(connection, nickmask, nick, arguments)
  286. elif command == 'status':
  287. self.__status(connection, nick, login, arguments)
  288. elif login and command == 'logout':
  289. self.__logout(connection, nick)
  290. elif login and command == 'unset':
  291. self.__unset(connection, nick, login, arguments)
  292. elif admin and command == 'reload':
  293. self.__reload(connection, nick)
  294. elif admin and command == 'restart':
  295. self.__restart(connection)
  296. elif admin and command == 'say':
  297. self.__say(connection, nick, arguments)
  298. elif admin and command == 'who':
  299. self.__who(connection, nick)
  300. else:
  301. self.__unknown(connection, nick, command)
  302. elif event.eventtype() == 'privmsg':
  303. self.__unknown(connection, nick, command)
  304. def on_quit(self, connection, event):
  305. self.__logins.pop(irclib.nm_to_n(event.source()), None)
  306. def on_welcome(self, connection, event):
  307. for channel in self.__channels:
  308. connection.join(channel)
  309. def start(self):
  310. self.__latitude_thread = threading.Thread(None, self.__latitude)
  311. self.__latitude_thread.daemon = True
  312. self.__latitude_thread.start()
  313. if not self.__reloading:
  314. self._connect()
  315. else:
  316. self.__reloading = False
  317. while not self.__reloading:
  318. if self.__locations_lock.acquire(False):
  319. if self.__locations and sorted(self.__channels) == sorted(self.channels.keys()):
  320. for nick, channel, location in self.__locations:
  321. self.connection.notice(channel, '%s is in %s' % (nick, location))
  322. self.__locations = []
  323. self.__locations_lock.release()
  324. self.ircobj.process_once(0.2)
  325. self.__latitude_thread.join()
  326. with self.__latitude_timer_lock:
  327. if self.__latitude_timer is not None:
  328. self.__latitude_timer.cancel()
  329. self.__latitude_timer.join()
  330. def _or(function, values):
  331. return reduce(lambda a, b: a or b, map(function, values) if values else [False])
  332. if __name__ == '__main__':
  333. import locationbot
  334. bot = None
  335. try:
  336. while True:
  337. bot = reload(locationbot).LocationBot(bot)
  338. bot.start()
  339. except KeyboardInterrupt:
  340. bot.connection.disconnect('oh no!')