-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathapi_client.py
More file actions
190 lines (166 loc) · 6.76 KB
/
api_client.py
File metadata and controls
190 lines (166 loc) · 6.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
from functools import cached_property
from typing import Union
import requests
from requests import HTTPError
_BASE_ENDPOINT_URI = 'https://discord.com/api/v10'
class MissingBotToken(Exception):
def __init__(self) -> None:
super().__init__('You need to provide the Bot Access Token into DiscordClient initialization')
class UnathorizedOperation(Exception):
pass
class DiscordAppClient:
def __init__(self, access_token: str):
self._access_token = access_token
@cached_property
def current_user(self):
headers = {
'Authorization': f'Bearer {self._access_token}'
}
r = requests.get(f'{_BASE_ENDPOINT_URI}/users/@me', headers=headers)
r.raise_for_status()
discord_user_dict = r.json()
return discord_user_dict
class DiscordBotClient:
def __init__(self, bot_token: str):
self._bot_token = bot_token
def get_dm_channel(self, discord_user_id: str):
"""
Reference: https://discord.com/developers/docs/resources/user#create-dm
"""
headers = {
'Authorization': f'Bot {self._bot_token}'
}
r = requests.post(
f'{_BASE_ENDPOINT_URI}/users/@me/channels',
headers=headers,
json={'recipient_id': discord_user_id}
)
r.raise_for_status()
dm_channel = r.json()
return dm_channel
def create_message(self, channel_id: str, msg: str) -> dict:
"""
Reference: https://discord.com/developers/docs/resources/channel#create-message
"""
headers = {
'Authorization': f'Bot {self._bot_token}'
}
r = requests.post(
f'{_BASE_ENDPOINT_URI}/channels/{channel_id}/messages',
headers=headers,
json={'content': msg}
)
r.raise_for_status()
message = r.json()
return message
def get_member(self, discord_user_id: str):
headers = {
'Authorization': f'Bot {self._bot_token}'
}
r = requests.get(f'{_BASE_ENDPOINT_URI}/users/{discord_user_id}', headers=headers)
r.raise_for_status()
discord_user_dict = r.json()
return discord_user_dict
def list_guild_members(self, guild_id, limit=100, after=0) -> dict:
"""
:param guild_id: the discord server id
"""
headers = {
'Authorization': f'Bot {self._bot_token}'
}
params = {'limit': limit, 'after': after}
r = requests.get(
f'{_BASE_ENDPOINT_URI}/guilds/{guild_id}/members',
params=params,
headers=headers)
try:
r.raise_for_status()
except HTTPError as error:
if error.response.status_code == 403:
raise UnathorizedOperation(
f"You have no permission to list member of Guild with id {guild_id}"
f"\nCheck if Guild id is right and you have added your Discord bot on Guild"
) from error
else:
return r.json()
def remove_guild_member(self, guild_id, user_id):
headers = {
'Authorization': f'Bot {self._bot_token}'
}
r = requests.delete(
f'{_BASE_ENDPOINT_URI}/guilds/{guild_id}/members/{user_id}',
headers=headers)
try:
r.raise_for_status()
except HTTPError as error:
if error.response.status_code == 403:
raise UnathorizedOperation(
f"You have no permission to remove member {user_id} of Guild with id {guild_id}"
f"\nCheck if Guild id is right and you have added your Discord bot on Guild"
"\nAlso check that Bot has role bigger than the member you want to kick. Check more info on:"
"\nhttps://discord.com/developers/docs/topics/permissions#permission-hierarchy"
) from error
def send_user_message(self, user_id: str, message: str):
"""
This is only a shortcut for sending a message to a user
It calls get_dm_channel function to get a discord bot channel and after that
it calls create_message function to send a message to a user
"""
dm_channel = self.get_dm_channel(user_id)
return self.create_message(dm_channel['id'], message)
class DiscordAppAndBotClient(DiscordAppClient, DiscordBotClient):
def __init__(self, access_token: str, bot_token: str):
DiscordAppClient.__init__(self, access_token)
DiscordBotClient.__init__(self, bot_token)
def add_guild_member(self, guild_id) -> dict:
"""
:param guild_id: the discord server id
:return: a dict representing guild's member
If user is already on guild, return a member dict but only with user data.
"""
current_user = self.current_user
headers = {
'Authorization': f'Bot {self._bot_token}'
}
data = {'access_token': self._access_token}
user_id = current_user['id']
r = requests.put(
f'{_BASE_ENDPOINT_URI}/guilds/{guild_id}/members/{user_id}',
json=data,
headers=headers)
try:
r.raise_for_status()
except HTTPError as error:
if error.response.status_code == 403:
raise UnathorizedOperation(
f"You have no permission to add user with id {user_id} on Guild if id {guild_id}"
f"\nCheck if Guild id is right and you have added your Discord bot on Guild"
) from error
if r.status_code == 204:
return {'user': current_user}
elif r.status_code == 201:
return r.json()
class DiscordCredentials:
def __init__(self, app_client_id: str, app_client_secret: str, redirect_uri: str, bot_token=None):
self._bot_token = bot_token
self._app_client_id = app_client_id
self._app_client_secret = app_client_secret
self._redirect_uri = redirect_uri
def generate_api_client(self, autorization_code: str) -> Union[DiscordAppClient, DiscordAppAndBotClient]:
data = {
'client_id': self._app_client_id,
'client_secret': self._app_client_secret,
'grant_type': 'authorization_code',
'code': autorization_code,
'redirect_uri': self._redirect_uri
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
r = requests.post(f'{_BASE_ENDPOINT_URI}/oauth2/token', data=data, headers=headers)
r.raise_for_status()
oauth2_data = r.json()
access_token = oauth2_data['access_token']
if self._bot_token is None:
return DiscordAppClient(access_token)
return DiscordAppAndBotClient(access_token, self._bot_token)