Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/twitchio/rewards.py
7813 views
1
# -*- coding: utf-8 -*-
2
3
"""
4
The MIT License (MIT)
5
6
Copyright (c) 2017-2021 TwitchIO
7
8
Permission is hereby granted, free of charge, to any person obtaining a
9
copy of this software and associated documentation files (the "Software"),
10
to deal in the Software without restriction, including without limitation
11
the rights to use, copy, modify, merge, publish, distribute, sublicense,
12
and/or sell copies of the Software, and to permit persons to whom the
13
Software is furnished to do so, subject to the following conditions:
14
15
The above copyright notice and this permission notice shall be included in
16
all copies or substantial portions of the Software.
17
18
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24
DEALINGS IN THE SOFTWARE.
25
"""
26
27
import datetime
28
from typing import Optional, TYPE_CHECKING
29
30
from .errors import HTTPException, Unauthorized
31
32
if TYPE_CHECKING:
33
from .http import TwitchHTTP
34
from .user import PartialUser
35
36
37
__all__ = "CustomReward", "CustomRewardRedemption"
38
39
40
class CustomReward:
41
"""
42
Represents a Custom Reward object, as given by the api. Use :func:`User.get_custom_rewards` to fetch these
43
"""
44
45
__slots__ = (
46
"_http",
47
"_channel",
48
"id",
49
"image",
50
"background_color",
51
"enabled",
52
"cost",
53
"title",
54
"prompt",
55
"input_required",
56
"max_per_stream",
57
"max_per_user_stream",
58
"cooldown",
59
"paused",
60
"in_stock",
61
"redemptions_skip_queue",
62
"redemptions_current_stream",
63
"cooldown_until",
64
"_broadcaster_id",
65
)
66
67
def __init__(self, http: "TwitchHTTP", obj: dict, channel: "PartialUser"):
68
self._http = http
69
self._channel = channel
70
71
try:
72
self._broadcaster_id = obj["broadcaster_id"]
73
except KeyError:
74
self._broadcaster_id = obj["channel_id"]
75
76
self.id = obj["id"]
77
self.image = obj["image"]["url_1x"] if obj["image"] else obj["default_image"]["url_1x"]
78
self.background_color = obj["background_color"]
79
self.enabled = obj["is_enabled"]
80
self.cost = obj["cost"]
81
self.title = obj["title"]
82
self.prompt = obj["prompt"]
83
self.input_required = obj["is_user_input_required"]
84
85
try:
86
self.max_per_stream = (
87
obj["max_per_stream_setting"]["is_enabled"],
88
obj["max_per_stream_setting"]["max_per_stream"],
89
)
90
self.max_per_user_stream = (
91
obj["max_per_user_per_stream_setting"]["is_enabled"],
92
obj["max_per_user_per_stream_setting"]["max_per_user_per_stream"],
93
)
94
self.cooldown = (
95
obj["global_cooldown_setting"]["is_enabled"],
96
obj["global_cooldown_setting"]["global_cooldown_seconds"],
97
)
98
except KeyError:
99
self.max_per_stream = (obj["max_per_stream"]["is_enabled"], obj["max_per_stream"]["max_per_stream"])
100
self.max_per_user_stream = (
101
obj["max_per_user_per_stream"]["is_enabled"],
102
obj["max_per_user_per_stream"]["max_per_user_per_stream"],
103
)
104
self.cooldown = (
105
obj["global_cooldown"]["is_enabled"],
106
obj["global_cooldown"]["global_cooldown_seconds"],
107
)
108
109
self.paused = obj["is_paused"]
110
self.in_stock = obj["is_in_stock"]
111
self.redemptions_skip_queue = obj["should_redemptions_skip_request_queue"]
112
self.redemptions_current_stream = obj["redemptions_redeemed_current_stream"]
113
self.cooldown_until = obj["cooldown_expires_at"]
114
115
async def edit(
116
self,
117
token: str,
118
title: str = None,
119
prompt: str = None,
120
cost: int = None,
121
background_color: str = None,
122
enabled: bool = None,
123
input_required: bool = None,
124
max_per_stream_enabled: bool = None,
125
max_per_stream: int = None,
126
max_per_user_per_stream_enabled: bool = None,
127
max_per_user_per_stream: int = None,
128
global_cooldown_enabled: bool = None,
129
global_cooldown: int = None,
130
paused: bool = None,
131
redemptions_skip_queue: bool = None,
132
):
133
"""
134
Edits the reward. Note that apps can only modify rewards they have made.
135
136
Parameters
137
-----------
138
token: the bearer token for the channel of the reward
139
title: the new title of the reward
140
prompt: the new prompt for the reward
141
cost: the new cost for the reward
142
background_color: the new background color for the reward
143
enabled: whether the reward is enabled or not
144
input_required: whether user input is required or not
145
max_per_stream_enabled: whether the stream limit should be enabled
146
max_per_stream: how many times this can be redeemed per stream
147
max_per_user_per_stream_enabled: whether the user stream limit should be enabled
148
max_per_user_per_stream: how many times a user can redeem this reward per stream
149
global_cooldown_enabled: whether the global cooldown should be enabled
150
global_cooldown: how many seconds the global cooldown should be
151
paused: whether redemptions on this reward should be paused or not
152
redemptions_skip_queue: whether redemptions skip the request queue or not
153
154
Returns
155
--------
156
:class:`CustomReward` itself.
157
"""
158
159
try:
160
data = await self._http.update_reward(
161
token,
162
self._broadcaster_id,
163
self.id,
164
title,
165
prompt,
166
cost,
167
background_color,
168
enabled,
169
input_required,
170
max_per_stream_enabled,
171
max_per_stream,
172
max_per_user_per_stream_enabled,
173
max_per_user_per_stream,
174
global_cooldown_enabled,
175
global_cooldown,
176
paused,
177
redemptions_skip_queue,
178
)
179
except Unauthorized as error:
180
raise Unauthorized("The given token is invalid", "", 401) from error
181
except HTTPException as error:
182
status = error.args[2]
183
if status == 403:
184
raise HTTPException(
185
"The custom reward was created by a different application, or channel points are "
186
"not available for the broadcaster (403)",
187
error.args[1],
188
403,
189
) from error
190
raise
191
else:
192
for reward in data["data"]:
193
if reward["id"] == self.id:
194
self.__init__(self._http, reward, self._channel)
195
break
196
197
return self
198
199
async def delete(self, token: str):
200
"""
201
Deletes the custom reward
202
203
Parameters
204
----------
205
token:
206
:class:`str` the oauth token of the target channel
207
208
Returns
209
--------
210
None
211
"""
212
try:
213
await self._http.delete_custom_reward(token, self._broadcaster_id, self.id)
214
except Unauthorized as error:
215
raise Unauthorized("The given token is invalid", "", 401) from error
216
except HTTPException as error:
217
status = error.args[2]
218
if status == 403:
219
raise HTTPException(
220
"The custom reward was created by a different application, or channel points are "
221
"not available for the broadcaster (403)",
222
error.args[1],
223
403,
224
) from error
225
raise
226
227
async def get_redemptions(self, token: str, status: str, sort: str = None):
228
"""
229
Gets redemptions for this reward
230
231
Parameters
232
-----------
233
token:
234
:class:`str` the oauth token of the target channel
235
status:
236
:class:`str` one of UNFULFILLED, FULFILLED or CANCELED
237
sort:
238
:class:`str` the order redemptions are returned in. One of OLDEST, NEWEST. Default: OLDEST.
239
"""
240
try:
241
data = await self._http.get_reward_redemptions(
242
token, self._broadcaster_id, self.id, status=status, sort=sort
243
)
244
except Unauthorized as error:
245
raise Unauthorized("The given token is invalid", "", 401) from error
246
except HTTPException as error:
247
status = error.args[2]
248
if status == 403:
249
raise HTTPException(
250
"The custom reward was created by a different application, or channel points are "
251
"not available for the broadcaster (403)",
252
error.args[1],
253
403,
254
) from error
255
raise
256
else:
257
return [CustomRewardRedemption(x, self._http, self) for x in data["data"]]
258
259
260
class CustomRewardRedemption:
261
262
__slots__ = "_http", "_broadcaster_id", "id", "user_id", "user_name", "input", "status", "redeemed_at", "reward"
263
264
def __init__(self, obj: dict, http: "TwitchHTTP", parent: Optional[CustomReward]):
265
self._http = http
266
self._broadcaster_id = obj["broadcaster_id"]
267
self.id = obj["id"]
268
self.user_id = int(obj["user_id"])
269
self.user_name = obj["user_name"]
270
self.input = obj["user_input"]
271
self.status = obj["status"]
272
self.redeemed_at = datetime.datetime.fromisoformat(obj["redeemed_at"])
273
self.reward = parent or obj["reward"]
274
275
async def fulfill(self, token: str):
276
"""
277
marks the redemption as fulfilled
278
279
Parameters
280
----------
281
token:
282
:class:`str` the token of the target channel
283
284
Returns
285
--------
286
itself.
287
"""
288
reward_id = self.reward.id if isinstance(self.reward, CustomReward) else self.reward["id"]
289
try:
290
data = await self._http.update_reward_redemption_status(
291
token, self._broadcaster_id, self.id, reward_id, True
292
)
293
except Unauthorized as error:
294
raise Unauthorized("The given token is invalid", "", 401) from error
295
except HTTPException as error:
296
status = error.args[2]
297
if status == 403:
298
raise HTTPException(
299
"The custom reward was created by a different application, or channel points are "
300
"not available for the broadcaster (403)",
301
error.args[1],
302
403,
303
) from error
304
raise
305
else:
306
self.__init__(data["data"], self._http, self.reward if isinstance(self.reward, CustomReward) else None)
307
return self
308
309
async def refund(self, token: str):
310
"""
311
marks the redemption as cancelled
312
313
Parameters
314
----------
315
token:
316
:class:`str` the token of the target channel
317
318
Returns
319
--------
320
itself.
321
"""
322
reward_id = self.reward.id if isinstance(self.reward, CustomReward) else self.reward["id"]
323
try:
324
data = await self._http.update_reward_redemption_status(
325
token, self._broadcaster_id, self.id, reward_id, False
326
)
327
except Unauthorized as error:
328
raise Unauthorized("The given token is invalid", "", 401) from error
329
except HTTPException as error:
330
status = error.args[2]
331
if status == 403:
332
raise HTTPException(
333
"The custom reward was created by a different application, or channel points are "
334
"not available for the broadcaster (403)",
335
error.args[1],
336
403,
337
) from error
338
raise
339
else:
340
self.__init__(data["data"], self._http, self.reward if isinstance(self.reward, CustomReward) else None)
341
return self
342
343