bot.py 20 KB

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