bot.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. target = message.split()[1]
  247. if target.startswith("#"):
  248. self.processline(':' + self.conf.getNick(self.network) + '!~' + self.conf.getNick(self.network) + '@fakehost.here ' + message.rstrip())
  249. def pong(self, response):
  250. """
  251. Keepalive heartbeat for IRC protocol. Until someone changes the IRC spec, don't modify this.
  252. """
  253. self.send('PONG ' + response + '\n')
  254. def processline(self, line):
  255. """
  256. Grab newline-delineated lines sent to us, and determine what to do with them.
  257. 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.
  258. Also immediately passes off PING messages to PONG.
  259. Args:
  260. line: string.
  261. """
  262. if self.DEBUG:
  263. import datetime
  264. if os.name == "posix": # because windows doesn't like the color codes.
  265. self.debug_print(util.bcolors.OKBLUE + "<< " + util.bcolors.ENDC + line)
  266. else:
  267. self.debug_print("<< " + ": " + line)
  268. message_number = line.split()[1]
  269. try:
  270. first_word = line.split(":", 2)[2].split()[0]
  271. channel = line.split()[2]
  272. except IndexError:
  273. pass
  274. else:
  275. if first_word in self.command_function_map:
  276. self.command_function_map[first_word](self, line, channel)
  277. try:
  278. for e in self.events_list:
  279. if e.matches(line):
  280. e.notifySubscribers(line)
  281. # don't bother going any further if it's a PING/PONG request
  282. if line.startswith("PING"):
  283. ping_response_line = line.split(":", 1)
  284. self.pong(ping_response_line[1])
  285. # pings we respond to directly. everything else...
  286. else:
  287. # patch contributed by github.com/thekanbo
  288. if self.JOINED is False and (message_number == "376" or message_number == "422"):
  289. # wait until we receive end of MOTD before joining, or until the server tells us the MOTD doesn't exis
  290. self.chan_list = self.conf.getChannels(self.network)
  291. for c in self.chan_list:
  292. self.send('JOIN '+c+' \n')
  293. self.JOINED = True
  294. line_array = line.split()
  295. user_and_mask = line_array[0][1:]
  296. usr = user_and_mask.split("!")[0]
  297. channel = line_array[2]
  298. try:
  299. message = line.split(":",2)[2]
  300. self.brain.respond(usr, channel, message)
  301. except IndexError:
  302. try:
  303. message = line.split(":",2)[1]
  304. self.brain.respond(usr, channel, message)
  305. except IndexError:
  306. print "index out of range.", line
  307. except Exception:
  308. print "Unexpected error:", sys.exc_info()[0]
  309. traceback.print_exc(file=sys.stdout)
  310. def worker(self, mock=False):
  311. """
  312. Open the socket, make the first incision^H^H connection and get us on the server.
  313. Handles keeping the connection alive; if we disconnect from the server, attempts to reconnect.
  314. Args:
  315. mock: boolean. If mock is true, don't loop forever -- mock is for testing.
  316. """
  317. self.HOST = self.network
  318. self.NICK = self.conf.getNick(self.network)
  319. # we have to cast it to an int, otherwise the connection fails silently and the entire process dies
  320. self.PORT = int(self.conf.getPort(self.network))
  321. self.IDENT = 'mypy'
  322. self.REALNAME = 's1ash'
  323. self.OWNER = self.conf.getOwner(self.network)
  324. # connect to server
  325. self.s = socket.socket()
  326. while self.CONNECTED == False:
  327. try:
  328. # low level socket TCP/IP connection
  329. self.s.connect((self.HOST, self.PORT)) # force them into one argument
  330. self.CONNECTED = True
  331. self.logger.write(Logger.INFO, "Connected to " + self.network, self.NICK)
  332. if self.DEBUG:
  333. self.debug_print(util.bcolors.YELLOW + ">> " + util.bcolors.ENDC + "connected to " + self.network)
  334. except:
  335. if self.DEBUG:
  336. self.debug_print(util.bcolors.FAIL + ">> " + util.bcolors.ENDC + "Could not connect! Retrying... ")
  337. self.logger.write(Logger.CRITICAL, "Could not connect! Retrying...")
  338. time.sleep(1)
  339. self.worker()
  340. time.sleep(1)
  341. # core IRC protocol stuff
  342. self.s.send('NICK '+self.NICK+'\n')
  343. if self.DEBUG:
  344. self.debug_print(util.bcolors.YELLOW + ">> " + util.bcolors.ENDC + self.network + ': NICK ' + self.NICK + '\\n')
  345. self.s.send('USER '+self.IDENT+ ' 8 ' + ' bla : '+self.REALNAME+'\n') # yeah, don't delete this line
  346. if self.DEBUG:
  347. self.debug_print(util.bcolors.YELLOW + ">> " + util.bcolors.ENDC + self.network + ": USER " +self.IDENT+ ' 8 ' + ' bla : '+self.REALNAME+'\\n')
  348. time.sleep(3) # allow services to catch up
  349. self.s.send('PRIVMSG nickserv identify '+self.conf.getIRCPass(self.network)+'\n') # we're registered!
  350. if self.DEBUG:
  351. self.debug_print(util.bcolors.YELLOW + ">> " + util.bcolors.ENDC + self.network + ': PRIVMSG nickserv identify '+self.conf.getIRCPass(self.network)+'\\n')
  352. self.s.setblocking(1)
  353. read = ""
  354. timeout = 0
  355. # if we're only running a test of connecting, and don't want to loop forever
  356. if mock:
  357. return
  358. # infinite loop to keep parsing lines
  359. while True:
  360. try:
  361. timeout += 1
  362. # if we haven't received anything for 120 seconds
  363. time_since = self.conf.getTimeout(self.network)
  364. if timeout > time_since:
  365. if self.DEBUG:
  366. self.debug_print("Disconnected! Retrying... ")
  367. self.logger.write(Logger.CRITICAL, "Disconnected!", self.NICK)
  368. # so that we rejoin all our channels upon reconnecting to the server
  369. self.JOINED = False
  370. self.CONNECTED = False
  371. self.worker()
  372. time.sleep(1)
  373. # if self.CONNECTED == False:
  374. # self.connect()
  375. ready = select.select([self.s],[],[], 1)
  376. if ready[0]:
  377. try:
  378. read = read + self.s.recv(1024).decode('utf8')
  379. except UnicodeDecodeError, e:
  380. self.debug_print("Unicode decode error; " + e.__str__())
  381. self.debug_print("Offending recv: " + read)
  382. pass
  383. except Exception, e:
  384. print e
  385. if self.DEBUG:
  386. self.debug_print("Disconnected! Retrying... ")
  387. self.logger.write(Logger.CRITICAL, "Disconnected!", self.NICK)
  388. self.JOINED = False
  389. self.CONNECTED = False
  390. self.worker()
  391. lines = read.split('\n')
  392. # Important: all lines from irc are terminated with '\n'. lines.pop() will get you any "to be continued"
  393. # line that couldn't fit in the socket buffer. It is stored and tacked on to the start of the next recv.
  394. read = lines.pop()
  395. if len(lines) > 0:
  396. timeout = 0
  397. for line in lines:
  398. line = line.rstrip()
  399. self.processline(line)
  400. except KeyboardInterrupt:
  401. print "keyboard interrupt caught; exiting ..."
  402. raise
  403. # end worker
  404. def debug_print(self, line):
  405. """
  406. Prepends incoming lines with the current timestamp and the thread's name, then spits it to stdout.
  407. Warning: this is entirely asynchronous between threads. If you connect to multiple networks, they will interrupt each other between lines.
  408. Args:
  409. line: text.
  410. """
  411. print str(datetime.datetime.now()) + ": " + self.getName() + ": " + line.strip('\n').rstrip().lstrip()
  412. def run(self):
  413. """
  414. For implementing the parent threading.Thread class. Allows the thread the be initialized with our code.
  415. """
  416. self.worker()
  417. def say(self, channel, thing):
  418. """
  419. Speak, damn you!
  420. """
  421. self.brain.say(channel, thing)
  422. # end class Bot
  423. ## MAIN ## ACTUAL EXECUTION STARTS HERE
  424. if __name__ == "__main__":
  425. import bot
  426. DEBUG = False
  427. for i in sys.argv:
  428. if i == "-d":
  429. DEBUG = True
  430. # duuude this is so old.
  431. botslist = list()
  432. if not DEBUG and hasattr(os, 'fork'):
  433. pid = os.fork()
  434. if pid == 0: # child
  435. if os.name == "posix":
  436. print "starting bot in the background, pid " + util.bcolors.GREEN + str(os.getpid()) + util.bcolors.ENDC
  437. else:
  438. print "starting bot in the background, pid " + str(os.getpid())
  439. if len(sys.argv) > 1:
  440. CONF = sys.argv[1]
  441. else: CONF = "~/.pybotrc"
  442. cm = confman.ConfManager(CONF)
  443. net_list = cm.getNetworks()
  444. for c in cm.getNetworks():
  445. b = bot.Bot(cm, c, DEBUG)
  446. b.start()
  447. elif pid > 0:
  448. sys.exit(0)
  449. else: # don't background; either we're in debug (foreground) mode, or on windows TODO
  450. if os.name == 'nt':
  451. print 'in debug mode; backgrounding currently unsupported on windows.'
  452. DEBUG = True
  453. print "starting bot, pid " + util.bcolors.GREEN + str(os.getpid()) + util.bcolors.ENDC
  454. if len(sys.argv) > 1 and sys.argv[1] != "-d": # the conf file must be first argument
  455. CONF = sys.argv[1]
  456. try:
  457. f = open(CONF)
  458. except IOError:
  459. print "Could not open conf file " + sys.argv[1]
  460. sys.exit(1)
  461. else: CONF = "~/.pybotrc"
  462. cm = confman.ConfManager(CONF)
  463. net_list = cm.getNetworks()
  464. for c in cm.getNetworks():
  465. b = bot.Bot(cm, c, DEBUG)
  466. b.daemon = True
  467. b.start()
  468. botslist.append(b)
  469. try:
  470. while True:
  471. time.sleep(5)
  472. except (KeyboardInterrupt, SystemExit):
  473. for b in botslist:
  474. b.s.send("QUIT :because I got killed\n")
  475. print
  476. print "keyboard interrupt caught; exiting"
  477. sys.exit(1)