globals.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import os
  2. import pytz
  3. import logging
  4. import discord
  5. import mariadb
  6. import feedparser
  7. import socket
  8. from configparser import ConfigParser
  9. class ImproperlyConfigured(Exception): pass
  10. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  11. HOME_DIR = os.path.expanduser("~")
  12. DEFAULT_CONFIG_PATHS = [
  13. os.path.join("myanimebot.conf"),
  14. os.path.join(BASE_DIR, "myanimebot.conf"),
  15. os.path.join("/etc/malbot/myanimebot.conf"),
  16. os.path.join(HOME_DIR, "myanimebot.conf")
  17. ]
  18. def get_config():
  19. config = ConfigParser()
  20. config_paths = []
  21. for path in DEFAULT_CONFIG_PATHS:
  22. if os.path.isfile(path):
  23. config_paths.append(path)
  24. break
  25. else: raise ImproperlyConfigured("No configuration file found")
  26. config.read(config_paths)
  27. return config
  28. # Loading configuration
  29. try:
  30. config=get_config()
  31. except Exception as e:
  32. print ("Cannot read configuration: " + str(e))
  33. exit (1)
  34. CONFIG=config["MYANIMEBOT"]
  35. logLevel=CONFIG.get("logLevel", "INFO")
  36. dbHost=CONFIG.get("dbHost", "127.0.0.1")
  37. dbUser=CONFIG.get("dbUser", "myanimebot")
  38. dbPassword=CONFIG.get("dbPassword")
  39. dbName=CONFIG.get("dbName", "myanimebot")
  40. logPath=CONFIG.get("logPath", "myanimebot.log")
  41. timezone=pytz.timezone(CONFIG.get("timezone", "utc"))
  42. secondMax=CONFIG.getint("secondMax", 7200)
  43. token=CONFIG.get("token")
  44. prefix=CONFIG.get("prefix", "!malbot")
  45. MAL_ICON_URL=CONFIG.get("iconMAL", "https://cdn.myanimelist.net/img/sp/icon/apple-touch-icon-256.png")
  46. ANILIST_ICON_URL=CONFIG.get("iconAniList", "https://anilist.co/img/icons/android-chrome-512x512.png")
  47. iconBot=CONFIG.get("iconBot", "http://myanimebot.pentou.eu/rsc/bot_avatar.jpg")
  48. SERVICE_ANILIST="AniList"
  49. SERVICE_MAL="mal"
  50. MAL_URL="https://myanimelist.net/"
  51. MAL_PROFILE_URL="https://myanimelist.net/profile/"
  52. ANILIST_PROFILE_URL="https://anilist.co/user/"
  53. # class that send logs to DB
  54. class LogDBHandler(logging.Handler):
  55. def __init__(self, sql_conn, sql_cursor):
  56. logging.Handler.__init__(self)
  57. self.sql_cursor = sql_cursor
  58. self.sql_conn = sql_conn
  59. def emit(self, record):
  60. # Clear the log message so it can be put to db via sql (escape quotes)
  61. self.log_msg = str(record.msg.strip().replace('\'', '\'\''))
  62. # Make the SQL insert
  63. try:
  64. self.sql_cursor.execute("INSERT INTO t_logs (host, level, type, log, date, source) VALUES (%s, %s, %s, %s, NOW(), %s)", (str(socket.gethostname()), str(record.levelno), str(record.levelname), self.log_msg, str(record.name)))
  65. self.sql_conn.commit()
  66. except Exception as e:
  67. print ('Error while logging into DB: ' + str(e))
  68. # Log configuration
  69. log_format='%(asctime)-13s : %(name)-15s : %(levelname)-8s : %(message)s'
  70. logging.basicConfig(handlers=[logging.FileHandler(logPath, 'a', 'utf-8')], format=log_format, level=logLevel)
  71. console = logging.StreamHandler()
  72. console.setLevel(logging.INFO)
  73. console.setFormatter(logging.Formatter(log_format))
  74. logger = logging.getLogger("myanimebot")
  75. logger.setLevel(logLevel)
  76. logging.getLogger('').addHandler(console)
  77. # Script version
  78. VERSION = "0.9.6.2"
  79. # The help message
  80. HELP = """**Here's some help for you:**
  81. ```
  82. - here :
  83. Type this command on the channel where you want to see the activity of the MAL profiles.
  84. - stop :
  85. Cancel the here command, no message will be displayed.
  86. - add :
  87. Followed by a username, add a MAL user into the database to be displayed on this server.
  88. ex: !malbot add MyUser
  89. - delete :
  90. Followed by a username, remove a user from the database.
  91. ex: !malbot delete MyUser
  92. - group :
  93. Specify a group that can use the add and delete commands.
  94. - info :
  95. Get the users already in the database for this server.
  96. - about :
  97. Get some information about this bot.
  98. ```"""
  99. logger.info("Booting MyAnimeBot " + VERSION + "...")
  100. logger.debug("DEBUG log: OK")
  101. feedparser.PREFERRED_XML_PARSERS.remove("drv_libxml2")
  102. # Initialization of the database
  103. try:
  104. # Main database connection
  105. conn = mariadb.connect(host=dbHost, user=dbUser, password=dbPassword, database=dbName)
  106. # We initialize the logs into the DB.
  107. log_conn = mariadb.connect(host=dbHost, user=dbUser, password=dbPassword, database=dbName)
  108. log_cursor = log_conn.cursor()
  109. logdb = LogDBHandler(log_conn, log_cursor)
  110. logging.getLogger('').addHandler(logdb)
  111. logger.info("The database logger is running.")
  112. except Exception as e:
  113. logger.critical("Can't connect to the database: " + str(e))
  114. quit()
  115. # Initialization of the Discord client
  116. client = discord.Client()
  117. task_feed = None
  118. task_gameplayed = None
  119. task_thumbnail = None
  120. print("DONE GLOBALS") # TODO REMOVE, DEBUG