myanimebot.py 24 KB

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