-
Notifications
You must be signed in to change notification settings - Fork 0
/
EmoteImgify.py
319 lines (267 loc) · 11.4 KB
/
EmoteImgify.py
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import os
import requests
import discord
from discord.ext import commands
from keep_alive import keep_alive
redirect_uri = 'http://localhost'
twitch_token_auth_url = 'https://id.twitch.tv/oauth2/token'
twitch_users_api = 'https://api.twitch.tv/helix/users'
twitch_validate_api = 'https://id.twitch.tv/oauth2/validate'
twitch_emote_api = 'https://api.twitch.tv/helix/chat/emotes'
bttv_user_api = 'https://api.betterttv.net/3/cached/users/twitch/'
ffz_user_api = 'https://api.frankerfacez.com/v1/room/id/'
twitch_global_emote_api = 'https://api.twitch.tv/helix/chat/emotes/global'
bttv_global_emotes = 'https://api.betterttv.net/3/cached/emotes/global'
ffz_global_emote_api = 'https://api.frankerfacez.com/v1/set/global'
twitch_animated_emote_url = lambda emote_id: 'https://static-cdn.jtvnw.net/emoticons/v2/' + emote_id + '/default/dark/3.0'
bttv_emote_url = lambda emote_id: 'https://cdn.betterttv.net/emote/' + emote_id + '/3x'
class BotClient(commands.Bot):
client_id = os.getenv("TWITCH_CLIENT_ID")
client_secret = os.getenv("TWITCH_CLIENT_SECRET")
def get_twitch_app_access_token(self):
"""Makes a call to Twitch authentication API to get an app access token
Uses client id and client secret from hidden token environment variables
Sets instance variable of access_token to the app access token from the API response
Returns: Boolean indicating whether the API request failed or succeeded
"""
auth_header = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'client_credentials'
}
response = requests.post(twitch_token_auth_url, data=auth_header)
response_dict = response.json()
self.access_token = response_dict['access_token']
self.token_header = {
'Authorization': 'Bearer ' + self.access_token,
'Client-Id': self.client_id
}
print(response_dict)
return response.ok
def validate_access_token(self):
"""Validates that the app access token has not yet expired,
if access token has expired, grabs a new one
Returns: None
"""
token_header = {'Authorization': 'OAuth ' + self.access_token}
response = requests.get(twitch_validate_api, headers=token_header)
if response.ok:
return
self.get_twitch_app_access_token()
def get_channelID(self, channel_name):
"""Makes a call to Twitch API to get an user's channel ID from their name
Param channel_name: The channel name of the user to lookup (String)
Returns: The app access token from the API response (String)
"""
user_param = {'login': channel_name}
response = requests.get(twitch_users_api,
params=user_param,
headers=self.token_header)
response_dict = response.json()['data'][0]
channel_id = response_dict['id']
return channel_id
def get_twitch_emoteURL(self, channel_id, emote_name):
"""Makes a call to Twitch API to get a channel's emote from a specific emote name
Param channel_id: The unique identifier of the channel (String)
Param emote_name: The name of the emote (String)
Returns: URL to display requested emote (String)
"""
param = {'broadcaster_id': channel_id}
response = requests.get(twitch_emote_api,
params=param,
headers=self.token_header)
response_list = response.json()['data']
for dicts in response_list:
if (dicts['name'].lower() == emote_name.lower()):
if (dicts['id'].startswith('emotesv2_')):
url = twitch_animated_emote_url(dicts['id'])
else:
url = dicts['images']['url_4x']
return url
return None
def get_bttv_emoteURL(self, channel_id, emote_name):
"""Makes a call to BetterTTV API to get a channel's emote from a specific emote name
Param channel_id: The unique identifier of the channel (String)
Param emote_name: The name of the emote (String)
Returns: URL to display requested emote (String)
"""
response = requests.get(bttv_user_api + channel_id)
channel_emotes = response.json()['channelEmotes']
shared_emotes = response.json()['sharedEmotes']
for emotes in channel_emotes:
if (emotes['code'].lower() == emote_name.lower()):
url = bttv_emote_url(emotes['id'])
if (emotes['imageType'] == 'gif'):
url += '.gif'
return url
for emotes in shared_emotes:
if (emotes['code'].lower() == emote_name.lower()):
url = bttv_emote_url(emotes['id'])
if (emotes['imageType'] == 'gif'):
url += '.gif'
return url
return None
def get_ffz_emoteURL(self, channel_id, emote_name):
"""Makes a call to FrankerFaceZ API to get a channel's emote from a specific emote name
Param channel_id: The unique identifier of the channel (String)
Param emote_name: The name of the emote (String)
Returns: URL to display requested emote (String)
"""
response = requests.get(ffz_user_api + channel_id)
response_json = response.json()
for sets in response_json['sets'].values():
for emotes in sets['emoticons']:
if (emotes['name'].lower() == emote_name.lower()):
url = 'https:' + emotes['urls'][max(emotes['urls'], key=int)]
return url
return None
def get_twitch_global_emoteURL(self, emote_name):
"""Makes a call to Twitch API to get a global emote from an emote name
Param emote_name: The name of the emote (String)
Returns: URL to display requested emote (String)
"""
response = requests.get(twitch_global_emote_api,
headers=self.token_header)
response_list = response.json()['data']
for dicts in response_list:
if (dicts['name'].lower() == emote_name.lower()):
if (dicts['id'].startswith('emotesv2_')):
url = twitch_animated_emote_url(dicts['id'])
else:
url = dicts['images']['url_4x']
return url
return None
def get_bttv_global_emoteURL(self, emote_name):
"""Makes a call to BetterTTV API to get a global emote from an emote name
Param emote_name: The name of the emote (String)
Returns: URL to display requested emote (String)
"""
emote_set = requests.get(bttv_global_emotes).json()
for emotes in emote_set:
if (emotes['code'].lower() == emote_name.lower()):
return bttv_emote_url(emotes['id'])
return None
def get_ffz_global_emoteURL(self, emote_name):
"""Makes a call to FrankerFaceZ API to get a global emote from an emote name
Param emote_name: The name of the emote (String)
Returns: URL to display requested emote (String)
"""
response = requests.get(ffz_global_emote_api)
response_json = response.json()
for sets in response_json['sets'].values():
for emotes in sets['emoticons']:
if (emotes['name'].lower() == emote_name.lower()):
url = 'https:' + emotes['urls'][max(emotes['urls'], key=int)]
return url
return None
cmd_prefix = '^'
client = BotClient(command_prefix=cmd_prefix, help_command=None)
@client.event
async def on_ready():
print('Logged on as {0}!'.format(client.user))
@client.event
async def on_connect():
act = discord.Streaming(name="Do ^help", url="https://twitch.tv/dextinfire")
await client.change_presence(activity=act)
client.get_twitch_app_access_token()
@client.command()
async def emote(ctx, channel_name, emote_name):
client.validate_access_token()
print("Channel Name: " + channel_name + " Emote Name: " + emote_name)
channel_id = client.get_channelID(channel_name)
print("Channel ID: " + channel_id)
emote_URL = client.get_twitch_emoteURL(channel_id, emote_name)
if(emote_URL == None):
emote_URL = client.get_bttv_emoteURL(channel_id, emote_name)
if(emote_URL == None):
emote_URL = client.get_ffz_emoteURL(channel_id, emote_name)
response_string = emote_URL if emote_URL else "Emote cannot be found"
await ctx.send(response_string)
@client.command(aliases=['global'])
async def _global(ctx, emote_name):
client.validate_access_token()
print("Emote Name: " + emote_name)
emote_URL = client.get_twitch_global_emoteURL(emote_name)
if(emote_URL == None):
emote_URL = client.get_bttv_global_emoteURL(emote_name)
if(emote_URL == None):
emote_URL = client.get_ffz_global_emoteURL(emote_name)
response_string = emote_URL if emote_URL else "Emote cannot be found"
await ctx.send(response_string)
@client.command()
async def help(ctx):
helpArr = [
['^help',
'',
'-Shows this command!'],
['^emote',
'<Channel> <Emote>',
'-Grab an emote for Twitch channel and sends as an image. Supports sub emotes, BTTV, and FFZ.'],
['^global',
'<Emote>',
'-Grab an emote from global list and send it as an image. Supports Twitch emotes, BTTV, and FFZ.'],
['^join',
'',
'-Joins a voice channel'],
['^leave',
'',
'-Leaves a voice channel']]
helpStr = "```"
for row in helpArr:
helpStr += "{: <8} {: <20} {: <20}\n".format(*row)
helpStr += "```"
await ctx.send(helpStr)
@client.command()
async def join(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if(voice == None):
channel = ctx.author.voice.channel
if(channel != None):
if(channel.permissions_for(ctx.guild.me).connect):
await ctx.send('Joining channel: '+ channel.name)
await channel.connect()
else:
await ctx.send('No permission to join channel: ' + channel.name)
else:
await ctx.send('Please join a voice channel first!')
else:
await ctx.send('I\'m already connected to a voice channel!')
@client.command()
async def leave(ctx):
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if(voice != None):
await ctx.send('Left channel: '+ voice.channel.name)
return await voice.disconnect()
return await ctx.send("I am not connected to any voice channel on this server!")
@emote.error
async def emote_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
message = "Requires both channel name and emote name (in that order)"
else:
message = "Unknown error occured with command!"
raise error
await ctx.send(message, delete_after=5)
await ctx.message.delete(delay=5)
@_global.error
async def global_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
message = "Missing emote name"
else:
message = "Unknown error occured with command!"
raise error
await ctx.send(message, delete_after=5)
await ctx.message.delete(delay=5)
@join.error
async def join_error(ctx, error):
message = "An error occured!"
raise error
await ctx.send(message, delete_after=5)
await ctx.message.delete(delay=5)
@leave.error
async def leave_error(ctx, error):
message = "An error occured!"
raise error
await ctx.send(message, delete_after=5)
await ctx.message.delete(delay=5)
keep_alive()
client.run(os.getenv("DISCORD_TOKEN"))