pybot.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env python3
  2. import argparse, os, sys, time
  3. import confman, util, logger, bot
  4. if __name__ == "__main__":
  5. DEBUG = False
  6. parser = argparse.ArgumentParser(description="a python irc bot that does stuff")
  7. parser.add_argument('config', nargs='?')
  8. parser.add_argument('-d', help='debug (foreground) mode', action='store_true')
  9. args = parser.parse_args()
  10. if args.d:
  11. DEBUG = True
  12. if args.config:
  13. config = args.config
  14. else:
  15. config = "~/.pybotrc"
  16. botslist = list()
  17. if not DEBUG and hasattr(os, 'fork'):
  18. pid = os.fork()
  19. if pid == 0: # child
  20. if os.name == "posix":
  21. print("starting bot in the background, pid " + util.bcolors.GREEN + str(os.getpid()) + util.bcolors.ENDC)
  22. else:
  23. print("starting bot in the background, pid " + str(os.getpid()))
  24. cm = confman.ConfManager(config)
  25. net_list = cm.getNetworks()
  26. for c in cm.getNetworks():
  27. b = bot.Bot(cm, c, DEBUG)
  28. b.start()
  29. elif pid > 0:
  30. sys.exit(0)
  31. else: # don't background; either we're in debug (foreground) mode, or on windows TODO
  32. if os.name == 'nt':
  33. print('in debug mode; backgrounding currently unsupported on windows.')
  34. DEBUG = True
  35. print("starting bot, pid " + util.bcolors.GREEN + str(os.getpid()) + util.bcolors.ENDC)
  36. try:
  37. f = open(os.path.expanduser(config))
  38. except IOError:
  39. print("Could not open conf file " + config)
  40. sys.exit(1)
  41. cm = confman.ConfManager(config)
  42. net_list = cm.getNetworks()
  43. for c in cm.getNetworks():
  44. b = bot.Bot(cm, c, DEBUG)
  45. b.daemon = True
  46. b.start()
  47. botslist.append(b)
  48. try:
  49. while True:
  50. time.sleep(5)
  51. except (KeyboardInterrupt, SystemExit):
  52. l = logger.Logger()
  53. l.write(logger.Logger.INFO, "killed by ctrl+c or term signal")
  54. for b in botslist:
  55. b.save_persistence()
  56. b.s.send(("QUIT :because I got killed\n").encode())
  57. print()
  58. print("keyboard interrupt caught; exiting")
  59. sys.exit(1)