bot.py 17 KB

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