bot.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. #!/usr/bin/env python2
  2. #
  3. # see version.py for version
  4. # works with python 2.6.x and 2.7.x
  5. #
  6. import sys
  7. import socket
  8. import string
  9. import os
  10. import datetime
  11. import time
  12. import select
  13. import traceback
  14. import threading
  15. import inspect
  16. import argparse
  17. import botbrain
  18. from logger import Logger
  19. import confman
  20. from event import Event
  21. import util
  22. DEBUG = False
  23. RETRY_COUNTER = 0
  24. class Bot(threading.Thread):
  25. """
  26. bot instance. one bot gets instantiated per network, as an entirely distinct, sandboxed thread.
  27. handles the core IRC protocol stuff, and passing lines to defined events, which dispatch to their subscribed modules.
  28. """
  29. def __init__(self, conf=None, network=None, d=None):
  30. threading.Thread.__init__(self)
  31. self.HOST = None
  32. self.PORT = None
  33. self.REALNAME = None
  34. self.IDENT = None
  35. self.DEBUG = d
  36. self.brain = None
  37. self.network = network
  38. self.OFFLINE = False
  39. self.CONNECTED = False
  40. self.JOINED = False
  41. self.conf = conf
  42. self.pid = os.getpid()
  43. self.logger = Logger()
  44. # to be a dict of dicts
  45. self.command_function_map = dict()
  46. if self.conf.getDBType() == "sqlite":
  47. import lite
  48. self.db = lite.SqliteDB(self)
  49. else:
  50. import db
  51. self.db = db.DB(self)
  52. self.NICK = self.conf.getNick(self.network)
  53. self.logger.write(Logger.INFO, "\n", self.NICK)
  54. self.logger.write(Logger.INFO, " initializing bot, pid " + str(os.getpid()), self.NICK)
  55. # arbitrary key/value store for modules
  56. # they should be 'namespaced' like bot.mem_store.module_name
  57. self.mem_store = dict()
  58. self.CHANNELINIT = conf.getChannels(self.network)
  59. # this will be the socket
  60. self.s = None # each bot thread holds its own socket open to the network
  61. self.brain = botbrain.BotBrain(self.send, self)
  62. self.events_list = list()
  63. # define events here and add them to the events_list
  64. all_lines = Event("1__all_lines__")
  65. all_lines.define(".*")
  66. self.events_list.append(all_lines)
  67. implying = Event("__implying__")
  68. implying.define(">")
  69. #command = Event("__command__")
  70. # this is an example of passing in a regular expression to the event definition
  71. #command.define("fo.bar")
  72. lastfm = Event("__.lastfm__")
  73. lastfm.define(".lastfm")
  74. dance = Event("__.dance__")
  75. dance.define("\.dance")
  76. #unloads = Event("__module__")
  77. #unloads.define("^\.module")
  78. pimp = Event("__pimp__")
  79. pimp.define("\.pimp")
  80. bofh = Event("__.bofh__")
  81. bofh.define("\.bofh")
  82. #youtube = Event("__youtubes__")
  83. #youtube.define("youtube.com[\S]+")
  84. weather = Event("__.weather__")
  85. weather.define("\.weather")
  86. steam = Event("__.steam__")
  87. steam.define("\.steam")
  88. part = Event("__.part__")
  89. part.define("part")
  90. tell = Event("__privmsg__")
  91. tell.define("PRIVMSG")
  92. links = Event("__urls__")
  93. links.define("https?://*")
  94. # example
  95. # test = Event("__test__")
  96. # test.define(msg_definition="^\.test")
  97. # add your defined events here
  98. # tell your friends
  99. self.events_list.append(lastfm)
  100. self.events_list.append(dance)
  101. self.events_list.append(pimp)
  102. #self.events_list.append(youtube)
  103. self.events_list.append(bofh)
  104. self.events_list.append(weather)
  105. self.events_list.append(steam)
  106. self.events_list.append(part)
  107. self.events_list.append(tell)
  108. self.events_list.append(links)
  109. #self.events_list.append(unloads)
  110. # example
  111. # self.events_list.append(test)
  112. self.load_modules()
  113. self.logger.write(Logger.INFO, "bot initialized.", self.NICK)
  114. # conditionally subscribe to events list or add event to listing
  115. def register_event(self, event, module):
  116. """
  117. Allows for dynamic, asynchronous event creation. To be used by modules, mostly, to define their own events in their initialization.
  118. Prevents multiple of the same _type of event being registered.
  119. Args:
  120. event: an event object to be registered with the bot
  121. module: calling module; ensures the calling module can be subscribed to the event if it is not already.
  122. Returns:
  123. nothing.
  124. """
  125. for e in self.events_list:
  126. if e.definition == event.definition and e._type == event._type:
  127. # if our event is already in the listing, don't add it again, just have our module subscribe
  128. e.subscribe(module)
  129. return
  130. self.events_list.append(event)
  131. return
  132. def load_snippets(self):
  133. import imp
  134. snippets_path = self.modules_path + '/snippets'
  135. self.snippets_list = set()
  136. # load up snippets first
  137. for filename in os.listdir(snippets_path):
  138. name, ext = os.path.splitext(filename)
  139. try:
  140. if ext == ".py":
  141. # snippet is a module
  142. snippet = imp.load_source(name, snippets_path + '/' + filename)
  143. self.snippets_list.add(snippet)
  144. except Exception, e:
  145. print e
  146. print name, filename
  147. def set_snippets(self):
  148. """
  149. check each snippet for a function with a list of commands in it
  150. create a big ol list of dictionaries, commands mapping to the functions to call if the command is encountered
  151. """
  152. for obj in self.snippets_list:
  153. for k,v in inspect.getmembers(obj, inspect.isfunction):
  154. if inspect.isfunction(v) and hasattr(v, 'commands'):
  155. for c in v.commands:
  156. if not c in self.command_function_map:
  157. self.command_function_map[c] = dict()
  158. self.command_function_map[c] = v
  159. # utility function for loading modules; can be called by modules themselves
  160. def load_modules(self, specific=None):
  161. """
  162. Run through the ${bot_dir}/modules directory, dynamically instantiating each module as it goes.
  163. Args:
  164. specific: string name of module. if it is specified, the function attempts to load the named module.
  165. Returns:
  166. 1 if successful, 0 on failure. In keeping with the perverse reversal of UNIX programs and boolean values.
  167. """
  168. nonspecific = False
  169. found = False
  170. self.loaded_modules = list()
  171. modules_dir_list = list()
  172. tmp_list = list()
  173. self.modules_path = 'modules'
  174. modules_path = 'modules'
  175. self.autoload_path = 'modules/autoloads'
  176. autoload_path = 'modules/autoloads'
  177. # this is magic.
  178. import os, imp, json
  179. self.load_snippets()
  180. self.set_snippets()
  181. dir_list = os.listdir(modules_path)
  182. mods = {}
  183. autoloads = {}
  184. # load autoloads if it exists
  185. if os.path.isfile(autoload_path):
  186. self.logger.write(Logger.INFO, "Found autoloads file", self.NICK)
  187. try:
  188. autoloads = json.load(open(autoload_path))
  189. # logging
  190. for k in autoloads.keys():
  191. self.logger.write(Logger.INFO, "Autoloads found for network " + k, self.NICK)
  192. except IOError:
  193. self.logger.write(Logger.ERROR, "Could not load autoloads file.",self.NICK)
  194. # create dictionary of things in the modules directory to load
  195. for fname in dir_list:
  196. name, ext = os.path.splitext(fname)
  197. if specific is None:
  198. nonspecific = True
  199. # ignore compiled python and __init__ files.
  200. # choose to either load all .py files or, available, just ones specified in autoloads
  201. if self.network not in autoloads.keys(): # if autoload does not specify for this network
  202. if ext == '.py' and not name == '__init__':
  203. f, filename, descr = imp.find_module(name, [modules_path])
  204. mods[name] = imp.load_module(name, f, filename, descr)
  205. self.logger.write(Logger.INFO, " loaded " + name + " for network " + self.network, self.NICK)
  206. else: # follow autoload's direction
  207. if ext == '.py' and not name == '__init__':
  208. if name == 'module':
  209. f, filename, descr = imp.find_module(name, [modules_path])
  210. mods[name] = imp.load_module(name, f, filename, descr)
  211. self.logger.write(Logger.INFO, " loaded " + name + " for network " + self.network, self.NICK)
  212. elif ('include' in autoloads[self.network] and name in autoloads[self.network]['include']) or ('exclude' in autoloads[self.network] and name not in autoloads[self.network]['exclude']):
  213. f, filename, descr = imp.find_module(name, [modules_path])
  214. mods[name] = imp.load_module(name, f, filename, descr)
  215. self.logger.write(Logger.INFO, " loaded " + name + " for network " + self.network, self.NICK)
  216. else:
  217. if name == specific: # we're reloading only one module
  218. if ext != '.pyc': # ignore compiled
  219. f, filename, descr = imp.find_module(name, [modules_path])
  220. mods[name] = imp.load_module(name, f, filename, descr)
  221. found = True
  222. for k,v in mods.iteritems():
  223. for name in dir(v):
  224. obj = getattr(mods[k], name) # get the object from the namespace of 'mods'
  225. try:
  226. if inspect.isclass(obj): # it's a class definition, initialize it
  227. a = obj(self.events_list, self.send, self, self.say) # now we're passing in a reference to the calling bot
  228. if a not in self.loaded_modules: # don't add in multiple copies
  229. self.loaded_modules.append(a)
  230. except TypeError:
  231. pass
  232. if nonspecific is True or found is True:
  233. return 0
  234. else:
  235. return 1
  236. # end magic.
  237. def send(self, message):
  238. """
  239. Simply sends the specified message to the socket. Which should be our connected server.
  240. We parse our own lines, as well, in case we want an event triggered by something we say.
  241. If debug is True, we also print out a pretty thing to console.
  242. Args:
  243. message: string, sent directly and without manipulation (besides UTF-8ing it) to the server.
  244. """
  245. if self.OFFLINE:
  246. self.debug_print(util.bcolors.YELLOW + " >> " + util.bcolors.ENDC + self.getName() + ": " + message.encode('utf-8', 'ignore'))
  247. else:
  248. if self.DEBUG is True:
  249. self.logger.write(Logger.INFO, "DEBUGGING OUTPUT", self.NICK)
  250. self.logger.write(Logger.INFO, self.getName() + " " + message.encode('utf-8', 'ignore'), self.NICK)
  251. self.debug_print(util.bcolors.OKGREEN + ">> " + util.bcolors.ENDC + ": " + " " + message.encode('utf-8', 'ignore'))
  252. self.s.send(message.encode('utf-8', 'ignore'))
  253. target = message.split()[1]
  254. if target.startswith("#"):
  255. self.processline(':' + self.conf.getNick(self.network) + '!~' + self.conf.getNick(self.network) + '@fakehost.here ' + message.rstrip())
  256. def pong(self, response):
  257. """
  258. Keepalive heartbeat for IRC protocol. Until someone changes the IRC spec, don't modify this.
  259. """
  260. self.send('PONG ' + response + '\n')
  261. def processline(self, line):
  262. """
  263. Grab newline-delineated lines sent to us, and determine what to do with them.
  264. This function handles our initial low-level IRC stuff, as well; if we haven't joined, it waits for the MOTD message (or message indicating there isn't one) and then issues our own JOIN calls.
  265. Also immediately passes off PING messages to PONG.
  266. Args:
  267. line: string.
  268. """
  269. if self.DEBUG:
  270. import datetime
  271. if os.name == "posix": # because windows doesn't like the color codes.
  272. self.debug_print(util.bcolors.OKBLUE + "<< " + util.bcolors.ENDC + line)
  273. else:
  274. self.debug_print("<< " + ": " + line)
  275. message_number = line.split()[1]
  276. try:
  277. first_word = line.split(":", 2)[2].split()[0]
  278. channel = line.split()[2]
  279. except IndexError:
  280. pass
  281. else:
  282. if first_word in self.command_function_map:
  283. self.command_function_map[first_word](self, line, channel)
  284. try:
  285. for e in self.events_list:
  286. if e.matches(line):
  287. e.notifySubscribers(line)
  288. # don't bother going any further if it's a PING/PONG request
  289. if line.startswith("PING"):
  290. ping_response_line = line.split(":", 1)
  291. self.pong(ping_response_line[1])
  292. # pings we respond to directly. everything else...
  293. else:
  294. # patch contributed by github.com/thekanbo
  295. if self.JOINED is False and (message_number == "376" or message_number == "422"):
  296. # wait until we receive end of MOTD before joining, or until the server tells us the MOTD doesn't exist
  297. self.chan_list = self.conf.getChannels(self.network)
  298. for c in self.chan_list:
  299. self.send('JOIN '+c+' \n')
  300. self.JOINED = True
  301. line_array = line.split()
  302. user_and_mask = line_array[0][1:]
  303. usr = user_and_mask.split("!")[0]
  304. channel = line_array[2]
  305. try:
  306. message = line.split(":",2)[2]
  307. self.brain.respond(usr, channel, message)
  308. except IndexError:
  309. try:
  310. message = line.split(":",2)[1]
  311. self.brain.respond(usr, channel, message)
  312. except IndexError:
  313. print "index out of range.", line
  314. except Exception:
  315. print "Unexpected error:", sys.exc_info()[0]
  316. traceback.print_exc(file=sys.stdout)
  317. def worker(self, mock=False):
  318. """
  319. Open the socket, make the first incision^H^H connection and get us on the server.
  320. Handles keeping the connection alive; if we disconnect from the server, attempts to reconnect.
  321. Args:
  322. mock: boolean. If mock is true, don't loop forever -- mock is for testing.
  323. """
  324. self.HOST = self.network
  325. self.NICK = self.conf.getNick(self.network)
  326. # we have to cast it to an int, otherwise the connection fails silently and the entire process dies
  327. self.PORT = int(self.conf.getPort(self.network))
  328. self.IDENT = 'mypy'
  329. self.REALNAME = 's1ash'
  330. self.OWNER = self.conf.getOwner(self.network)
  331. # connect to server
  332. self.s = socket.socket()
  333. while not self.CONNECTED:
  334. try:
  335. # low level socket TCP/IP connection
  336. self.s.connect((self.HOST, self.PORT)) # force them into one argument
  337. self.CONNECTED = True
  338. self.logger.write(Logger.INFO, "Connected to " + self.network, self.NICK)
  339. if self.DEBUG:
  340. self.debug_print(util.bcolors.YELLOW + ">> " + util.bcolors.ENDC + "connected to " + self.network)
  341. except:
  342. if self.DEBUG:
  343. self.debug_print(util.bcolors.FAIL + ">> " + util.bcolors.ENDC + "Could not connect to " + self.HOST + " at " + str(self.PORT) + "! Retrying... ")
  344. self.logger.write(Logger.CRITICAL, "Could not connect to " + self.HOST + " at " + str(self.PORT) + "! Retrying...")
  345. time.sleep(1)
  346. self.worker()
  347. time.sleep(1)
  348. # core IRC protocol stuff
  349. self.s.send('NICK '+self.NICK+'\n')
  350. if self.DEBUG:
  351. self.debug_print(util.bcolors.YELLOW + ">> " + util.bcolors.ENDC + self.network + ': NICK ' + self.NICK + '\\n')
  352. self.s.send('USER '+self.IDENT+ ' 8 ' + ' bla : '+self.REALNAME+'\n') # yeah, don't delete this line
  353. if self.DEBUG:
  354. self.debug_print(util.bcolors.YELLOW + ">> " + util.bcolors.ENDC + self.network + ": USER " +self.IDENT+ ' 8 ' + ' bla : '+self.REALNAME+'\\n')
  355. time.sleep(3) # allow services to catch up
  356. self.s.send('PRIVMSG nickserv identify '+self.conf.getIRCPass(self.network)+'\n') # we're registered!
  357. if self.DEBUG:
  358. self.debug_print(util.bcolors.YELLOW + ">> " + util.bcolors.ENDC + self.network + ': PRIVMSG nickserv identify '+self.conf.getIRCPass(self.network)+'\\n')
  359. self.s.setblocking(1)
  360. read = ""
  361. timeout = 0
  362. # does not require a definition -- it will be invoked specifically when the bot notices it has been disconnected
  363. disconnect_event = Event("__.disconnection__")
  364. # if we're only running a test of connecting, and don't want to loop forever
  365. if mock:
  366. return
  367. # infinite loop to keep parsing lines
  368. while True:
  369. try:
  370. timeout += 1
  371. # if we haven't received anything for 120 seconds
  372. time_since = self.conf.getTimeout(self.network)
  373. if timeout > time_since:
  374. if self.DEBUG:
  375. self.debug_print("Disconnected! Retrying... ")
  376. disconnect_event.notifySubscribers("null")
  377. self.logger.write(Logger.CRITICAL, "Disconnected!", self.NICK)
  378. # so that we rejoin all our channels upon reconnecting to the server
  379. self.JOINED = False
  380. self.CONNECTED = False
  381. global RETRY_COUNTER
  382. if RETRY_COUNTER > 10:
  383. self.debug_print("Failed to reconnect after 10 tries. Giving up...")
  384. sys.exit(1)
  385. RETRY_COUNTER+=1
  386. self.worker()
  387. time.sleep(1)
  388. ready = select.select([self.s], [], [], 1)
  389. if ready[0]:
  390. try:
  391. read = read + self.s.recv(1024).decode('utf8', 'ignore')
  392. except UnicodeDecodeError, e:
  393. self.debug_print("Unicode decode error; " + e.__str__())
  394. self.debug_print("Offending recv: " + self.s.recv)
  395. pass
  396. except Exception, e:
  397. print e
  398. if self.DEBUG:
  399. self.debug_print("Disconnected! Retrying... ")
  400. disconnect_event.notifySubscribers("null")
  401. self.logger.write(Logger.CRITICAL, "Disconnected!", self.NICK)
  402. self.JOINED = False
  403. self.CONNECTED = False
  404. self.worker()
  405. lines = read.split('\n')
  406. # Important: all lines from irc are terminated with '\n'. lines.pop() will get you any "to be continued"
  407. # line that couldn't fit in the socket buffer. It is stored and tacked on to the start of the next recv.
  408. read = lines.pop()
  409. if len(lines) > 0:
  410. timeout = 0
  411. for line in lines:
  412. line = line.rstrip()
  413. self.processline(line)
  414. except KeyboardInterrupt:
  415. print "keyboard interrupt caught; exiting ..."
  416. raise
  417. # end worker
  418. def debug_print(self, line, error=False):
  419. """
  420. Prepends incoming lines with the current timestamp and the thread's name, then spits it to stdout.
  421. Warning: this is entirely asynchronous between threads. If you connect to multiple networks, they will interrupt each other between lines.
  422. Args:
  423. line: text.
  424. error: boolean, defaults to False. if True, prints out with red >> in the debug line
  425. """
  426. if not error:
  427. print str(datetime.datetime.now()) + ": " + self.getName() + ": " + line.strip('\n').rstrip().lstrip()
  428. else:
  429. print str(datetime.datetime.now()) + ": " + self.getName() + ": " + util.bcolors.RED + ">> " + util.bcolors.ENDC + line.strip('\n').rstrip().lstrip()
  430. def run(self):
  431. """
  432. For implementing the parent threading.Thread class. Allows the thread the be initialized with our code.
  433. """
  434. self.worker()
  435. def say(self, channel, thing):
  436. """
  437. Speak, damn you!
  438. """
  439. self.brain.say(channel, thing)
  440. # end class Bot
  441. ## MAIN ## ACTUAL EXECUTION STARTS HERE
  442. if __name__ == "__main__":
  443. DEBUG = False
  444. import bot
  445. parser = argparse.ArgumentParser(description="a python irc bot that does stuff")
  446. parser.add_argument('config', nargs='?')
  447. parser.add_argument('-d', help='debug (foreground) mode', action='store_true')
  448. args = parser.parse_args()
  449. if args.d:
  450. DEBUG = True
  451. if args.config:
  452. config = args.config
  453. else:
  454. config = "~/.pybotrc"
  455. botslist = list()
  456. if not DEBUG and hasattr(os, 'fork'):
  457. pid = os.fork()
  458. if pid == 0: # child
  459. if os.name == "posix":
  460. print "starting bot in the background, pid " + util.bcolors.GREEN + str(os.getpid()) + util.bcolors.ENDC
  461. else:
  462. print "starting bot in the background, pid " + str(os.getpid())
  463. cm = confman.ConfManager(config)
  464. net_list = cm.getNetworks()
  465. for c in cm.getNetworks():
  466. b = bot.Bot(cm, c, DEBUG)
  467. b.start()
  468. elif pid > 0:
  469. sys.exit(0)
  470. else: # don't background; either we're in debug (foreground) mode, or on windows TODO
  471. if os.name == 'nt':
  472. print 'in debug mode; backgrounding currently unsupported on windows.'
  473. DEBUG = True
  474. print "starting bot, pid " + util.bcolors.GREEN + str(os.getpid()) + util.bcolors.ENDC
  475. try:
  476. f = open(os.path.expanduser(config))
  477. except IOError:
  478. print "Could not open conf file " + config
  479. sys.exit(1)
  480. cm = confman.ConfManager(config)
  481. net_list = cm.getNetworks()
  482. for c in cm.getNetworks():
  483. b = bot.Bot(cm, c, DEBUG)
  484. b.daemon = True
  485. b.start()
  486. botslist.append(b)
  487. try:
  488. while True:
  489. time.sleep(5)
  490. except (KeyboardInterrupt, SystemExit):
  491. l = Logger()
  492. l.write(Logger.INFO, "killed by ctrl+c or term signal")
  493. for b in botslist:
  494. b.s.send("QUIT :because I got killed\n")
  495. print
  496. print "keyboard interrupt caught; exiting"
  497. sys.exit(1)