You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

136 lines
4.6KB

  1. # -*- coding: utf-8 -*-
  2. # MIT License
  3. #
  4. # Copyright (c) 2017-2018 Roxanne Gibson
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in all
  14. # copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. import random
  24. import argparse
  25. import discord
  26. from discord.ext import commands
  27. from roxbot import http, config, exceptions
  28. class ArgParser(argparse.ArgumentParser):
  29. """Create Roxbot's own version of ArgumentParser that doesn't exit the program on error."""
  30. def error(self, message):
  31. # By passing here, it will just continue in cases where a user inputs an arg that can't be parsed.
  32. pass
  33. async def danbooru_clone_api_req(channel, base_url, endpoint_url, cache=None, tags="", banned_tags="", sfw=False):
  34. """Utility function that deals with danbooru clone api interaction.
  35. It also deals with cache management for these interactions.
  36. Params
  37. =======
  38. channel: discord.Channel
  39. Channel command has been invoked in
  40. base_url: str
  41. Base url of the site
  42. endpoint_url: str
  43. Endpoint of images in the API. This is used if the API does not give this in its response.
  44. cache: dict (optional)
  45. Post cache. Were channel ID's are keys with values that are lists of identifiable info.
  46. Cache is handled in this function and will be updated so that other functions can access it.
  47. tags: str (optional)
  48. tags to use in the search. Separated by spaces.
  49. banned_tags: str (optional)
  50. banned tags to append to the search. Separated by spaces with a - in front to remove them from search results.
  51. """
  52. limit = "150"
  53. is_e621_site = bool("e621" in base_url or "e926" in base_url)
  54. if is_e621_site:
  55. banned_tags += " -cub" # Removes TOS breaking content from the search
  56. tags = tags + banned_tags
  57. if len(tags.split()) > 6:
  58. raise exceptions.UserError("Too many tags given for this site.")
  59. else:
  60. banned_tags += " -loli -shota -shotacon -lolicon -cub" # Removes TOS breaking content from the search
  61. tags = tags + banned_tags
  62. page_number = str(random.randrange(20))
  63. if "konachan" in base_url or is_e621_site:
  64. page = "&page="
  65. else:
  66. page = "&pid="
  67. url = base_url + tags + '&limit=' + limit + page + page_number
  68. if isinstance(channel, discord.DMChannel):
  69. cache_id = channel.id
  70. else:
  71. cache_id = channel.guild.id
  72. # IF ID is not in cache, create cache for ID
  73. if not cache.get(cache_id, False):
  74. cache[cache_id] = []
  75. posts = await http.api_request(url)
  76. if not posts:
  77. return None
  78. post = None
  79. while posts:
  80. index = random.randint(0, len(posts)-1)
  81. post = posts.pop(index)
  82. if sfw:
  83. if post["rating"] == "e" or post["rating"] == "q":
  84. continue
  85. md5 = post.get("md5") or post.get("hash")
  86. if md5 not in cache[cache_id]:
  87. cache[cache_id].append(md5)
  88. if len(cache[cache_id]) > 10:
  89. cache[cache_id].pop(0)
  90. break
  91. if not posts:
  92. return None
  93. url = post.get("file_url")
  94. if not url:
  95. url = endpoint_url + "{0[directory]}/{0[image]}".format(post)
  96. return url
  97. def has_permissions(ctx, **perms):
  98. """Copy of code from discord.py to work outside of wrappers"""
  99. ch = ctx.channel
  100. permissions = ch.permissions_for(ctx.author)
  101. missing = [perm for perm, value in perms.items() if getattr(permissions, perm, None) != value]
  102. if not missing:
  103. return True
  104. return False
  105. #raise commands.MissingPermissions(missing)
  106. def has_permissions_or_owner(ctx, **perms):
  107. if ctx.author.id == config["Roxbot"]["OwnerID"]:
  108. return True
  109. return has_permissions(ctx, **perms)