webhook.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # https://github.com/Derpolino/discord-webhooks-python/blob/master/discordWebhooks.py
  2. import requests
  3. import json
  4. import time
  5. now = time.time()
  6. # https://discordapp.com/developers/docs/resources/webhook#execute-webhook
  7. class Webhook():
  8. def __init__(self, url, **kwargs):
  9. self.url = url
  10. self.wh = {
  11. #"username": kwargs.get("username", None),
  12. #"avatar_url": kwargs.get("avatar_url", None),
  13. "content": None,
  14. "embeds": []
  15. }
  16. self.requests = requests.Session()
  17. def add_embed(self, embed):
  18. self.wh["embeds"].append(embed)
  19. def clear_embeds(self):
  20. self.wh["embeds"] = []
  21. def send(self, content=None, tts=False):
  22. self.wh["content"] = content
  23. self.wh["tts"] = tts
  24. #print(self.wh)
  25. #return True # BORRAR ESTO
  26. r = self.requests.post(self.url, json=self.wh)
  27. if "X-RateLimit-Remaining" in r.headers and int(r.headers["X-RateLimit-Remaining"]) <= 1:
  28. wait = int(r.headers["X-RateLimit-Reset"])-int(now)
  29. raise Exception("RateLimit {0}/{1}, reset in ~{2}s".format(r.headers["X-RateLimit-Remaining"], r.headers["X-RateLimit-Limit"], wait))
  30. """rl = "RateLimit {0}/{1}, reset in ~{2}s".format(r.headers["X-RateLimit-Remaining"], r.headers["X-RateLimit-Limit"], wait)
  31. if wait < 600:
  32. print(rl)
  33. time.sleep(wait+1)
  34. else:
  35. raise Exception(rl)"""
  36. if r.text != "":
  37. raise Exception("Webhook error: {0}".format(r.text))
  38. return True
  39. # https://discordapp.com/developers/docs/resources/channel#embed-object
  40. def embed(**kwargs):
  41. return {
  42. "title": kwargs.get("title", None),
  43. "description": kwargs.get("description", None),
  44. "url": kwargs.get("url", None),
  45. "color": kwargs.get("color", None),
  46. "image": kwargs.get("image", None),
  47. "thumbnail": kwargs.get("thumbnail", None),
  48. "footer": kwargs.get("footer", None),
  49. "fields": kwargs.get("fields", [])
  50. }
  51. def field(name, value, inline=False):
  52. return {
  53. "name": name,
  54. "value": value,
  55. "inline": inline
  56. }
  57. def image(url, w=50, h=50):
  58. return {
  59. "url": url,
  60. "width": w,
  61. "height": h
  62. }
  63. def thumbnail(url, w=50, h=50):
  64. return {
  65. "url": url,
  66. "width": w,
  67. "height": h
  68. }
  69. def footer(text, icon_url):
  70. return {
  71. "text": text,
  72. "icon_url": icon_url
  73. }
  74. __all__ = ["Webhook", "embed", "field", "footer"]