bot.py 20 KB

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