-
-
Notifications
You must be signed in to change notification settings - Fork 165
/
Copy pathuser.py
4023 lines (3232 loc) · 155 KB
/
user.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
MIT License
Copyright (c) 2017 - Present PythonistaGuild
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Literal
from .assets import Asset
from .exceptions import HTTPException, MessageRejectedError
from .models.ads import AdSchedule, CommercialStart, SnoozeAd
from .models.raids import Raid
from .utils import Colour, parse_timestamp
if TYPE_CHECKING:
import datetime
from twitchio.types_.responses import (
UserActiveExtensionsResponseData,
UserExtensionsResponseData,
UserPanelComponentItem,
UserPanelItem,
UserPanelOverlayItem,
UsersResponseData,
)
from .http import HTTPAsyncIterator, HTTPClient
from .models.analytics import ExtensionAnalytics, GameAnalytics
from .models.bits import BitsLeaderboard
from .models.channel_points import CustomReward
from .models.channels import ChannelEditor, ChannelFollowerEvent, ChannelFollowers, ChannelInfo, FollowedChannels
from .models.charity import CharityCampaign, CharityDonation
from .models.chat import ChannelEmote, ChatBadge, ChatSettings, Chatters, SentMessage, SharedChatSession, UserEmote
from .models.clips import Clip, CreatedClip
from .models.eventsub_ import ChannelChatMessageEvent, ChatMessageBadge
from .models.goals import Goal
from .models.hype_train import HypeTrainEvent
from .models.moderation import (
AutomodCheckMessage,
AutomodSettings,
AutoModStatus,
Ban,
BannedUser,
BlockedTerm,
ShieldModeStatus,
Timeout,
UnbanRequest,
Warning,
)
from .models.polls import Poll
from .models.predictions import Prediction
from .models.schedule import Schedule
from .models.streams import Stream, StreamMarker, VideoMarkers
from .models.subscriptions import BroadcasterSubscriptions, UserSubscription
from .models.teams import ChannelTeam
__all__ = ("ActiveExtensions", "Extension", "PartialUser", "User")
class PartialUser:
"""A class that contains minimal data about a user from the API.
Any API calls pertaining to a user / broadcaster / channel will be on this object.
Attributes
-----------
id: str | int
The user's ID.
name: str | None
The user's name. In most cases, this is provided. There are however, rare cases where it is not.
display_name: str | None
The user's display name in chat. In most cases, this is provided otherwise fallsback to `name`. There are however, rare cases where it is not.
"""
__slots__ = "_cached_rewards", "_http", "display_name", "id", "name"
def __init__(self, id: str | int, name: str | None = None, display_name: str | None = None, *, http: HTTPClient) -> None:
self._http = http
self.id = str(id)
self.name = name
self.display_name = display_name or name
def __repr__(self) -> str:
return f"<PartialUser id={self.id} name={self.name}>"
def __str__(self) -> str:
return self.name or "..."
def __eq__(self, other: object) -> bool:
if not isinstance(other, (PartialUser, User, Chatter)):
return NotImplemented
return self.id == other.id
@property
def mention(self) -> str:
"""Property returning the users display_name formatted to mention them in chat.
E.g. "@kappa"
"""
return f"@{self.display_name or '...'}"
async def start_commercial(self, *, length: int) -> CommercialStart:
"""|coro|
Starts a commercial on the specified channel.
.. important::
Only partners and affiliates may run commercials and they must be streaming live at the time.
Only the broadcaster may start a commercial; the broadcaster's editors and moderators may not start commercials on behalf of the broadcaster.
.. note::
Requires user access token that includes the ``channel:edit:commercial`` scope.
Parameters
----------
length: int
The length of the commercial to run, in seconds. Max length is 180.
If you request a commercial that's longer than 180 seconds, the API uses 180 seconds.
Returns
-------
CommercialStart
A CommercialStart object.
"""
data = await self._http.start_commercial(broadcaster_id=self.id, length=length, token_for=self.id)
return CommercialStart(data["data"][0])
async def fetch_ad_schedule(self) -> AdSchedule:
"""|coro|
Fetch ad schedule related information, including snooze, when the last ad was run, when the next ad is scheduled, and if the channel is currently in pre-roll free time.
.. important::
A new ad cannot be run until 8 minutes after running a previous ad.
The user id in the user access token must match the id of this PartialUser object.
.. note::
Requires user access token that includes the ``channel:read:ads`` scope.
Returns
-------
AdSchedule
An AdSchedule object.
"""
data = await self._http.get_ad_schedule(broadcaster_id=self.id, token_for=self.id)
return AdSchedule(data["data"][0])
async def snooze_next_ad(self) -> SnoozeAd:
"""|coro|
If available, pushes back the timestamp of the upcoming automatic mid-roll ad by 5 minutes.
This endpoint duplicates the snooze functionality in the creator dashboard's Ads Manager.
.. important::
The user id in the user access token must match the id of this PartialUser object.
.. note::
Requires user access token that includes the ``channel:manage:ads`` scope.
Returns
-------
SnoozeAd
A SnoozeAd object.
"""
data = await self._http.post_snooze_ad(broadcaster_id=self.id, token_for=self.id)
return SnoozeAd(data["data"][0])
def fetch_extension_analytics(
self,
*,
token_for: str | PartialUser,
first: int = 20,
extension_id: str | None = None,
type: Literal["overview_v2"] = "overview_v2",
started_at: datetime.date | None = None,
ended_at: datetime.date | None = None,
max_results: int | None = None,
) -> HTTPAsyncIterator[ExtensionAnalytics]:
"""|aiter|
Fetches an analytics report for one or more extensions. The response contains the URLs used to download the reports (CSV files)
.. important::
Both ``started_at`` and ``ended_at`` must be provided when requesting a date range. They are UTC timezone by default.
If you omit both of these then the report includes all available data from January 31, 2018.
Because it can take up to two days for the data to be available, you must specify an end date that's earlier than today minus one to two days.
If not, the API ignores your end date and uses an end date that is today minus one to two days.
.. note::
Requires user access token that includes the ``analytics:read:extensions`` scope.
Parameters
-----------
token_for: str | PartialUser
A user access token that includes the ``analytics:read:extensions`` scope.
extension_id: str
The extension's client ID. If specified, the response contains a report for the specified extension.
If not specified, the response includes a report for each extension that the authenticated user owns.
type: Literal["overview_v2"]
The type of analytics report to get. This is set to ``overview_v2`` by default.
started_at: datetime.date
The date to start the report from. If you specify a start date, you must specify an end date.
ended_at: datetime.date
The end date for the report, this is inclusive. Specify an end date only if you provide a start date.
first: int
Maximum number of items to return per page. Default is 20.
Min is 1 and Max is 100.
max_results: int | None
Maximum number of total results to return. When this is set to None (default), then everything found is returned.
Returns
--------
HTTPAsyncIterator[ExtensionAnalytics]
Raises
------
ValueError
Both started_at and ended_at must be provided together.
"""
first = max(1, min(100, first))
if bool(started_at) != bool(ended_at):
raise ValueError("Both started_at and ended_at must be provided together.")
return self._http.get_extension_analytics(
first=first,
token_for=token_for,
extension_id=extension_id,
type=type,
started_at=started_at,
ended_at=ended_at,
max_results=max_results,
)
def fetch_game_analytics(
self,
*,
token_for: str | PartialUser,
first: int = 20,
game_id: str | None = None,
type: Literal["overview_v2"] = "overview_v2",
started_at: datetime.date | None = None,
ended_at: datetime.date | None = None,
max_results: int | None = None,
) -> HTTPAsyncIterator[GameAnalytics]:
"""|aiter|
Fetches a game report for one or more games. The response contains the URLs used to download the reports (CSV files)
.. important::
Both ``started_at`` and ``ended_at`` must be provided when requesting a date range.
If you omit both of these then the report includes all available data from January 31, 2018.
Because it can take up to two days for the data to be available, you must specify an end date that's earlier than today minus one to two days.
If not, the API ignores your end date and uses an end date that is today minus one to two days.
.. note::
Requires user access token that includes the ``analytics:read:extensions`` scope.
Parameters
-----------
token_for: str | PartialUser
A user access token that includes the ``analytics:read:extensions`` scope.
game_id: str
The game's client ID. If specified, the response contains a report for the specified game.
If not specified, the response includes a report for each of the authenticated user's games.
type: Literal["overview_v2"]
The type of analytics report to get. This is set to ``overview_v2`` by default.
started_at: datetime.date
The date to start the report from. If you specify a start date, you must specify an end date.
ended_at: datetime.date
The end date for the report, this is inclusive. Specify an end date only if you provide a start date.
first: int
Maximum number of items to return per page. Default is 20.
Min is 1 and Max is 100.
max_results: int | None
Maximum number of total results to return. When this is set to None (default), then everything found is returned.
Returns
--------
twitchio.HTTPAsyncIterator[GameAnalytics]
Raises
------
ValueError
Both started_at and ended_at must be provided together.
"""
first = max(1, min(100, first))
if bool(started_at) != bool(ended_at):
raise ValueError("Both started_at and ended_at must be provided together")
return self._http.get_game_analytics(
first=first,
token_for=token_for,
game_id=game_id,
type=type,
started_at=started_at,
ended_at=ended_at,
max_results=max_results,
)
async def fetch_bits_leaderboard(
self,
count: int = 10,
period: Literal["all", "day", "week", "month", "year"] = "all",
started_at: datetime.datetime | None = None,
user: str | int | PartialUser | None = None,
) -> BitsLeaderboard:
"""|coro|
Fetches the Bits leaderboard for this user.
.. important::
``started_at`` is converted to PST before being used, so if you set the start time to 2022-01-01T00:00:00.0Z and period to month, the actual reporting period is December 2021, not January 2022.
If you want the reporting period to be January 2022, you must set the start time to 2022-01-01T08:00:00.0Z or 2022-01-01T00:00:00.0-08:00.
When providing ``started_at``, you must also change the ``period`` parameter to any value other than "all".
Conversely, if `period` is set to anything other than "all", ``started_at`` must also be provided.
.. note::
Requires user access token that includes the ``bits:read`` scope.
+---------+-----------------------------------------------------------------------------------------------------+
| Period | Description |
+=========+=====================================================================================================+
| day | A day spans from 00:00:00 on the day specified in started_at and runs through 00:00:00 of the next |
| | day. |
+---------+-----------------------------------------------------------------------------------------------------+
| week | A week spans from 00:00:00 on the Monday of the week specified in started_at and runs through |
| | 00:00:00 of the next Monday. |
+---------+-----------------------------------------------------------------------------------------------------+
| month | A month spans from 00:00:00 on the first day of the month specified in started_at and runs through |
| | 00:00:00 of the first day of the next month. |
+---------+-----------------------------------------------------------------------------------------------------+
| year | A year spans from 00:00:00 on the first day of the year specified in started_at and runs through |
| | 00:00:00 of the first day of the next year. |
+---------+-----------------------------------------------------------------------------------------------------+
| all | Default. The lifetime of the broadcaster's channel. |
+---------+-----------------------------------------------------------------------------------------------------+
Parameters
----------
count: int
The number of results to return. The minimum count is 1 and the maximum is 100. The default is 10.
period: Literal["all", "day", "week", "month", "year"]
The time period over which data is aggregated (uses the PST time zone).
started_at: datetime.datetime | None
The start date, used for determining the aggregation period. Specify this parameter only if you specify the period query parameter.
The start date is ignored if period is all. This can be timezone aware.
user: str | int | PartialUser | None
A User ID that identifies a user that cheered bits in the channel.
If count is greater than 1, the response may include users ranked above and below the specified user.
To get the leaderboard's top leaders, don't specify a user ID.
Returns
-------
BitsLeaderboard
BitsLeaderboard object for a user's channel.
Raises
------
ValueError
Count must be between 10 and 100.
ValueError
The 'period' parameter must be set to anything other than 'all' if 'started_at' is provided, and vice versa.
"""
if count > 100 or count < 1:
raise ValueError("Count must be between 10 and 100.")
if (period != "all" and started_at is None) or (period == "all" and started_at is not None):
raise ValueError(
"The 'period' parameter must be set to anything other than 'all' if 'started_at' is provided, and vice versa."
)
from .models.bits import BitsLeaderboard
data = await self._http.get_bits_leaderboard(
token_for=self.id,
count=count,
period=period,
started_at=started_at,
user_id=user,
)
return BitsLeaderboard(data, http=self._http)
async def fetch_channel_info(self, *, token_for: str | PartialUser | None = None) -> ChannelInfo:
"""|coro|
Retrieve channel information for this user.
Parameters
-----------
token_for: str | PartialUser | None
An optional user token to use instead of the default app token.
Returns
--------
ChannelInfo
ChannelInfo object representing the channel information.
"""
from .models.channels import ChannelInfo
data = await self._http.get_channel_info(broadcaster_ids=[self.id], token_for=token_for)
return ChannelInfo(data["data"][0], http=self._http)
async def modify_channel(
self,
*,
game_id: str | None = None,
language: str | None = None,
title: str | None = None,
delay: int | None = None,
tags: list[str] | None = None,
classification_labels: list[
dict[
Literal[
"DebatedSocialIssuesAndPolitics",
"MatureGame",
"DrugsIntoxication",
"SexualThemes",
"ViolentGraphic",
"Gambling",
"ProfanityVulgarity",
],
bool,
]
]
| None = None,
branded: bool | None = None,
) -> None:
"""|coro|
Updates this user's channel properties.
.. important::
A channel may specify a maximum of 10 tags. Each tag is limited to a maximum of 25 characters and may not be an empty string or contain spaces or special characters.
Tags are case insensitive.
For readability, consider using camelCasing or PascalCasing.
.. note::
Requires user access token that includes the ``channel:manage:broadcast`` scope.
Examples
--------
.. code:: python3
import twitchio
users: list[ChannelInfo] = await client.fetch_channels([21734222])
msg_checks: list[AutomodCheckMessage] = [AutomodCheckMessage(id="1234", text="Some Text"), AutomodCheckMessage(id="12345", text="Some More Text")]
checks: list[AutoModStatus] = await users[0].check_automod_status(messages=msg_checks, token_for="21734222")
Parameters
-----------
game_id: str | None
The ID of the game that the user plays. The game is not updated if the ID isn't a game ID that Twitch recognizes. To unset this field, use '0' or '' (an empty string).
language: str | None
The user's preferred language. Set the value to an ISO 639-1 two-letter language code (for example, en for English).
Set to “other” if the user's preferred language is not a Twitch supported language.
The language isn't updated if the language code isn't a Twitch supported language.
title: str | None
The title of the user's stream. You may not set this field to an empty string.
delay: int | None
The number of seconds you want your broadcast buffered before streaming it live.
The delay helps ensure fairness during competitive play.
Only users with Partner status may set this field. The maximum delay is 900 seconds (15 minutes).
tags: list[str] | None
A list of channel-defined tags to apply to the channel. To remove all tags from the channel, set tags to an empty array. Tags help identify the content that the channel streams.
You may set a maximum of 10 tags, each limited to 25 characters. They can not be empty strings, contain spaces or special characters.
See `here for more information <https://help.twitch.tv/s/article/guide-to-tags>`_
classification_labels: list[dict[Literal["DebatedSocialIssuesAndPolitics", "MatureGame", "DrugsIntoxication", "SexualThemes", "ViolentGraphic", "Gambling", "ProfanityVulgarity"], bool]] | None
List of labels that should be set as the Channel's CCLs.
branded: bool | None
Boolean flag indicating if the channel has branded content.
"""
return await self._http.patch_channel_info(
broadcaster_id=self.id,
token_for=self.id,
game_id=game_id,
language=language,
title=title,
delay=delay,
tags=tags,
classification_labels=classification_labels,
branded_content=branded,
)
async def fetch_editors(self) -> list[ChannelEditor]:
"""|coro|
Fetches a list of the user's editors for their channel.
.. note::
Requires user access token that includes the ``channel:manage:broadcast`` scope.
Returns
-------
list[ChannelEditor]
A list of ChannelEditor objects.
"""
from .models.channels import ChannelEditor
data = await self._http.get_channel_editors(broadcaster_id=self.id, token_for=self.id)
return [ChannelEditor(d, http=self._http) for d in data["data"]]
async def fetch_followed_channels(
self,
broadcaster: str | int | None = None,
first: int = 20,
max_results: int | None = None,
) -> FollowedChannels | None:
"""|coro|
Fetches information of who and when this user followed other channels.
.. note::
Requires user access token that includes the ``user:read:follows`` scope.
Parameters
-----------
broadcaster: str | int | PartialUser | None
Provide a User ID, or PartialUser, to check whether the user follows this broadcaster.
first: int
Maximum number of items to return per page. Default is 20.
Min is 1 and Max is 100.
max_results: int | None
Maximum number of total results to return. When this is set to None (default), then everything found is returned.
Returns
-------
FollowedChannels
FollowedChannels object.
"""
return await self._http.get_followed_channels(
user_id=self.id,
token_for=self.id,
broadcaster_id=broadcaster,
first=first,
max_results=max_results,
)
async def fetch_followers(
self,
user: str | int | PartialUser | None = None,
first: int = 20,
max_results: int | None = None,
) -> ChannelFollowers:
"""|coro|
Fetches information of who and when users followed this channel.
.. important::
The user ID in the token must match that of the broadcaster or a moderator.
.. note::
Requires user access token that includes the ``moderator:read:followers`` scope.
Parameters
-----------
user: str | int | PartialUser | None
Provide a User ID, or PartialUser, to check whether the user follows this broadcaster.
first: int
Maximum number of items to return per page. Default is 20.
Min is 1 and Max is 100.
max_results: int | None
Maximum number of total results to return. When this is set to None (default), then everything found is returned.
Returns
-------
ChannelFollowers
A ChannelFollowers object.
"""
return await self._http.get_channel_followers(
broadcaster_id=self.id,
token_for=self.id,
user_id=user,
first=first,
max_results=max_results,
)
async def create_custom_reward(
self,
title: str,
cost: int,
*,
prompt: str | None = None,
enabled: bool = True,
background_color: str | Colour | None = None,
max_per_stream: int | None = None,
max_per_user: int | None = None,
global_cooldown: int | None = None,
redemptions_skip_queue: bool = False,
) -> CustomReward:
"""|coro|
Creates a Custom Reward in the broadcaster's channel.
.. note::
The maximum number of custom rewards per channel is 50, which includes both enabled and disabled rewards.
.. note::
Requires user access token that includes the channel:manage:redemptions scope.
Parameters
-----------
title: str
The custom reward's title. The title may contain a maximum of 45 characters and it must be unique amongst all of the broadcaster's custom rewards.
cost: int
The cost of the reward, in Channel Points. The minimum is 1 point.
prompt: str | None
The prompt shown to the viewer when they redeem the reward. The prompt is limited to a maximum of 200 characters.
If provided, the user must input a message when redeeming the reward.
enabled: bool
A Boolean value that determines whether the reward is enabled. Viewers see only enabled rewards. The default is True.
background_color: str | Colour | None
The background color to use for the reward. Specify the color using Hex format (for example, #9147FF).
This can also be a [`.Colour`][twitchio.utils.Colour] object.
max_per_stream: int | None
The maximum number of redemptions allowed per live stream. Minimum value is 1.
max_per_user: int | None
The maximum number of redemptions allowed per user per stream. Minimum value is 1.
global_cooldown: int | None
The cooldown period, in seconds. The minimum value is 1; however, the minimum value is 60 for it to be shown in the Twitch UX.
redemptions_skip_queue: bool
A Boolean value that determines whether redemptions should be set to FULFILLED status immediately when a reward is redeemed. If False, status is set to UNFULFILLED and follows the normal request queue process. The default is False.
Returns
--------
CustomReward
Information regarding the custom reward.
Raises
------
ValueError
title must be a maximum of 45 characters.
ValueError
prompt must be a maximum of 200 characters.
ValueError
Minimum value must be at least 1.
"""
if len(title) > 45:
raise ValueError("title must be a maximum of 45 characters.")
if cost < 1:
raise ValueError("cost must be at least 1.")
if prompt is not None and len(prompt) > 200:
raise ValueError("prompt must be a maximum of 200 characters.")
if max_per_stream is not None and max_per_stream < 1:
raise ValueError("max_per_stream must be at least 1.")
if max_per_user is not None and max_per_user < 1:
raise ValueError("max_per_user must be at least 1.")
if global_cooldown is not None and global_cooldown < 1:
raise ValueError("global_cooldown must be at least 1.")
from .models.channel_points import CustomReward
data = await self._http.post_custom_reward(
broadcaster_id=self.id,
token_for=self.id,
title=title,
cost=cost,
prompt=prompt,
enabled=enabled,
background_color=background_color,
max_per_stream=max_per_stream,
max_per_user=max_per_user,
global_cooldown=global_cooldown,
skip_queue=redemptions_skip_queue,
)
return CustomReward(data["data"][0], http=self._http)
async def fetch_custom_rewards(self, *, ids: list[str] | None = None, manageable: bool = False) -> list[CustomReward]:
"""|coro|
Fetches list of custom rewards that the specified broadcaster created.
.. note::
Requires user access token that includes the ``channel:read:redemptions`` or ``channel:manage:redemptions`` scope.
Parameters
----------
ids: list[str] | None
A list of IDs to filter the rewards by. You may request a maximum of 50.
manageable: bool | None
A Boolean value that determines whether the response contains only the custom rewards that the app (Client ID) may manage.
Default is False.
Returns
-------
list[CustomReward]
_description_
"""
from .models.channel_points import CustomReward
data = await self._http.get_custom_reward(
broadcaster_id=self.id, reward_ids=ids, manageable=manageable, token_for=self.id
)
return [CustomReward(d, http=self._http) for d in data["data"]]
async def fetch_charity_campaign(self) -> CharityCampaign:
"""|coro|
Fetch the active charity campaign of a broadcaster.
.. note::
Requires user access token that includes the ``channel:read:charity`` scope.
Returns
-------
CharityCampaign
A CharityCampaign object.
"""
from .models.charity import CharityCampaign
data = await self._http.get_charity_campaign(broadcaster_id=self.id, token_for=self.id)
return CharityCampaign(data["data"][0], http=self._http)
def fetch_charity_donations(
self,
*,
first: int = 20,
max_results: int | None = None,
) -> HTTPAsyncIterator[CharityDonation]:
"""|aiter|
Fetches information about all broadcasts on Twitch.
.. note::
Requires user access token that includes the ``channel:read:charity`` scope.
Parameters
-----------
first: int
Maximum number of items to return per page. Default is 20.
Min is 1 and Max is 100.
max_results: int | None
Maximum number of total results to return. When this is set to None (default), then everything found is returned.
Returns
--------
HTTPAsyncIterator[CharityDonation]
"""
first = max(1, min(100, first))
return self._http.get_charity_donations(
broadcaster_id=self.id,
first=first,
token_for=self.id,
max_results=max_results,
)
async def fetch_chatters(
self,
*,
moderator: str | int | PartialUser, # TODO Default to bot_id, same for token_for.
first: int = 100,
max_results: int | None = None,
) -> Chatters:
"""|coro|
Fetches users that are connected to the broadcaster's chat session.
.. note::
Requires user access token that includes the ``moderator:read:chatters`` scope.
Parameters
----------
moderator: str | int | PartialUser
The ID, or PartialUser, of the broadcaster or one of the broadcaster's moderators.
This ID must match the user ID in the user access token.
first: int | None
The maximum number of items to return per page in the response.
The minimum page size is 1 item per page and the maximum is 1,000. The default is 100.
max_results: int | None
Maximum number of total results to return. When this is set to None (default), then everything found is returned.
Returns
-------
Chatters
A Chatters object containing the information of a broadcaster's connected chatters.
"""
first = max(1, min(1000, first))
return await self._http.get_chatters(
token_for=moderator, first=first, broadcaster_id=self.id, moderator_id=moderator, max_results=max_results
)
async def fetch_channel_emotes(self, token_for: str | PartialUser | None = None) -> list[ChannelEmote]:
"""|coro|
Fetches the broadcaster's list of custom emotes.
Broadcasters create these custom emotes for users who subscribe to or follow the channel or cheer Bits in the channel's chat window.
Parameters
----------
token_for: str | PartialUser | None
An optional user token to use instead of the default app token.
Returns
-------
list[ChannelEmote]
A list of ChannelEmote objects
"""
from twitchio.models.chat import ChannelEmote
data = await self._http.get_channel_emotes(broadcaster_id=self.id, token_for=token_for)
template = data["template"]
return [ChannelEmote(d, template=template, http=self._http) for d in data["data"]]
def fetch_user_emotes(
self,
*,
broadcaster: str | int | PartialUser | None = None,
max_results: int | None = None,
) -> HTTPAsyncIterator[UserEmote]:
"""|aiter|
Fetches the broadcaster's list of custom emotes.
Broadcasters create these custom emotes for users who subscribe to or follow the channel or cheer Bits in the channel's chat window.
.. note::
Requires user access token that includes the ``user:read:emotes`` scope.
Parameters
----------
broadcaster: str | int | PartialUser | None
The User ID, or PartialUser, of a broadcaster you wish to get follower emotes of. Using this query parameter will guarantee inclusion of the broadcaster's follower emotes in the response body.
max_results: int | None
Maximum number of total results to return. When this is set to None (default), then everything found is returned.
Returns
-------
HTTPAsyncIterator[UserEmote]
"""
return self._http.get_user_emotes(
user_id=self.id,
token_for=self.id,
broadcaster_id=broadcaster,
max_results=max_results,
)
async def fetch_badges(self, token_for: str | PartialUser | None = None) -> list[ChatBadge]:
"""|coro|
Fetches the broadcaster's list of custom chat badges.
If you wish to fetch globally available chat badges use If you wish to fetch a specific broadcaster's chat badges use [`client.fetch_badges`][twitchio.client.fetch_badges]
Parameters
----------
token_for: str | PartialUser | None
An optional user token to use instead of the default app token.
Returns
--------
list[ChatBadge]
A list of ChatBadge objects belonging to the user.
"""
from .models.chat import ChatBadge
data = await self._http.get_channel_chat_badges(broadcaster_id=self.id, token_for=token_for)
return [ChatBadge(d, http=self._http) for d in data["data"]]
async def fetch_chat_settings(
self, *, moderator: str | int | PartialUser | None = None, token_for: str | PartialUser | None = None
) -> ChatSettings:
"""|coro|
Fetches the broadcaster's chat settings.
.. note::
If you wish to view ``non_moderator_chat_delay`` and ``non_moderator_chat_delay_duration`` then you will need to provide a moderator, which can be
either the broadcaster's or a moderators'. The token must include the ``moderator:read:chat_settings`` scope.
Parameters
----------
moderator: str | int | PartialUser | None
The ID, or PartialUser, of the broadcaster or one of the broadcaster's moderators.
This field is only required if you want to include the ``non_moderator_chat_delay`` and ``non_moderator_chat_delay_duration`` settings in the response.
If you specify this field, this ID must match the user ID in the user access token.
token_for: str | PartialUser | None
If you need the response to contain ``non_moderator_chat_delay`` and ``non_moderator_chat_delay_duration`` then you will provide a token for the user in ``moderator``.
The required scope is ``moderator:read:chat_settings``.
Otherwise it is an optional user token to use instead of the default app token.
Returns
-------
ChatSettings
ChatSettings object of the broadcaster's chat settings.
"""
from .models.chat import ChatSettings
data = await self._http.get_channel_chat_settings(
broadcaster_id=self.id, moderator_id=moderator, token_for=token_for
)
return ChatSettings(data["data"][0], http=self._http)
async def update_chat_settings(
self,
moderator: str | int | PartialUser,
emote_mode: bool | None = None,
follower_mode: bool | None = None,
follower_mode_duration: int | None = None,
slow_mode: bool | None = None,
slow_mode_wait_time: int | None = None,
subscriber_mode: bool | None = None,
unique_chat_mode: bool | None = None,
non_moderator_chat_delay: bool | None = None,
non_moderator_chat_delay_duration: Literal[2, 4, 6] | None = None,
) -> ChatSettings:
"""|coro|
Update the user's chat settings.
.. note::
- To set the ``slow_mode_wait_time`` or ``follower_mode_duration`` field to its default value, set the corresponding ``slow_mode`` or ``follower_mode`` field to True (and don't include the ``slow_mode_wait_time`` or ``follower_mode_duration`` field).
- To set the ``slow_mode_wait_time``, ``follower_mode_duration``, or ``non_moderator_chat_delay_duration`` field's value, you must set the corresponding ``slow_mode``, ``follower_mode``, or ``non_moderator_chat_delay`` field to True.
- To remove the ``slow_mode_wait_time``, ``follower_mode_duration``, or ``non_moderator_chat_delay_duration`` field's value, set the corresponding ``slow_mode``, ``follower_mode``, or ``non_moderator_chat_delay`` field to False (and don't include the slow_mode_wait_time, follower_mode_duration, or non_moderator_chat_delay_duration field).
.. note::
Requires a user access token that includes the ``moderator:manage:chat_settings`` scope.
Parameters
----------
moderator: str | int | PartialUser
The ID, or PartialUser, of a user that has permission to moderate the broadcaster's chat room, or the broadcaster's ID if they're making the update.
This ID must match the user ID in the user access token.
emote_mode: bool | None
A Boolean value that determines whether chat messages must contain only emotes.
follower_mode: bool | None
A Boolean value that determines whether the broadcaster restricts the chat room to followers only.
follower_mode_duration: int | None
The length of time, in minutes, that users must follow the broadcaster before being able to participate in the chat room.
Set only if follower_mode is True. Possible values are: 0 (no restriction) through 129600 (3 months).
slow_mode: bool | None
A Boolean value that determines whether the broadcaster limits how often users in the chat room are allowed to send messages.
Set to True if the broadcaster applies a wait period between messages; otherwise, False.
slow_mode_wait_time: int | None
The amount of time, in seconds, that users must wait between sending messages. Set only if slow_mode is True.
Possible values are: 3 (3 second delay) through 120 (2 minute delay). The default is 30 seconds.
subscriber_mode: bool | None
A Boolean value that determines whether only users that subscribe to the broadcaster's channel may talk in the chat room.
Set to True if the broadcaster restricts the chat room to subscribers only; otherwise, False.
unique_chat_mode: bool | None
A Boolean value that determines whether the broadcaster requires users to post only unique messages in the chat room.
Set to True if the broadcaster allows only unique messages; otherwise, False.
non_moderator_chat_delay: bool | None
A Boolean value that determines whether the broadcaster adds a short delay before chat messages appear in the chat room.
This gives chat moderators and bots a chance to remove them before viewers can see the message.
Set to True if the broadcaster applies a delay; otherwise, False.
non_moderator_chat_delay_duration: Literal[2, 4, 6] | None
The amount of time, in seconds, that messages are delayed before appearing in chat.
Set only if non_moderator_chat_delay is True.
Possible values in seconds: 2 (recommended), 4 and 6.