1
0

globals.py 4.6 KB

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