1
0

myanimebot.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. #!/usr/bin/env python3
  2. # Copyright Penta & lulu (c) 2018/2021 - Under BSD License - Based on feed2discord.py by Eric Eisenhart
  3. # Compatible for Python 3.7.X
  4. # Library import
  5. import asyncio
  6. import logging
  7. import sys
  8. import urllib.request
  9. from configparser import ConfigParser
  10. from datetime import datetime
  11. from typing import List, Tuple
  12. import aiohttp
  13. import discord
  14. import feedparser
  15. from aiohttp.web_exceptions import HTTPError, HTTPNotModified
  16. from dateutil.parser import parse as parse_datetime
  17. from html2text import HTML2Text
  18. # Our modules
  19. import myanimebot.anilist as anilist
  20. import myanimebot.globals as globals
  21. import myanimebot.utils as utils
  22. import myanimebot.myanimelist as myanimelist
  23. from myanimebot.discord import send_embed_wrapper, build_embed
  24. if not sys.version_info[:2] >= (3, 7):
  25. print("ERROR: Requires python 3.7 or newer.")
  26. exit(1)
  27. # Main function that check the RSS feeds from MyAnimeList
  28. async def background_check_feed(asyncioloop):
  29. globals.logger.info("Starting up background_check_feed")
  30. # We configure the http header
  31. http_headers = { "User-Agent": "MyAnimeBot Discord Bot v" + globals.VERSION, }
  32. await globals.client.wait_until_ready()
  33. globals.logger.debug("Discord client connected, unlocking background_check_feed...")
  34. while not globals.client.is_closed():
  35. try:
  36. db_user = globals.conn.cursor(buffered=True, dictionary=True)
  37. db_user.execute("SELECT mal_user, servers FROM t_users WHERE service=%s", [globals.SERVICE_MAL])
  38. data_user = db_user.fetchone()
  39. except Exception as e:
  40. globals.logger.critical("Database unavailable! (" + str(e) + ")")
  41. quit()
  42. while data_user is not None:
  43. user = utils.User(id=None,
  44. service_id=None,
  45. name=data_user[globals.DB_USER_NAME],
  46. servers=data_user["servers"].split(','))
  47. stop_boucle = 0
  48. feed_type = 1
  49. try:
  50. while stop_boucle == 0 :
  51. try:
  52. async with aiohttp.ClientSession() as httpclient:
  53. if feed_type == 1 :
  54. http_response = await httpclient.request("GET", "https://myanimelist.net/rss.php?type=rm&u=" + user.name, headers=http_headers)
  55. media = "manga"
  56. else :
  57. http_response = await httpclient.request("GET", "https://myanimelist.net/rss.php?type=rw&u=" + user.name, headers=http_headers)
  58. media = "anime"
  59. except Exception as e:
  60. globals.logger.error("Error while loading RSS (" + str(feed_type) + ") of '" + user.name + "': " + str(e))
  61. break
  62. http_data = await http_response.read()
  63. feeds_data = feedparser.parse(http_data)
  64. for feed_data in feeds_data.entries:
  65. pubDateRaw = datetime.strptime(feed_data.published, '%a, %d %b %Y %H:%M:%S %z').astimezone(globals.timezone)
  66. pubDate = pubDateRaw.strftime("%Y-%m-%d %H:%M:%S")
  67. if feed_type == 1:
  68. media_type = utils.MediaType.MANGA
  69. else:
  70. media_type = utils.MediaType.ANIME
  71. feed = myanimelist.build_feed_from_data(feed_data, user, None, pubDateRaw.timestamp(), media_type)
  72. cursor = globals.conn.cursor(buffered=True)
  73. cursor.execute("SELECT published, title, url, type FROM t_feeds WHERE published=%s AND title=%s AND user=%s AND type=%s AND obsolete=0 AND service=%s", [pubDate, feed.media.name, user.name, feed.get_status_str(), globals.SERVICE_MAL])
  74. data = cursor.fetchone()
  75. if data is None:
  76. var = datetime.now(globals.timezone) - pubDateRaw
  77. globals.logger.debug(" - " + feed.media.name + ": " + str(var.total_seconds()))
  78. if var.total_seconds() < globals.secondMax:
  79. globals.logger.info(user.name + ": Item '" + feed.media.name + "' not seen, processing...")
  80. cursor.execute("SELECT thumbnail FROM t_animes WHERE guid=%s AND service=%s LIMIT 1", [feed.media.url, globals.SERVICE_MAL]) # TODO Change that ?
  81. data_img = cursor.fetchone()
  82. if data_img is None:
  83. try:
  84. image = myanimelist.get_thumbnail(feed.media.url)
  85. globals.logger.info("First time seeing this " + media + ", adding thumbnail into database: " + image)
  86. except Exception as e:
  87. globals.logger.warning("Error while getting the thumbnail: " + str(e))
  88. image = ""
  89. cursor.execute("INSERT INTO t_animes (guid, service, title, thumbnail, found, discoverer, media) VALUES (%s, %s, %s, %s, NOW(), %s, %s)", [feed.media.url, globals.SERVICE_MAL, feed.media.name, image, user.name, media])
  90. globals.conn.commit()
  91. else: image = data_img[0]
  92. feed.media.image = image
  93. cursor.execute("UPDATE t_feeds SET obsolete=1 WHERE published=%s AND title=%s AND user=%s AND service=%s", [pubDate, feed.media.name, user.name, globals.SERVICE_MAL])
  94. cursor.execute("INSERT INTO t_feeds (published, title, service, url, user, found, type) VALUES (%s, %s, %s, %s, %s, NOW(), %s)", (pubDate, feed.media.name, globals.SERVICE_MAL, feed.media.url, user.name, feed.get_status_str()))
  95. globals.conn.commit()
  96. for server in user.servers:
  97. db_srv = globals.conn.cursor(buffered=True)
  98. db_srv.execute("SELECT channel FROM t_servers WHERE server = %s", [server])
  99. data_channel = db_srv.fetchone()
  100. while data_channel is not None:
  101. for channel in data_channel: await send_embed_wrapper(asyncioloop, channel, globals.client, build_embed(feed))
  102. data_channel = db_srv.fetchone()
  103. if feed_type == 1:
  104. feed_type = 0
  105. await asyncio.sleep(globals.MYANIMELIST_SECONDS_BETWEEN_REQUESTS)
  106. else:
  107. stop_boucle = 1
  108. except Exception as e:
  109. globals.logger.exception("Error when parsing RSS for '" + user.name + "': \n")
  110. await asyncio.sleep(globals.MYANIMELIST_SECONDS_BETWEEN_REQUESTS)
  111. data_user = db_user.fetchone()
  112. async def fetch_activities_anilist():
  113. await anilist.check_new_activities()
  114. @globals.client.event
  115. async def on_ready():
  116. globals.logger.info("Logged in as " + globals.client.user.name + " (" + str(globals.client.user.id) + ")")
  117. globals.logger.info("Starting all tasks...")
  118. globals.task_feed = globals.client.loop.create_task(background_check_feed(globals.client.loop))
  119. globals.task_feed_anilist = globals.client.loop.create_task(anilist.background_check_feed(globals.client.loop))
  120. globals.task_thumbnail = globals.client.loop.create_task(update_thumbnail_catalog(globals.client.loop))
  121. globals.task_gameplayed = globals.client.loop.create_task(change_gameplayed(globals.client.loop))
  122. @globals.client.event
  123. async def on_error(event, *args, **kwargs):
  124. globals.logger.exception("Crap! An unknown Discord error occured...")
  125. def build_info_cmd_message(users, server, channels, filters : List[utils.Service]) -> str:
  126. ''' Build the corresponding message for the info command '''
  127. registered_channel = globals.client.get_channel(int(channels[0]["channel"]))
  128. # Store users
  129. mal_users = []
  130. anilist_users = []
  131. for user in users:
  132. # If user is part of the server, add it to the message
  133. if str(server.id) in user['servers'].split(','):
  134. try:
  135. user_service = utils.Service.from_str(user["service"])
  136. if user_service == utils.Service.MAL:
  137. mal_users.append(user[globals.DB_USER_NAME])
  138. elif user_service == utils.Service.ANILIST:
  139. anilist_users.append(user[globals.DB_USER_NAME])
  140. except NotImplementedError:
  141. pass # Nothing to do here
  142. if not mal_users and not anilist_users:
  143. return "No users registered on this server. Try to add one."
  144. else:
  145. message = 'Registered user(s) on **{}**\n\n'.format(server)
  146. if mal_users: # If not empty
  147. # Don't print if there is filters and MAL is not in them
  148. if not filters or (filters and utils.Service.MAL in filters):
  149. message += '**MyAnimeList** users:\n'
  150. message += '```{}```\n'.format(', '.join(mal_users))
  151. if anilist_users: # If not empty
  152. # Don't print if there is filters and MAL is not in them
  153. if not filters or (filters and utils.Service.ANILIST in filters):
  154. message += '**AniList** users:\n'
  155. message += '```{}```\n'.format(', '.join(anilist_users))
  156. message += 'Assigned channel : **{}**'.format(registered_channel)
  157. return message
  158. def get_service_filters_list(filters : str) -> List[utils.Service]:
  159. ''' Creates and returns a service filter list from a comma-separated string '''
  160. filters_list = []
  161. for filter in filters.split(','):
  162. try:
  163. filters_list.append(utils.Service.from_str(filter))
  164. except NotImplementedError:
  165. pass # Ignore incorrect filter
  166. return filters_list
  167. async def info_cmd(message, words):
  168. ''' Processes the command "info" and sends a message '''
  169. # Get filters if available
  170. filters = []
  171. if (len(words) >= 3): # If filters are specified
  172. filters = get_service_filters_list(words[2])
  173. server = message.guild
  174. if utils.is_server_in_db(server.id) == False:
  175. await message.channel.send("The server **{}** is not in our database.".format(server))
  176. else:
  177. users = utils.get_users()
  178. channels = utils.get_channels(server.id)
  179. if channels is None:
  180. await message.channel.send("No channel assigned for this bot on this server.")
  181. else:
  182. await message.channel.send(build_info_cmd_message(users, server, channels, filters))
  183. def check_user_name_validity(user_name: str, service : utils.Service) -> Tuple[bool, str]:
  184. """ Check if user_name exists on a specific service.
  185. Returns:
  186. - bool: True if user_name exists
  187. - str: Error string if the user does not exist
  188. """
  189. if service == utils.Service.MAL:
  190. try:
  191. # Ping user profile to check validity
  192. urllib.request.urlopen('{}{}'.format(globals.MAL_PROFILE_URL, user_name))
  193. except urllib.error.HTTPError as e:
  194. if (e.code == 404): # URL profile not found
  195. return False, "User **{}** doesn't exist on MyAnimeList!".format(user_name)
  196. else:
  197. globals.logger.warning("HTTP Code {} while trying to add user '{}' and checking its validity.".format(e.code, user_name))
  198. return False, "An error occured when we checked this username on MyAnimeList, maybe the website is down?"
  199. elif service == utils.Service.ANILIST:
  200. is_user_valid = anilist.check_username_validity(user_name)
  201. if is_user_valid == False:
  202. globals.logger.warning("No results returned while trying to add user '{}' and checking its validity.".format(user_name))
  203. return False, "User **{}** doesn't exist on AniList!".format(user_name)
  204. return True, None
  205. async def add_user_cmd(words, message):
  206. ''' Processes the command "add" and add a user to fetch the data for '''
  207. # Check if command is valid
  208. if len(words) != 4:
  209. if (len(words) < 4):
  210. return await message.channel.send("Usage: {} add **{}**/**{}** **username**".format(globals.prefix, globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  211. return await message.channel.send("Too many arguments! You have to specify only one username.")
  212. try:
  213. service = utils.Service.from_str(words[2])
  214. except NotImplementedError:
  215. return await message.channel.send('Incorrect service. Use **"{}"** or **"{}"** for example'.format(globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  216. user = words[3]
  217. server_id = str(message.guild.id)
  218. if(len(user) > 14):
  219. return await message.channel.send("Username too long!")
  220. try:
  221. # Check user validity
  222. is_valid, error_string = check_user_name_validity(user, service)
  223. if is_valid == False:
  224. return await message.channel.send(error_string)
  225. # Get user's servers
  226. user_servers = utils.get_user_servers(user, service)
  227. # User not present in database
  228. if user_servers is None:
  229. utils.insert_user_into_db(user, service, server_id)
  230. return await message.channel.send("**{}** added to the database for the server **{}**.".format(user, str(message.guild)))
  231. else: # User present in database
  232. is_server_present = server_id in user_servers.split(',')
  233. if is_server_present == True: # The user already has registered this server
  234. return await message.channel.send("User **{}** is already registered in our database for this server!".format(user))
  235. else:
  236. new_servers = '{},{}'.format(user_servers, server_id)
  237. utils.update_user_servers_db(user, service, new_servers)
  238. return await message.channel.send("**{}** added to the database for the server **{}**.".format(user, str(message.guild)))
  239. except Exception as e:
  240. globals.logger.warning("Error while adding user '{}' on server '{}': {}".format(user, message.guild, str(e)))
  241. return await message.channel.send("An unknown error occured while addind this user, the error has been logged.")
  242. async def delete_user_cmd(words, message):
  243. ''' Processes the command "delete" and remove a registered user '''
  244. # Check if command is valid
  245. if len(words) != 4:
  246. if (len(words) < 4):
  247. return await message.channel.send("Usage: {} delete **{}**/**{}** **username**".format(globals.prefix, globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  248. return await message.channel.send("Too many arguments! You have to specify only one username.")
  249. try:
  250. service = utils.Service.from_str(words[2])
  251. except NotImplementedError:
  252. return await message.channel.send('Incorrect service. Use **"{}"** or **"{}"** for example'.format(globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  253. user = words[3]
  254. server_id = str(message.guild.id)
  255. user_servers = utils.get_user_servers(user, service)
  256. # If user is not present in the database
  257. if user_servers is None:
  258. return await message.channel.send("The user **" + user + "** is not in our database for this server!")
  259. # Else if present, update the servers for this user
  260. srv_string = utils.remove_server_from_servers(server_id, user_servers)
  261. if srv_string is None: # Server not present in the user's servers
  262. return await message.channel.send("The user **" + user + "** is not in our database for this server!")
  263. if srv_string == "":
  264. utils.delete_user_from_db(user, service)
  265. else:
  266. utils.update_user_servers_db(user, service, srv_string)
  267. return await message.channel.send("**" + user + "** deleted from the database for this server.")
  268. @globals.client.event
  269. async def on_message(message):
  270. if message.author == globals.client.user: return
  271. words = message.content.split(" ")
  272. author = str('{0.author.mention}'.format(message))
  273. # A user is trying to get help
  274. if words[0] == globals.prefix:
  275. if len(words) > 1:
  276. if words[1] == "ping":
  277. await message.channel.send("pong")
  278. elif words[1] == "here":
  279. if message.author.guild_permissions.administrator:
  280. cursor = globals.conn.cursor(buffered=True)
  281. cursor.execute("SELECT server, channel FROM t_servers WHERE server=%s", [str(message.guild.id)])
  282. data = cursor.fetchone()
  283. if data is None:
  284. cursor.execute("INSERT INTO t_servers (server, channel) VALUES (%s,%s)", [str(message.guild.id), str(message.channel.id)])
  285. globals.conn.commit()
  286. await message.channel.send("Channel **" + str(message.channel) + "** configured for **" + str(message.guild) + "**.")
  287. else:
  288. if(data[1] == str(message.channel.id)): await message.channel.send("Channel **" + str(message.channel) + "** already in use for this server.")
  289. else:
  290. cursor.execute("UPDATE t_servers SET channel = %s WHERE server = %s", [str(message.channel.id), str(message.guild.id)])
  291. globals.conn.commit()
  292. await message.channel.send("Channel updated to: **" + str(message.channel) + "**.")
  293. cursor.close()
  294. else: await message.channel.send("Only server's admins can use this command!")
  295. elif words[1] == "add":
  296. await add_user_cmd(words, message)
  297. elif words[1] == "delete":
  298. await delete_user_cmd(words, message)
  299. elif words[1] == "stop":
  300. if message.author.guild_permissions.administrator:
  301. if (len(words) == 2):
  302. cursor = globals.conn.cursor(buffered=True)
  303. cursor.execute("SELECT server FROM t_servers WHERE server=%s", [str(message.guild.id)])
  304. data = cursor.fetchone()
  305. if data is None: await globals.client.send_message(message.channel, "The server **" + str(message.guild) + "** is not in our database.")
  306. else:
  307. cursor.execute("DELETE FROM t_servers WHERE server = %s", [message.guild.id])
  308. globals.conn.commit()
  309. await message.channel.send("Server **" + str(message.guild) + "** deleted from our database.")
  310. cursor.close()
  311. else: await message.channel.send("Too many arguments! Only type *stop* if you want to stop this bot on **" + message.guild + "**")
  312. else: await message.channel.send("Only server's admins can use this command!")
  313. elif words[1] == "info":
  314. await info_cmd(message, words)
  315. elif words[1] == "about": await message.channel.send(embed=discord.Embed(colour=0x777777, title="MyAnimeBot version " + globals.VERSION + " by Penta & lulu", description="This bot check the MyAnimeList and Anilist profiles for each user specified, and send a message if there is something new.\nMore help with the **" + globals.prefix + " help** command.\n\nCheck the GitHub page: https://github.com/Penta/MyAnimeBot").set_thumbnail(url=globals.iconBot))
  316. elif words[1] == "help": await message.channel.send(globals.HELP)
  317. elif words[1] == "top":
  318. if len(words) == 2:
  319. try:
  320. cursor = globals.conn.cursor(buffered=True)
  321. cursor.execute("SELECT * FROM v_Top")
  322. data = cursor.fetchone()
  323. if data is None: await message.channel.send("It seems that there is no statistics... (what happened?!)")
  324. else:
  325. topText = "**__Here is the global statistics of this bot:__**\n\n"
  326. while data is not None:
  327. topText += " - " + str(data[0]) + ": " + str(data[1]) + "\n"
  328. data = cursor.fetchone()
  329. cursor = globals.conn.cursor(buffered=True)
  330. cursor.execute("SELECT * FROM v_TotalFeeds")
  331. data = cursor.fetchone()
  332. topText += "\n***Total user entry***: " + str(data[0])
  333. cursor = globals.conn.cursor(buffered=True)
  334. cursor.execute("SELECT * FROM v_TotalAnimes")
  335. data = cursor.fetchone()
  336. topText += "\n***Total unique manga/anime***: " + str(data[0])
  337. await message.channel.send(topText)
  338. cursor.close()
  339. except Exception as e:
  340. globals.logger.warning("An error occured while displaying the global top: " + str(e))
  341. await message.channel.send("Unable to reply to your request at the moment...")
  342. elif len(words) > 2:
  343. keyword = str(' '.join(words[2:]))
  344. globals.logger.info("Displaying the global top for the keyword: " + keyword)
  345. try:
  346. cursor = globals.conn.cursor(buffered=True)
  347. cursor.callproc('sp_UsersPerKeyword', [str(keyword), '20'])
  348. for result in cursor.stored_results():
  349. data = result.fetchone()
  350. if data is None: await message.channel.send("It seems that there is no statistics for the keyword **" + keyword + "**.")
  351. else:
  352. topKeyText = "**__Here is the statistics for the keyword " + keyword + ":__**\n\n"
  353. while data is not None:
  354. topKeyText += " - " + str(data[0]) + ": " + str(data[1]) + "\n"
  355. data = result.fetchone()
  356. await message.channel.send(topKeyText)
  357. cursor.close()
  358. except Exception as e:
  359. globals.logger.warning("An error occured while displaying the global top for keyword '" + keyword + "': " + str(e))
  360. await message.channel.send("Unable to reply to your request at the moment...")
  361. elif words[1] == "group":
  362. if len(words) > 2:
  363. if message.author.guild_permissions.administrator:
  364. group = words[2]
  365. await message.channel.send("admin OK")
  366. else: await message.channel.send("Only server's admins can use this command!")
  367. else:
  368. await message.channel.send("You have to specify a group!")
  369. elif words[1] == "fetch-debug":
  370. await fetch_activities_anilist()
  371. # If mentioned
  372. elif globals.client.user in message.mentions:
  373. await message.channel.send(":heart:")
  374. # Get a random anime name and change the bot's activity
  375. async def change_gameplayed(asyncioloop):
  376. globals.logger.info("Starting up change_gameplayed")
  377. await globals.client.wait_until_ready()
  378. await asyncio.sleep(1)
  379. while not globals.client.is_closed():
  380. # Get a random anime name from the users' list
  381. cursor = globals.conn.cursor(buffered=True)
  382. cursor.execute("SELECT title FROM t_animes ORDER BY RAND() LIMIT 1")
  383. data = cursor.fetchone()
  384. anime = utils.truncate_end_show(data[0])
  385. # Try to change the bot's activity
  386. try:
  387. if data is not None: await globals.client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=anime))
  388. except Exception as e:
  389. globals.logger.warning("An error occured while changing the displayed anime title: " + str(e))
  390. cursor.close()
  391. # Do it every minute
  392. await asyncio.sleep(60)
  393. async def update_thumbnail_catalog(asyncioloop):
  394. globals.logger.info("Starting up update_thumbnail_catalog")
  395. while not globals.client.is_closed():
  396. await asyncio.sleep(43200)
  397. globals.logger.info("Automatic check of the thumbnail database on going...")
  398. reload = 0
  399. cursor = globals.conn.cursor(buffered=True)
  400. cursor.execute("SELECT guid, title, thumbnail FROM t_animes")
  401. data = cursor.fetchone()
  402. while data is not None:
  403. try:
  404. if (data[2] != "") : urllib.request.urlopen(data[2])
  405. else: reload = 1
  406. except urllib.error.HTTPError as e:
  407. globals.logger.warning("HTTP Error while getting the current thumbnail of '" + str(data[1]) + "': " + str(e))
  408. reload = 1
  409. except Exception as e:
  410. globals.logger.debug("Error while getting the current thumbnail of '" + str(data[1]) + "': " + str(e))
  411. if (reload == 1) :
  412. try:
  413. image = myanimelist.get_thumbnail(data[0])
  414. cursor.execute("UPDATE t_animes SET thumbnail = %s WHERE guid = %s", [image, data[0]])
  415. globals.conn.commit()
  416. globals.logger.info("Updated thumbnail found for \"" + str(data[1]) + "\": %s", image)
  417. except Exception as e:
  418. globals.logger.warning("Error while downloading updated thumbnail for '" + str(data[1]) + "': " + str(e))
  419. await asyncio.sleep(3)
  420. data = cursor.fetchone()
  421. cursor.close()
  422. globals.logger.info("Thumbnail database checked.")
  423. # Starting main function
  424. if __name__ == "__main__":
  425. try:
  426. globals.client.run(globals.token)
  427. except:
  428. logging.info("Closing all tasks...")
  429. globals.task_feed.cancel()
  430. globals.task_feed_anilist.cancel()
  431. globals.task_thumbnail.cancel()
  432. globals.task_gameplayed.cancel()
  433. globals.logger.critical("Script halted.")
  434. # We close all the ressources
  435. globals.conn.close()
  436. globals.log_cursor.close()
  437. globals.log_conn.close()