2017-03-20 08:37:37 +01:00
|
|
|
import requests
|
|
|
|
import sys
|
|
|
|
import time
|
|
|
|
import json
|
2018-08-17 05:12:21 +02:00
|
|
|
import urllib
|
2017-12-29 18:40:32 +01:00
|
|
|
from titanembeds.utils import redis_store
|
2017-04-24 20:55:09 +02:00
|
|
|
from flask import request
|
2017-03-20 08:37:37 +01:00
|
|
|
|
|
|
|
_DISCORD_API_BASE = "https://discordapp.com/api/v6"
|
|
|
|
|
|
|
|
def json_or_text(response):
|
|
|
|
text = response.text
|
|
|
|
if response.headers['content-type'] == 'application/json':
|
|
|
|
return response.json()
|
|
|
|
return text
|
|
|
|
|
|
|
|
class DiscordREST:
|
|
|
|
def __init__(self, bot_token):
|
2017-04-22 14:10:46 +02:00
|
|
|
self.global_redis_prefix = "discordapiratelimit/"
|
2017-03-20 08:37:37 +01:00
|
|
|
self.bot_token = bot_token
|
2017-07-31 01:10:35 +02:00
|
|
|
self.user_agent = "TitanEmbeds (https://github.com/TitanEmbeds/Titan) Python/{} requests/{}".format(sys.version_info, requests.__version__)
|
2017-04-22 14:10:46 +02:00
|
|
|
|
2017-04-24 20:55:09 +02:00
|
|
|
def init_discordrest(self):
|
2017-04-22 14:10:46 +02:00
|
|
|
if not self._bucket_contains("global_limited"):
|
2019-01-15 00:21:02 +01:00
|
|
|
self._set_bucket("global_limited", "False")
|
2017-04-22 14:10:46 +02:00
|
|
|
self._set_bucket("global_limit_expire", 0)
|
|
|
|
|
|
|
|
def _get_bucket(self, key):
|
2017-12-29 18:44:10 +01:00
|
|
|
value = redis_store.get(self.global_redis_prefix + key)
|
|
|
|
if value:
|
2018-07-16 05:50:31 +02:00
|
|
|
value = value
|
2017-04-22 14:10:46 +02:00
|
|
|
return value
|
|
|
|
|
|
|
|
def _set_bucket(self, key, value):
|
2017-12-29 18:40:32 +01:00
|
|
|
return redis_store.set(self.global_redis_prefix + key, value)
|
2017-04-22 14:10:46 +02:00
|
|
|
|
|
|
|
def _bucket_contains(self, key):
|
2017-12-29 18:40:32 +01:00
|
|
|
return redis_store.exists(self.global_redis_prefix + key)
|
2017-03-20 08:37:37 +01:00
|
|
|
|
|
|
|
def request(self, verb, url, **kwargs):
|
|
|
|
headers = {
|
|
|
|
'User-Agent': self.user_agent,
|
|
|
|
'Authorization': 'Bot {}'.format(self.bot_token),
|
|
|
|
}
|
|
|
|
params = None
|
|
|
|
if 'params' in kwargs:
|
|
|
|
params = kwargs['params']
|
|
|
|
data = None
|
|
|
|
if 'data' in kwargs:
|
|
|
|
data = kwargs['data']
|
|
|
|
if 'json' in kwargs:
|
|
|
|
headers['Content-Type'] = 'application/json'
|
|
|
|
data = json.dumps(data)
|
|
|
|
|
|
|
|
for tries in range(5):
|
|
|
|
curepoch = time.time()
|
2017-04-22 14:10:46 +02:00
|
|
|
if self._get_bucket("global_limited") == "True":
|
2018-10-26 22:59:05 +02:00
|
|
|
time.sleep(int(float(self._get_bucket("global_limit_expire"))) - curepoch)
|
2017-03-20 08:37:37 +01:00
|
|
|
curepoch = time.time()
|
|
|
|
|
2018-02-11 04:34:53 +01:00
|
|
|
if self._bucket_contains(url) and float(int(self._get_bucket(url))) > curepoch:
|
2018-10-26 22:59:05 +02:00
|
|
|
time.sleep(int(self._get_bucket(url)) - curepoch)
|
2017-03-20 08:37:37 +01:00
|
|
|
|
|
|
|
url_formatted = _DISCORD_API_BASE + url
|
2018-08-17 05:12:21 +02:00
|
|
|
if data and "payload_json" in data:
|
|
|
|
if "Content-Type" in headers:
|
|
|
|
del headers["Content-Type"]
|
|
|
|
req = requests.request(verb, url_formatted, params=params, files=data, headers=headers)
|
|
|
|
else:
|
|
|
|
req = requests.request(verb, url_formatted, params=params, data=data, headers=headers)
|
2017-03-20 08:37:37 +01:00
|
|
|
|
|
|
|
remaining = None
|
|
|
|
if 'X-RateLimit-Remaining' in req.headers:
|
|
|
|
remaining = req.headers['X-RateLimit-Remaining']
|
|
|
|
if remaining == '0' and req.status_code != 429:
|
2017-04-22 14:10:46 +02:00
|
|
|
self._set_bucket(url, int(req.headers['X-RateLimit-Reset']))
|
2017-03-20 08:37:37 +01:00
|
|
|
|
|
|
|
if 300 > req.status_code >= 200:
|
2019-01-15 00:21:02 +01:00
|
|
|
self._set_bucket("global_limited", "False")
|
2017-03-20 08:37:37 +01:00
|
|
|
return {
|
|
|
|
'success': True,
|
|
|
|
'content': json_or_text(req),
|
|
|
|
'code': req.status_code,
|
|
|
|
}
|
|
|
|
|
|
|
|
if req.status_code == 429:
|
|
|
|
if 'X-RateLimit-Global' not in req.headers:
|
2017-04-22 14:10:46 +02:00
|
|
|
self._set_bucket(url, int(req.headers['X-RateLimit-Reset']))
|
2017-03-20 08:37:37 +01:00
|
|
|
else:
|
2019-01-15 00:21:02 +01:00
|
|
|
self._set_bucket("global_limited", "True")
|
2017-04-22 14:10:46 +02:00
|
|
|
self._set_bucket("global_limit_expire", time.time() + int(req.headers['Retry-After']))
|
2017-03-20 08:37:37 +01:00
|
|
|
|
|
|
|
if req.status_code == 502 and tries <= 5:
|
2018-10-26 22:59:05 +02:00
|
|
|
time.sleep(1 + tries * 2)
|
2017-03-20 08:37:37 +01:00
|
|
|
continue
|
|
|
|
|
|
|
|
if req.status_code == 403 or req.status_code == 404:
|
|
|
|
return {
|
|
|
|
'success': False,
|
|
|
|
'code': req.status_code,
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
'success': False,
|
|
|
|
'code': req.status_code,
|
|
|
|
'content': json_or_text(req),
|
|
|
|
}
|
|
|
|
|
2017-03-24 07:52:32 +01:00
|
|
|
#####################
|
|
|
|
# Channel
|
|
|
|
#####################
|
|
|
|
|
2018-08-17 05:12:21 +02:00
|
|
|
def create_message(self, channel_id, content, file=None):
|
2017-03-24 07:52:32 +01:00
|
|
|
_endpoint = "/channels/{channel_id}/messages".format(channel_id=channel_id)
|
|
|
|
payload = {'content': content}
|
2018-08-17 05:12:21 +02:00
|
|
|
if file:
|
|
|
|
payload = {"payload_json": (None, json.dumps(payload)), "file": (file.filename, file.read(), 'application/octet-stream')}
|
2017-03-24 07:52:32 +01:00
|
|
|
r = self.request("POST", _endpoint, data=payload)
|
|
|
|
return r
|
|
|
|
|
|
|
|
#####################
|
|
|
|
# Guild
|
|
|
|
#####################
|
|
|
|
|
2017-03-27 17:58:47 +02:00
|
|
|
def add_guild_member(self, guild_id, user_id, access_token, **kwargs):
|
|
|
|
_endpoint = "/guilds/{guild_id}/members/{user_id}".format(user_id=user_id, guild_id=guild_id)
|
|
|
|
payload = {'access_token': access_token}
|
|
|
|
payload.update(kwargs)
|
|
|
|
r = self.request("PUT", _endpoint, data=payload, json=True)
|
|
|
|
return r
|
|
|
|
|
2017-03-24 07:52:32 +01:00
|
|
|
def get_guild_embed(self, guild_id):
|
|
|
|
_endpoint = "/guilds/{guild_id}/embed".format(guild_id=guild_id)
|
|
|
|
r = self.request("GET", _endpoint)
|
|
|
|
return r
|
2018-07-08 22:31:36 +02:00
|
|
|
|
|
|
|
def get_guild_member(self, guild_id, user_id):
|
|
|
|
_endpoint = "/guilds/{guild_id}/members/{user_id}".format(guild_id=guild_id, user_id=user_id)
|
|
|
|
r = self.request("GET", _endpoint)
|
|
|
|
return r
|
2017-03-24 07:52:32 +01:00
|
|
|
|
|
|
|
def modify_guild_embed(self, guild_id, **kwargs):
|
|
|
|
_endpoint = "/guilds/{guild_id}/embed".format(guild_id=guild_id)
|
|
|
|
r = self.request("PATCH", _endpoint, data=kwargs, json=True)
|
|
|
|
return r
|
|
|
|
|
|
|
|
#####################
|
|
|
|
# Widget Handler
|
|
|
|
#####################
|
2017-03-20 08:37:37 +01:00
|
|
|
|
2017-03-24 07:52:32 +01:00
|
|
|
def get_widget(self, guild_id):
|
|
|
|
_endpoint = _DISCORD_API_BASE + "/servers/{guild_id}/widget.json".format(guild_id=guild_id)
|
|
|
|
embed = self.get_guild_embed(guild_id)
|
2017-09-07 02:59:22 +02:00
|
|
|
if not embed.get("success", True):
|
|
|
|
return {"success": False}
|
2017-03-24 07:52:32 +01:00
|
|
|
if not embed['content']['enabled']:
|
|
|
|
self.modify_guild_embed(guild_id, enabled=True, channel_id=guild_id)
|
|
|
|
widget = requests.get(_endpoint).json()
|
|
|
|
return widget
|
2017-07-01 08:52:21 +02:00
|
|
|
|
|
|
|
|
|
|
|
#####################
|
|
|
|
# Webhook
|
|
|
|
#####################
|
|
|
|
|
2017-08-27 23:41:36 +02:00
|
|
|
def create_webhook(self, channel_id, name, avatar=None):
|
|
|
|
_endpoint = "/channels/{channel_id}/webhooks".format(channel_id=channel_id)
|
|
|
|
payload = {
|
|
|
|
"name": name,
|
|
|
|
}
|
|
|
|
if avatar:
|
|
|
|
payload["avatar"] = avatar
|
|
|
|
r = self.request("POST", _endpoint, data=payload, json=True)
|
|
|
|
return r
|
|
|
|
|
2018-08-17 05:12:21 +02:00
|
|
|
def execute_webhook(self, webhook_id, webhook_token, username, avatar, content, file=None, wait=True):
|
2017-07-01 08:52:21 +02:00
|
|
|
_endpoint = "/webhooks/{id}/{token}".format(id=webhook_id, token=webhook_token)
|
|
|
|
if wait:
|
|
|
|
_endpoint += "?wait=true"
|
|
|
|
payload = {
|
|
|
|
'content': content,
|
|
|
|
'avatar_url': avatar,
|
|
|
|
'username': username
|
|
|
|
}
|
2018-08-17 05:12:21 +02:00
|
|
|
if file:
|
|
|
|
payload = {"payload_json": (None, json.dumps(payload)), "file": (file.filename, file.read(), 'application/octet-stream')}
|
2017-07-01 08:52:21 +02:00
|
|
|
r = self.request("POST", _endpoint, data=payload)
|
2017-08-27 23:41:36 +02:00
|
|
|
return r
|
|
|
|
|
|
|
|
def delete_webhook(self, webhook_id, webhook_token):
|
|
|
|
_endpoint = "/webhooks/{id}/{token}".format(id=webhook_id, token=webhook_token)
|
|
|
|
r = self.request("DELETE", _endpoint)
|
2019-01-15 00:21:02 +01:00
|
|
|
return r
|