1
0

globals.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import logging
  2. import os
  3. import socket
  4. from configparser import ConfigParser
  5. import discord
  6. import feedparser
  7. import mariadb
  8. import pytz
  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. iconBot=CONFIG.get("iconBot", "http://myanimebot.pentou.eu/rsc/bot_avatar.jpg")
  46. ANILIST_SECONDS_BETWEEN_FETCHES=CONFIG.getint("anilist_seconds_between_fetches", 60)
  47. MAL_ICON_URL=CONFIG.get("iconMAL", "https://cdn.myanimelist.net/img/sp/icon/apple-touch-icon-256.png")
  48. ANILIST_ICON_URL=CONFIG.get("iconAniList", "https://anilist.co/img/icons/android-chrome-512x512.png")
  49. SERVICE_ANILIST="ani"
  50. SERVICE_MAL="mal"
  51. MAL_URL="https://myanimelist.net/"
  52. MAL_PROFILE_URL="https://myanimelist.net/profile/"
  53. ANILIST_PROFILE_URL="https://anilist.co/user/"
  54. DB_USER_NAME="mal_user" # Column's name for usernames in the t_users table
  55. # class that send logs to DB
  56. class LogDBHandler(logging.Handler):
  57. def __init__(self, sql_conn, sql_cursor):
  58. logging.Handler.__init__(self)
  59. self.sql_cursor = sql_cursor
  60. self.sql_conn = sql_conn
  61. def emit(self, record):
  62. # Clear the log message so it can be put to db via sql (escape quotes)
  63. self.log_msg = str(record.msg.strip().replace('\'', '\'\''))
  64. # Make the SQL insert
  65. try:
  66. 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)))
  67. self.sql_conn.commit()
  68. except Exception as e:
  69. print ('Error while logging into DB: ' + str(e))
  70. # Log configuration
  71. log_format='%(asctime)-13s : %(name)-15s : %(levelname)-8s : %(message)s'
  72. logging.basicConfig(handlers=[logging.FileHandler(logPath, 'a', 'utf-8')], format=log_format, level=logLevel)
  73. console = logging.StreamHandler()
  74. console.setLevel(logging.INFO)
  75. console.setFormatter(logging.Formatter(log_format))
  76. logger = logging.getLogger("myanimebot")
  77. logger.setLevel(logLevel)
  78. logging.getLogger('').addHandler(console)
  79. # Script version
  80. VERSION = "0.9.6.2"
  81. # The help message
  82. HELP = """**Here's some help for you:**
  83. ```
  84. - here :
  85. Type this command on the channel where you want to see the activity of the MAL profiles.
  86. - stop :
  87. Cancel the here command, no message will be displayed.
  88. - add :
  89. Followed by a username, add a MAL user into the database to be displayed on this server.
  90. ex: !malbot add MyUser
  91. - delete :
  92. Followed by a username, remove a user from the database.
  93. ex: !malbot delete MyUser
  94. - group :
  95. Specify a group that can use the add and delete commands.
  96. - info :
  97. Get the users already in the database for this server.
  98. - about :
  99. Get some information about this bot.
  100. ```"""
  101. logger.info("Booting MyAnimeBot " + VERSION + "...")
  102. logger.debug("DEBUG log: OK")
  103. # feedparser.PREFERRED_XML_PARSERS.remove("drv_libxml2")
  104. # Initialization of the database
  105. try:
  106. # Main database connection
  107. conn = mariadb.connect(host=dbHost, user=dbUser, password=dbPassword, database=dbName)
  108. # We initialize the logs into the DB.
  109. log_conn = mariadb.connect(host=dbHost, user=dbUser, password=dbPassword, database=dbName)
  110. log_cursor = log_conn.cursor()
  111. logdb = LogDBHandler(log_conn, log_cursor)
  112. logging.getLogger('').addHandler(logdb)
  113. logger.info("The database logger is running.")
  114. except Exception as e:
  115. logger.critical("Can't connect to the database: " + str(e))
  116. quit()
  117. # Initialization of the Discord client
  118. client = discord.Client()
  119. task_feed = None
  120. task_feed_anilist = None
  121. task_gameplayed = None
  122. task_thumbnail = None