tg-sync

git clone git://archive.git.mtrnord.blog/Nordgedanken/tg-sync.git
Log | Files | Refs | README

bot.py (5064B)


      1 #Import external Modules that are needed
      2 import os.path, sys, traceback, shutil, logging, logging.config, argparse
      3 from multiprocessing import Pool
      4 
      5 logger = logging.getLogger(__name__)
      6 
      7 from bot.helper import config_class
      8 
      9 class Core:
     10     def run(self):
     11         pool = Pool(2)
     12         try:
     13             Ttelegram = pool.apply_async(Htelegram.Telegram().telegram_init(), [])
     14             Tslack = pool.apply_async(Hslack.Slack().slack_init(), [])
     15             pool.close()
     16             Ttelegram.join()
     17             Tslack.join()
     18         except KeyboardInterrupt:
     19             logger.info("Caught KeyboardInterrupt, terminating workers")
     20             pool.terminate()
     21 
     22 def configure_logging(args):
     23     """Configure Logging
     24     If the user specified a logging config file, open it, and
     25     fail if unable to open. If not, attempt to open the default
     26     logging config file. If that fails, move on to basic
     27     log configuration.
     28     """
     29 
     30     log_level = 'DEBUG' if args.debug else 'INFO'
     31 
     32     default_config = {
     33         'version': 1,
     34         'disable_existing_loggers': False,
     35         'formatters': {
     36             'console': {
     37                 'format': '%(asctime)s %(levelname)s %(name)s: %(message)s',
     38                 'datefmt': '%H:%M:%S'
     39                 },
     40             'default': {
     41                 'format': '%(asctime)s %(levelname)s %(name)s: %(message)s',
     42                 'datefmt': '%Y-%m-%d %H:%M:%S'
     43                 }
     44             },
     45         'handlers': {
     46             'console': {
     47                 'class': 'logging.StreamHandler',
     48                 'stream': 'ext://sys.stdout',
     49                 'level': 'INFO',
     50                 'formatter': 'console'
     51                 },
     52             'file': {
     53                 'class': 'logging.FileHandler',
     54                 'filename': args.log,
     55                 'level': log_level,
     56                 'formatter': 'default',
     57                 }
     58             },
     59         'loggers': {
     60             # root logger
     61             '': {
     62                 'handlers': ['file', 'console'],
     63                 'level': log_level
     64                 },
     65 
     66             # asyncio's debugging logs are VERY noisy, so adjust the log level
     67             'asyncio': {'level': 'WARNING'},
     68             'irde_bot': {'level': 'ERROR'}
     69             }
     70         }
     71 
     72     logging_config = default_config
     73 
     74     # Temporarily bring in the configuration file, just so we can configure
     75     # logging before bringing anything else up. There is no race internally,
     76     # if logging() is called before configured, it outputs to stderr, and
     77     # we will configure it soon enough
     78     if config_class.exists(["logging.system"]):
     79         logging_config = config_class["logging.system"]
     80 
     81     if "extras.setattr" in logging_config:
     82         for class_attr, value in logging_config["extras.setattr"].items():
     83             try:
     84                 [modulepath, classname, attribute] = class_attr.rsplit(".", maxsplit=2)
     85                 try:
     86                     setattr(class_from_name(modulepath, classname), attribute, value)
     87                 except ImportError:
     88                     logging.error("module {} not found".format(modulepath))
     89                 except AttributeError:
     90                     logging.error("{} in {} not found".format(classname, modulepath))
     91             except ValueError:
     92                 logging.error("format should be <module>.<class>.<attribute>")
     93 
     94     logging.config.dictConfig(logging_config)
     95 
     96     logger = logging.getLogger()
     97     if args.debug:
     98         logger.setLevel(logging.DEBUG)
     99 
    100 if __name__ == "__main__":
    101     default_log_path = os.path.join('config', 'TG-SL_bot.log')
    102 
    103     parser = argparse.ArgumentParser(prog='TG-SL_bot',
    104                                      formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    105     parser.add_argument('--log', default=default_log_path,
    106                             help='log file path')
    107     parser.add_argument('-d', '--debug', action='store_true',
    108                     help='log detailed debugging messages')
    109     args = parser.parse_args()
    110 
    111     if os.path.isdir("config"):
    112         if not (config_class.get_by_path(['SLACK_API_KEY'])) or not (config_class.get_by_path(['TELEGRAM_API_KEY'])):
    113             sys.exit('Please set Api Keys')
    114         #Import internal Modules that are needed
    115         from bot import Htelegram
    116         from bot import Hslack
    117         core = Core()
    118         core.run()
    119     else:
    120         os.makedirs("config")
    121         if not os.path.isfile(os.path.join('config', 'config.json')):
    122             try:
    123                 shutil.copy(os.path.join('defaults', 'config.json'), os.path.join('config', 'config.json'))
    124             except (OSError, IOError) as e:
    125                 sys.exit('Failed to copy default config file: {}'.format(e))
    126         if not os.path.isfile(os.path.join('config', 'memory.json')):
    127             try:
    128                 shutil.copy(os.path.join('defaults', 'memory.json'), os.path.join('config', 'memory.json'))
    129             except (OSError, IOError) as e:
    130                 sys.exit('Failed to copy default memory file: {}'.format(e))
    131         sys.exit('Please set Api Keys')
    132 
    133     configure_logging(args)