myanimebot.py 24 KB

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