myanimebot.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. #!/usr/bin/env python3
  2. # Copyright Penta (c) 2018/2020 - Under BSD License - Based on feed2discord.py by Eric Eisenhart
  3. # Compatible for Python 3.7.X
  4. #
  5. # Dependencies (for CentOS 7):
  6. # curl -LsS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash
  7. # yum install gcc MariaDB-client MariaDB-common MariaDB-shared MariaDB-devel
  8. # python3.7 -m pip install --upgrade pip
  9. # pip3.7 install discord.py mariadb pytz feedparser python-dateutil asyncio html2text bs4 PyNaCL aiodns cchardet configparser
  10. # Library import
  11. import logging
  12. import os
  13. import sys
  14. import discord
  15. import feedparser
  16. import pytz
  17. import aiohttp
  18. import asyncio
  19. import urllib.request
  20. import mariadb
  21. import string
  22. import time
  23. import socket
  24. # Custom libraries
  25. sys.path.append('include/')
  26. import utils
  27. from configparser import ConfigParser
  28. from datetime import datetime
  29. from dateutil.parser import parse as parse_datetime
  30. from html2text import HTML2Text
  31. from aiohttp.web_exceptions import HTTPError, HTTPNotModified
  32. if not sys.version_info[:2] >= (3, 7):
  33. print("ERROR: Requires python 3.7 or newer.")
  34. exit(1)
  35. class ImproperlyConfigured(Exception): pass
  36. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  37. HOME_DIR = os.path.expanduser("~")
  38. DEFAULT_CONFIG_PATHS = [
  39. os.path.join("myanimebot.conf"),
  40. os.path.join(BASE_DIR, "myanimebot.conf"),
  41. os.path.join("/etc/malbot/myanimebot.conf"),
  42. os.path.join(HOME_DIR, "myanimebot.conf")
  43. ]
  44. def get_config():
  45. config = ConfigParser()
  46. config_paths = []
  47. for path in DEFAULT_CONFIG_PATHS:
  48. if os.path.isfile(path):
  49. config_paths.append(path)
  50. break
  51. else: raise ImproperlyConfigured("No configuration file found")
  52. config.read(config_paths)
  53. return config
  54. # Loading configuration
  55. try:
  56. config=get_config()
  57. except Exception as e:
  58. print ("Cannot read configuration: " + str(e))
  59. exit (1)
  60. CONFIG=config["MYANIMEBOT"]
  61. logLevel=CONFIG.get("logLevel", "INFO")
  62. dbHost=CONFIG.get("dbHost", "127.0.0.1")
  63. dbUser=CONFIG.get("dbUser", "myanimebot")
  64. dbPassword=CONFIG.get("dbPassword")
  65. dbName=CONFIG.get("dbName", "myanimebot")
  66. logPath=CONFIG.get("logPath", "myanimebot.log")
  67. timezone=pytz.timezone(CONFIG.get("timezone", "utc"))
  68. secondMax=CONFIG.getint("secondMax", 7200)
  69. token=CONFIG.get("token")
  70. prefix=CONFIG.get("prefix", "!malbot")
  71. iconMAL=CONFIG.get("iconMAL", "https://cdn.myanimelist.net/img/sp/icon/apple-touch-icon-256.png")
  72. iconBot=CONFIG.get("iconBot", "http://myanimebot.pentou.eu/rsc/bot_avatar.jpg")
  73. # class that send logs to DB
  74. class LogDBHandler(logging.Handler):
  75. def __init__(self, sql_conn, sql_cursor):
  76. logging.Handler.__init__(self)
  77. self.sql_cursor = sql_cursor
  78. self.sql_conn = sql_conn
  79. def emit(self, record):
  80. # Clear the log message so it can be put to db via sql (escape quotes)
  81. self.log_msg = str(record.msg.strip().replace('\'', '\'\''))
  82. # Make the SQL insert
  83. try:
  84. 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)))
  85. self.sql_conn.commit()
  86. except Exception as e:
  87. print ('Error while logging into DB: ' + str(e))
  88. # Log configuration
  89. log_format='%(asctime)-13s : %(name)-15s : %(levelname)-8s : %(message)s'
  90. logging.basicConfig(handlers=[logging.FileHandler(logPath, 'a', 'utf-8')], format=log_format, level=logLevel)
  91. console = logging.StreamHandler()
  92. console.setLevel(logging.INFO)
  93. console.setFormatter(logging.Formatter(log_format))
  94. logger = logging.getLogger("myanimebot")
  95. logger.setLevel(logLevel)
  96. logging.getLogger('').addHandler(console)
  97. # Script version
  98. VERSION = "0.9.6.2"
  99. # The help message
  100. HELP = """**Here's some help for you:**
  101. ```
  102. - here :
  103. Type this command on the channel where you want to see the activity of the MAL profiles.
  104. - stop :
  105. Cancel the here command, no message will be displayed.
  106. - add :
  107. Followed by a username, add a MAL user into the database to be displayed on this server.
  108. ex: !malbot add MyUser
  109. - delete :
  110. Followed by a username, remove a user from the database.
  111. ex: !malbot delete MyUser
  112. - group :
  113. Specify a group that can use the add and delete commands.
  114. - info :
  115. Get the users already in the database for this server.
  116. - about :
  117. Get some information about this bot.
  118. ```"""
  119. logger.info("Booting MyAnimeBot " + VERSION + "...")
  120. logger.debug("DEBUG log: OK")
  121. feedparser.PREFERRED_XML_PARSERS.remove("drv_libxml2")
  122. # Initialization of the database
  123. try:
  124. # Main database connection
  125. conn = mariadb.connect(host=dbHost, user=dbUser, password=dbPassword, database=dbName)
  126. # We initialize the logs into the DB.
  127. log_conn = mariadb.connect(host=dbHost, user=dbUser, password=dbPassword, database=dbName)
  128. log_cursor = log_conn.cursor()
  129. logdb = LogDBHandler(log_conn, log_cursor)
  130. logging.getLogger('').addHandler(logdb)
  131. logger.info("The database logger is running.")
  132. except Exception as e:
  133. logger.critical("Can't connect to the database: " + str(e))
  134. quit()
  135. # Initialization of the Discord client
  136. client = discord.Client()
  137. task_feed = None
  138. task_gameplayed = None
  139. task_thumbnail = None
  140. # Function used to make the embed message related to the animes status
  141. def build_embed(user, item, channel, pubDate, image):
  142. try:
  143. embed = discord.Embed(colour=0xEED000, url=item.link, description="[" + utils.filter_name(item.title) + "](" + item.link + ")\n```" + item.description + "```", timestamp=pubDate.astimezone(pytz.timezone("utc")))
  144. embed.set_thumbnail(url=image)
  145. embed.set_author(name=user + "'s MyAnimeList", url="https://myanimelist.net/profile/" + user, icon_url=iconMAL)
  146. embed.set_footer(text="MyAnimeBot", icon_url=iconBot)
  147. return embed
  148. except Exception as e:
  149. logger.error("Error when generating the message: " + str(e))
  150. return
  151. # Function used to send the embed
  152. async def send_embed_wrapper(asyncioloop, channelid, client, embed):
  153. channel = client.get_channel(int(channelid))
  154. try:
  155. await channel.send(embed=embed)
  156. logger.info("Message sent in channel: " + channelid)
  157. except Exception as e:
  158. logger.debug("Impossible to send a message on '" + channelid + "': " + str(e))
  159. return
  160. # Main function that check the RSS feeds from MyAnimeList
  161. async def background_check_feed(asyncioloop):
  162. logger.info("Starting up background_check_feed")
  163. # We configure the http header
  164. http_headers = { "User-Agent": "MyAnimeBot Discord Bot v" + VERSION, }
  165. await client.wait_until_ready()
  166. logger.debug("Discord client connected, unlocking background_check_feed...")
  167. while not client.is_closed():
  168. try:
  169. db_user = conn.cursor(buffered=True)
  170. db_user.execute("SELECT mal_user, servers FROM t_users")
  171. data_user = db_user.fetchone()
  172. except Exception as e:
  173. logger.critical("Database unavailable! (" + str(e) + ")")
  174. quit()
  175. while data_user is not None:
  176. user=data_user[0]
  177. stop_boucle = 0
  178. feed_type = 1
  179. logger.debug("checking user: " + user)
  180. try:
  181. while stop_boucle == 0 :
  182. try:
  183. async with aiohttp.ClientSession() as httpclient:
  184. if feed_type == 1 :
  185. http_response = await httpclient.request("GET", "https://myanimelist.net/rss.php?type=rm&u=" + user, headers=http_headers)
  186. media = "manga"
  187. else :
  188. http_response = await httpclient.request("GET", "https://myanimelist.net/rss.php?type=rw&u=" + user, headers=http_headers)
  189. media = "anime"
  190. except Exception as e:
  191. logger.error("Error while loading RSS (" + str(feed_type) + ") of '" + user + "': " + str(e))
  192. break
  193. http_data = await http_response.read()
  194. feed_data = feedparser.parse(http_data)
  195. for item in feed_data.entries:
  196. pubDateRaw = datetime.strptime(item.published, '%a, %d %b %Y %H:%M:%S %z').astimezone(timezone)
  197. DateTimezone = pubDateRaw.strftime("%z")[:3] + ':' + pubDateRaw.strftime("%z")[3:]
  198. pubDate = pubDateRaw.strftime("%Y-%m-%d %H:%M:%S")
  199. cursor = conn.cursor(buffered=True)
  200. cursor.execute("SELECT published, title, url FROM t_feeds WHERE published=%s AND title=%s AND user=%s", [pubDate, item.title, user])
  201. data = cursor.fetchone()
  202. if data is None:
  203. var = datetime.now(timezone) - pubDateRaw
  204. logger.debug(" - " + item.title + ": " + str(var.total_seconds()))
  205. if var.total_seconds() < secondMax:
  206. logger.info(user + ": Item '" + item.title + "' not seen, processing...")
  207. if item.description.startswith('-') :
  208. if feed_type == 1 : item.description = "Re-Reading " + item.description
  209. else : item.description = "Re-Watching " + item.description
  210. cursor.execute("SELECT thumbnail FROM t_animes WHERE guid=%s LIMIT 1", [item.guid])
  211. data_img = cursor.fetchone()
  212. if data_img is None:
  213. try:
  214. image = utils.getThumbnail(item.link)
  215. logger.info("First time seeing this " + media + ", adding thumbnail into database: " + image)
  216. except Exception as e:
  217. logger.warning("Error while getting the thumbnail: " + str(e))
  218. image = ""
  219. cursor.execute("INSERT INTO t_animes (guid, title, thumbnail, found, discoverer, media) VALUES (%s, %s, %s, NOW(), %s, %s)", [item.guid, item.title, image, user, media])
  220. conn.commit()
  221. else: image = data_img[0]
  222. type = item.description.partition(" - ")[0]
  223. cursor.execute("INSERT INTO t_feeds (published, title, url, user, found, type) VALUES (%s, %s, %s, %s, NOW(), %s)", (pubDate, item.title, item.guid, user, type))
  224. conn.commit()
  225. for server in data_user[1].split(","):
  226. db_srv = conn.cursor(buffered=True)
  227. db_srv.execute("SELECT channel FROM t_servers WHERE server = %s", [server])
  228. data_channel = db_srv.fetchone()
  229. while data_channel is not None:
  230. for channel in data_channel: await send_embed_wrapper(asyncioloop, channel, client, build_embed(user, item, channel, pubDateRaw, image))
  231. data_channel = db_srv.fetchone()
  232. if feed_type == 1:
  233. feed_type = 0
  234. await asyncio.sleep(1)
  235. else:
  236. stop_boucle = 1
  237. except Exception as e:
  238. logger.error("Error when parsing RSS for '" + user + "': " + str(e))
  239. await asyncio.sleep(1)
  240. data_user = db_user.fetchone()
  241. @client.event
  242. async def on_ready():
  243. logger.info("Logged in as " + client.user.name + " (" + str(client.user.id) + ")")
  244. logger.info("Starting all tasks...")
  245. task_feed = client.loop.create_task(background_check_feed(client.loop))
  246. task_thumbnail = client.loop.create_task(update_thumbnail_catalog(client.loop))
  247. task_gameplayed = client.loop.create_task(change_gameplayed(client.loop))
  248. @client.event
  249. async def on_error(event, *args, **kwargs):
  250. logger.exception("Crap! An unknown Discord error occured...")
  251. @client.event
  252. async def on_message(message):
  253. if message.author == client.user: return
  254. words = message.content.split(" ")
  255. author = str('{0.author.mention}'.format(message))
  256. # A user is trying to get help
  257. if words[0] == prefix:
  258. if len(words) > 1:
  259. if words[1] == "ping": await message.channel.send("pong")
  260. elif words[1] == "here":
  261. if message.author.guild_permissions.administrator:
  262. cursor = conn.cursor(buffered=True)
  263. cursor.execute("SELECT server, channel FROM t_servers WHERE server=%s", [str(message.guild.id)])
  264. data = cursor.fetchone()
  265. if data is None:
  266. cursor.execute("INSERT INTO t_servers (server, channel) VALUES (%s,%s)", [str(message.guild.id), str(message.channel.id)])
  267. conn.commit()
  268. await message.channel.send("Channel **" + str(message.channel) + "** configured for **" + str(message.guild) + "**.")
  269. else:
  270. if(data[1] == str(message.channel.id)): await message.channel.send("Channel **" + str(message.channel) + "** already in use for this server.")
  271. else:
  272. cursor.execute("UPDATE t_servers SET channel = %s WHERE server = %s", [str(message.channel.id), str(message.guild.id)])
  273. conn.commit()
  274. await message.channel.send("Channel updated to: **" + str(message.channel) + "**.")
  275. cursor.close()
  276. else: await message.channel.send("Only server's admins can use this command!")
  277. elif words[1] == "add":
  278. if len(words) > 2:
  279. if (len(words) == 3):
  280. user = words[2]
  281. if(len(user) < 15):
  282. try:
  283. urllib.request.urlopen('https://myanimelist.net/profile/' + user)
  284. cursor = conn.cursor(buffered=True)
  285. cursor.execute("SELECT servers FROM t_users WHERE LOWER(mal_user)=%s", [user.lower()])
  286. data = cursor.fetchone()
  287. if data is None:
  288. cursor.execute("INSERT INTO t_users (mal_user, servers) VALUES (%s, %s)", [user, str(message.guild.id)])
  289. conn.commit()
  290. await message.channel.send("**" + user + "** added to the database for the server **" + str(message.guild) + "**.")
  291. else:
  292. var = 0
  293. for server in data[0].split(","):
  294. if (server == str(message.guild.id)): var = 1
  295. if (var == 1):
  296. await message.channel.send("User **" + user + "** already in our database for this server!")
  297. else:
  298. cursor.execute("UPDATE t_users SET servers = %s WHERE LOWER(mal_user) = %s", [data[0] + "," + str(message.guild.id), user.lower()])
  299. conn.commit()
  300. await message.channel.send("**" + user + "** added to the database for the server **" + str(message.guild) + "**.")
  301. cursor.close()
  302. except urllib.error.HTTPError as e:
  303. if (e.code == 404): await message.channel.send("User **" + user + "** doesn't exist on MyAnimeList!")
  304. else:
  305. await message.channel.send("An error occured when we checked this username on MyAnimeList, maybe the website is down?")
  306. logger.warning("HTTP Code " + str(e.code) + " while checking to add for the new user '" + user + "'")
  307. except Exception as e:
  308. await message.channel.send("An unknown error occured while addind this user, the error has been logged.")
  309. logger.warning("Error while adding user '" + user + "' on server '" + message.guild + "': " + str(e))
  310. else: await message.channel.send("Username too long!")
  311. else: await message.channel.send("Too many arguments! You have to specify only one username.")
  312. else: await message.channel.send("You have to specify a **MyAnimeList** username!")
  313. elif words[1] == "delete":
  314. if len(words) > 2:
  315. if (len(words) == 3):
  316. user = words[2]
  317. cursor = conn.cursor(buffered=True)
  318. cursor.execute("SELECT servers FROM t_users WHERE LOWER(mal_user)=%s", [user.lower()])
  319. data = cursor.fetchone()
  320. if data is not None:
  321. srv_string = ""
  322. present = 0
  323. for server in data[0].split(","):
  324. if server != str(message.guild.id):
  325. if srv_string == "": srv_string = server
  326. else: srv_string += "," + server
  327. else: present = 1
  328. if present == 1:
  329. if srv_string == "": cursor.execute("DELETE FROM t_users WHERE LOWER(mal_user) = %s", [user.lower()])
  330. else: cursor.execute("UPDATE t_users SET servers = %s WHERE LOWER(mal_user) = %s", [srv_string, user.lower()])
  331. conn.commit()
  332. await message.channel.send("**" + user + "** deleted from the database for this server.")
  333. else: await message.channel.send("The user **" + user + "** is not in our database for this server!")
  334. else: await message.channel.send("The user **" + user + "** is not in our database for this server!")
  335. cursor.close()
  336. else: await message.channel.send("Too many arguments! You have to specify only one username.")
  337. else: await message.channel.send("You have to specify a **MyAnimeList** username!")
  338. elif words[1] == "stop":
  339. if message.author.guild_permissions.administrator:
  340. if (len(words) == 2):
  341. cursor = conn.cursor(buffered=True)
  342. cursor.execute("SELECT server FROM t_servers WHERE server=%s", [str(message.guild.id)])
  343. data = cursor.fetchone()
  344. if data is None: await client.send_message(message.channel, "The server **" + str(message.guild) + "** is not in our database.")
  345. else:
  346. cursor.execute("DELETE FROM t_servers WHERE server = %s", [message.guild.id])
  347. conn.commit()
  348. await message.channel.send("Server **" + str(message.guild) + "** deleted from our database.")
  349. cursor.close()
  350. else: await message.channel.send("Too many arguments! Only type *stop* if you want to stop this bot on **" + message.guild + "**")
  351. else: await message.channel.send("Only server's admins can use this command!")
  352. elif words[1] == "info":
  353. cursor = conn.cursor(buffered=True)
  354. cursor.execute("SELECT server FROM t_servers WHERE server=%s", [str(message.guild.id)])
  355. data = cursor.fetchone()
  356. if data is None: await message.channel.send("The server **" + str(message.guild) + "** is not in our database.")
  357. else:
  358. user = ""
  359. cursor = conn.cursor(buffered=True)
  360. cursor.execute("SELECT mal_user, servers FROM t_users")
  361. data = cursor.fetchone()
  362. cursor_channel = conn.cursor(buffered=True)
  363. cursor_channel.execute("SELECT channel FROM t_servers WHERE server=%s", [str(message.guild.id)])
  364. data_channel = cursor_channel.fetchone()
  365. if data_channel is None: await message.channel.send("No channel assigned for this bot in this server.")
  366. else:
  367. while data is not None:
  368. if (str(message.guild.id) in data[1].split(",")):
  369. if (user == ""): user = data[0]
  370. else: user += ", " + data[0]
  371. data = cursor.fetchone()
  372. if (user == ""): await message.channel.send("No user in this server.")
  373. else: await message.channel.send("Here's the user(s) in the **" + str(message.guild) + "**'s server:\n```" + user + "```\nAssigned channel: **" + str(client.get_channel(int(data_channel[0]))) + "**")
  374. cursor.close()
  375. cursor_channel.close()
  376. elif words[1] == "about": await message.channel.send(embed=discord.Embed(colour=0x777777, title="MyAnimeBot version " + VERSION + " by Penta", description="This bot check the MyAnimeList's RSS for each user specified, and send a message if there is something new.\nMore help with the **!malbot help** command.\n\nAdd me on steam: http://steamcommunity.com/id/Penta_Pingouin").set_thumbnail(url="https://cdn.discordapp.com/avatars/415474467033317376/2d847944aab2104923c18863a41647da.jpg?size=64"))
  377. elif words[1] == "help": await message.channel.send(HELP)
  378. elif words[1] == "top":
  379. if len(words) == 2:
  380. try:
  381. cursor = conn.cursor(buffered=True)
  382. cursor.execute("SELECT * FROM v_Top")
  383. data = cursor.fetchone()
  384. if data is None: await message.channel.send("It seems that there is no statistics... (what happened?!)")
  385. else:
  386. topText = "**__Here is the global statistics of this bot:__**\n\n"
  387. while data is not None:
  388. topText += " - " + str(data[0]) + ": " + str(data[1]) + "\n"
  389. data = cursor.fetchone()
  390. cursor = conn.cursor(buffered=True)
  391. cursor.execute("SELECT * FROM v_TotalFeeds")
  392. data = cursor.fetchone()
  393. topText += "\n***Total user entry***: " + str(data[0])
  394. cursor = conn.cursor(buffered=True)
  395. cursor.execute("SELECT * FROM v_TotalAnimes")
  396. data = cursor.fetchone()
  397. topText += "\n***Total unique manga/anime***: " + str(data[0])
  398. await message.channel.send(topText)
  399. cursor.close()
  400. except Exception as e:
  401. logger.warning("An error occured while displaying the global top: " + str(e))
  402. await message.channel.send("Unable to reply to your request at the moment...")
  403. elif len(words) > 2:
  404. keyword = str(' '.join(words[2:]))
  405. logger.info("Displaying the global top for the keyword: " + keyword)
  406. try:
  407. cursor = conn.cursor(buffered=True)
  408. cursor.callproc('sp_UsersPerKeyword', [str(keyword), '20'])
  409. for result in cursor.stored_results():
  410. data = result.fetchone()
  411. if data is None: await message.channel.send("It seems that there is no statistics for the keyword **" + keyword + "**.")
  412. else:
  413. topKeyText = "**__Here is the statistics for the keyword " + keyword + ":__**\n\n"
  414. while data is not None:
  415. topKeyText += " - " + str(data[0]) + ": " + str(data[1]) + "\n"
  416. data = result.fetchone()
  417. await message.channel.send(topKeyText)
  418. cursor.close()
  419. except Exception as e:
  420. logger.warning("An error occured while displaying the global top for keyword '" + keyword + "': " + str(e))
  421. await message.channel.send("Unable to reply to your request at the moment...")
  422. elif words[1] == "group":
  423. if len(words) > 2:
  424. if message.author.guild_permissions.administrator:
  425. group = words[2]
  426. await message.channel.send("admin OK")
  427. else: await message.channel.send("Only server's admins can use this command!")
  428. else:
  429. await message.channel.send("You have to specify a group!")
  430. # If mentioned
  431. elif client.user in message.mentions:
  432. await message.channel.send(":heart:")
  433. # Get a random anime name and change the bot's activity
  434. async def change_gameplayed(asyncioloop):
  435. logger.info("Starting up change_gameplayed")
  436. await client.wait_until_ready()
  437. await asyncio.sleep(1)
  438. while not client.is_closed():
  439. # Get a random anime name from the users' list
  440. cursor = conn.cursor(buffered=True)
  441. cursor.execute("SELECT title FROM t_animes ORDER BY RAND() LIMIT 1")
  442. data = cursor.fetchone()
  443. anime = utils.truncate_end_show(data[0])
  444. # Try to change the bot's activity
  445. try:
  446. if data is not None: await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=anime))
  447. except Exception as e:
  448. logger.warning("An error occured while changing the displayed anime title: " + str(e))
  449. cursor.close()
  450. # Do it every minute
  451. await asyncio.sleep(60)
  452. async def update_thumbnail_catalog(asyncioloop):
  453. logger.info("Starting up update_thumbnail_catalog")
  454. while not client.is_closed():
  455. await asyncio.sleep(43200)
  456. logger.info("Automatic check of the thumbnail database on going...")
  457. reload = 0
  458. cursor = conn.cursor(buffered=True)
  459. cursor.execute("SELECT guid, title, thumbnail FROM t_animes")
  460. data = cursor.fetchone()
  461. while data is not None:
  462. try:
  463. if (data[2] != "") : urllib.request.urlopen(data[2])
  464. else: reload = 1
  465. except urllib.error.HTTPError as e:
  466. logger.warning("HTTP Error while getting the current thumbnail of '" + str(data[1]) + "': " + str(e))
  467. reload = 1
  468. except Exception as e:
  469. logger.debug("Error while getting the current thumbnail of '" + str(data[1]) + "': " + str(e))
  470. if (reload == 1) :
  471. try:
  472. image = utils.getThumbnail(data[0])
  473. cursor.execute("UPDATE t_animes SET thumbnail = %s WHERE guid = %s", [image, data[0]])
  474. conn.commit()
  475. logger.info("Updated thumbnail found for \"" + str(data[1]) + "\": %s", image)
  476. except Exception as e:
  477. logger.warning("Error while downloading updated thumbnail for '" + str(data[1]) + "': " + str(e))
  478. await asyncio.sleep(3)
  479. data = cursor.fetchone()
  480. cursor.close()
  481. logger.info("Thumbnail database checked.")
  482. # Starting main function
  483. if __name__ == "__main__":
  484. try:
  485. client.run(token)
  486. except:
  487. logging.info("Closing all tasks...")
  488. task_feed.cancel()
  489. task_thumbnail.cancel()
  490. task_gameplayed.cancel()
  491. logger.critical("Script halted.")
  492. # We close all the ressources
  493. conn.close()
  494. log_cursor.close()
  495. log_conn.close()