add_user.py 4.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import urllib
  2. import discord.ext.commands as discord_cmds
  3. from typing import Tuple
  4. import myanimebot.utils as utils
  5. import myanimebot.globals as globals
  6. import myanimebot.anilist as anilist
  7. import myanimebot.commands.permissions as permissions
  8. import myanimebot.commands.converters as converters
  9. def check_user_name_validity(user_name: str, service : utils.Service) -> Tuple[bool, str]:
  10. """ Check if user_name exists on a specific service.
  11. Returns:
  12. - bool: True if user_name exists
  13. - str: Error string if the user does not exist
  14. """
  15. if(len(user_name) > globals.USERNAME_MAX_LENGTH):
  16. return False, "Username too long!"
  17. if service == utils.Service.MAL:
  18. try:
  19. # Ping user profile to check validity
  20. urllib.request.urlopen('{}{}'.format(globals.MAL_PROFILE_URL, user_name))
  21. except urllib.error.HTTPError as e:
  22. if (e.code == 404): # URL profile not found
  23. return False, "User **{}** doesn't exist on MyAnimeList!".format(user_name)
  24. else:
  25. globals.logger.warning("HTTP Code {} while trying to add user '{}' and checking its validity.".format(e.code, user_name))
  26. return False, "An error occured when we checked this username on MyAnimeList, maybe the website is down?"
  27. elif service == utils.Service.ANILIST:
  28. is_user_valid = anilist.check_username_validity(user_name)
  29. if is_user_valid == False:
  30. globals.logger.warning("No results returned while trying to add user '{}' and checking its validity.".format(user_name))
  31. return False, "User **{}** doesn't exist on AniList!".format(user_name)
  32. return True, None
  33. @discord_cmds.command(name="add")
  34. @discord_cmds.check(permissions.in_allowed_role)
  35. async def add_user_cmd(ctx, service : converters.to_service, user : str):
  36. ''' Processes the command "add" and add a user to fetch the data for '''
  37. if user is None:
  38. return await ctx.send("Usage: {} add **{}**/**{}** **username**".format(globals.prefix, globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  39. elif service is None:
  40. return await ctx.send('Incorrect service. Use **"{}"** or **"{}"** for example'.format(globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  41. server = ctx.guild
  42. server_id = str(server.id)
  43. try:
  44. # Check user validity
  45. is_valid, error_string = check_user_name_validity(user, service)
  46. if is_valid == False:
  47. return await ctx.send(error_string)
  48. # Get user's servers
  49. user_servers = utils.get_user_servers(user, service)
  50. # User not present in database
  51. if user_servers is None:
  52. utils.insert_user_into_db(user, service, server_id)
  53. return await ctx.send("**{}** added to the database for the server **{}**.".format(user, server))
  54. else: # User present in database
  55. is_server_present = server_id in user_servers.split(',')
  56. if is_server_present == True: # The user already has registered this server
  57. return await ctx.send("User **{}** is already registered in our database for this server!".format(user))
  58. else:
  59. new_servers = '{},{}'.format(user_servers, server_id)
  60. utils.update_user_servers_db(user, service, new_servers)
  61. return await ctx.send("**{}** added to the database for the server **{}**.".format(user, server))
  62. except Exception as e:
  63. globals.logger.warning("Error while adding user '{}' on server '{}': {}".format(user, server, str(e)))
  64. return await ctx.send("An unknown error occured while addind this user, the error has been logged.")
  65. @add_user_cmd.error
  66. async def add_user_cmd_error(ctx, error):
  67. ''' Processes errors from add cmd '''
  68. if isinstance(error, discord_cmds.MissingRequiredArgument):
  69. return await ctx.send("Usage: {} add **{}**/**{}** **username**".format(globals.prefix, globals.SERVICE_MAL, globals.SERVICE_ANILIST))
  70. elif isinstance(error, discord_cmds.ConversionError):
  71. return await ctx.send('Incorrect service {}. Use **"{}"** or **"{}"** for example'.format(error.original, globals.SERVICE_MAL, globals.SERVICE_ANILIST))