bot.py 20 KB

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