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.

122 lines
3.8KB

  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 json
  24. import aiohttp
  25. async def request(url, *, headers=None, **kwargs):
  26. """Base GET request in case you need more control over GET requests.
  27. Params
  28. =======
  29. headers: dict (Optional)
  30. kwarg: kwargs (Optional)
  31. Returns
  32. =======
  33. Response: aiohttp Response object
  34. """
  35. async with aiohttp.ClientSession() as session:
  36. return await session.get(url, headers=headers, **kwargs)
  37. async def api_request(url, *, headers=None, **kwargs):
  38. """Returns JSON from an API request. Should be used for all Roxbot API requests.
  39. Params
  40. =======
  41. url: str
  42. headers: dict (Optional)
  43. kwargs: kwargs (Optional)
  44. Returns
  45. =======
  46. JSON response: dict
  47. """
  48. if headers is None:
  49. headers = {'User-agent': 'RoxBot Discord Bot'}
  50. else:
  51. headers = {'User-agent': 'RoxBot Discord Bot', **headers}
  52. async with aiohttp.ClientSession() as session:
  53. async with session.get(url, headers=headers, **kwargs) as resp:
  54. try:
  55. output = await resp.text()
  56. return json.loads(output)
  57. except json.JSONDecodeError:
  58. return None
  59. async def download_file(url, filename=None):
  60. """Downloads the file at the given url and then saves it under the filename given to disk.
  61. Params
  62. =======
  63. url: str
  64. filename: str (Optional)
  65. if not given, the function will try and determine filename from url.
  66. Returns
  67. =======
  68. filename: str
  69. Handy if no filename given
  70. """
  71. if filename is None:
  72. filename = url.split("/")[-1].split("?")[0]
  73. async with aiohttp.ClientSession() as session:
  74. async with session.get(url, headers={'User-agent': 'RoxBot Discord Bot'}) as data:
  75. with open(filename, 'wb') as f:
  76. f.write(await data.read())
  77. return filename
  78. async def upload_file(url, file):
  79. """Uploads a file using a POST request. Broke for pomf clones so idk. Might have to revert it to requests.
  80. :param url: url to POST to.
  81. :param file: Byes-like object to upload.
  82. :return:
  83. """
  84. async with aiohttp.ClientSession() as session:
  85. payload = {"files": open(file, "rb")}
  86. resp = await session.post(url, headers={'User-agent': 'RoxBot Discord Bot', "content_type": "multipart/form-data"}, data=payload)
  87. return await resp.json()
  88. async def get_page(url, *, headers=None, **kwargs):
  89. """Returns the html of the given url. Will need to run it through BS4 to parse it.
  90. Params
  91. =======
  92. url: str
  93. Returns
  94. =======
  95. HTML Page: str
  96. """
  97. async with aiohttp.ClientSession() as session:
  98. async with session.get(url, headers=headers, **kwargs) as page:
  99. return await page.text()