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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
|
%global _empty_manifest_terminate_build 0
Name: python-PythonTwitchBotFramework
Version: 2.10.2
Release: 1
Summary: asynchronous twitch-bot framework made in pure python
License: MIT
URL: https://github.com/sharkbound/PythonTwitchBotFramework
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/49/90/fbcb4f463894524cffe3a66d424c367a1092753f8833f25efb6884e74ae6/PythonTwitchBotFramework-2.10.2.tar.gz
BuildArch: noarch
Requires: python3-aiohttp
Requires: python3-sqlalchemy
Requires: python3-websockets
Requires: python3-dataclasses
%description
# if you have any questions concerning the bot, you can contact me in my discord server: https://discord.gg/PXrKVHp OR [r/pythontwitchbot](https://www.reddit.com/r/pythontwitchbot/) on reddit
if you would like to send a few dollars my way you can do so
here: [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=9ZVUE7CR24738)
this bot is also on PYPI: https://pypi.org/project/PythonTwitchBotFramework/
install from pip: `pip install PythonTwitchBotFramework`
# PythonTwitchBotFramework
fully async twitchbot framework/library compatible with python 3.6+
First and foremost, I want to thank anyone who uses this, or even is just reading this readme,
and to any contributors who have helped with updates/features.
## Note about the wiki and readme right now:
I am in the process of adding missing info to the wiki/readme,
and also updating to show the new command argument handling added in 2.7.0+.
(referring to the fact the command system now supporting and enforcing typehints, and not requiring *args anymore)
As well as some features i didn't put in the wiki or readme yet.
If you are any version earlier than 2.7.0, some things showcased/described on the wiki may not work for you.
## How to stop the bot
to stop the bot running, do any of these commands:
`!shutdown` or `!stop` in the twitch chat of the channel its in, this command tries to properly shutdown all the
tasks the bot is currently running and gives time to stop/cancel
these commands require the caller have permission to execute them
# Note:
### This readme only goes over basic info meant to help quickly get something working, the [GITHUB WIKI](https://github.com/sharkbound/PythonTwitchBotFramework/wiki) goes more in depth.
# Index
* [Quick Start](#quick-start)
* [Overriding Events](#overriding-events)
* [Overriding Events On Mods](#overriding-events-on-mods)
* [Adding Commands](#adding-commands)
* [SubCommands](#subcommands)
* [DummyCommands](#dummycommands)
* [Permissions](#permissions)
* [Using Chat Commands](#managing-permissions-using-chat-commands)
* [Editing The Config](#managing-permission-by-editing-the-configs)
* [Reloading Permissions](#reloading-permissions)
* [Command Server](#command-server)
* [Command Console](#command-console)
* [Database Support](#database-support)
* [Command Whitelist](#command-whitelist)
* [Twitch PubSub Client](#twitch-pubsub-client)
# Basic info
This is a fully async twitch bot framework complete with:
* builtin command system using decorators
* overridable events (message received, whisper received, ect)
* full permission system that is individual for each channel
* message timers
* quotes
* custom commands
* builtin economy
there is also mod system builtin to the bot, there is a collection of pre-made mods
here: [MODS](https://github.com/sharkbound/twitch_bot_mods)
# Quick Start
for a reference for builtin command look at the
wiki [HERE](https://github.com/sharkbound/PythonTwitchBotFramework/wiki/Builtin_Command_Reference)
the minimum code to get the bot running is this:
```python
from twitchbot import BaseBot
if __name__ == '__main__':
BaseBot().run()
```
this will start the bot.
if you have a folder with your own custom commands you can load the .py files in it with:
```python
from twitchbot import BaseBot
if __name__ == '__main__':
BaseBot().run()
```
# Overriding Events
the bots events are overridable via the following 2 ways:
## Using decorators:
```python
from twitchbot import event_handler, Event, Message
@event_handler(Event.on_privmsg_received)
async def on_privmsg_received(msg: Message):
print(f'{msg.author} sent message {msg.content} to channel {msg.channel_name}')
```
## Subclassing BaseBot
```python
from twitchbot import BaseBot, Message
class MyCustomTwitchBot(BaseBot):
async def on_privmsg_received(self, msg: Message):
print(f'{msg.author} sent message {msg.content} to channel {msg.channel_name}')
```
then you would use MyCustomTwitchBot instead of BaseBot:
```python
MyCustomTwitchBot().run()
```
## Overriding Events On Mods
Visit [***the mods wiki page***](https://github.com/sharkbound/PythonTwitchBotFramework/wiki/Mods#index)
on this repo's wiki to view how to do it via Mods
* all overridable events are:
#### when using the decorator event override way, `self` is not included, ex: `(self, msg: Message)` becomes: `(msg: Message)`
```python
from twitchbot import Event
Event.on_connected: (self)
Event.on_permission_check: (self, msg
: Message, cmd: Command) -> Optional[
bool] # return False to deny permission to execute the cmd, Return None to ignore and continue
Event.on_after_command_execute: (self, msg: Message, cmd: Command)
Event.on_before_command_execute: (self, msg: Message, cmd: Command) -> bool # return False to cancel command
Event.on_bits_donated: (self, msg: Message, bits: int)
Event.on_channel_raided: (self, channel: Channel, raider: str, viewer_count: int)
Event.on_channel_joined: (self, channel: Channel)
Event.on_channel_subscription: (self, subscriber: str, channel: Channel, msg: Message)
Event.on_privmsg_received: (self, msg: Message)
Event.on_privmsg_sent: (self, msg: str, channel: str, sender: str)
Event.on_whisper_received: (self, msg: Message)
Event.on_whisper_sent: (self, msg: str, receiver: str, sender: str)
Event.on_raw_message: (self, msg: Message)
Event.on_user_join: (self, user: str, channel: Channel)
Event.on_user_part: (self, user: str, channel: Channel)
Event.on_mod_reloaded: (self, mod: Mod)
Event.on_channel_points_redemption: (self, msg: Message, reward: str)
Event.on_bot_timed_out_from_channel: (self, msg: Message, channel: Channel, seconds: int)
Event.on_bot_banned_from_channel: (self, msg: Message, channel: Channel)
Event.on_poll_started: (self, channel: Channel, poll: PollData)
Event.on_poll_ended: (self, channel: Channel, poll: PollData)
Event.on_pubsub_received: (self, raw: 'PubSubData')
Event.on_pubsub_custom_channel_point_reward: (self, raw: 'PubSubData', data: 'PubSubPointRedemption')
Event.on_pubsub_bits: (self, raw: 'PubSubData', data: 'PubSubBits')
Event.on_pubsub_moderation_action: (self, raw: 'PubSubData', data: 'PubSubModerationAction')
Event.on_pubsub_subscription: (self, raw: 'PubSubData', data: 'PubSubSubscription')
Event.on_pubsub_twitch_poll_update: (self, raw: 'PubSubData', poll: 'PubSubPollData')
Event.on_pubsub_user_follow: (self, raw: 'PubSubData', data: 'PubSubFollow')
Event.on_bot_shutdown: (self)
Event.on_after_database_init(self) # used for triggering database operations after the bot starts
```
if this is the first time running the bot it will generate a folder named `configs`.
inside is `config.json` which you put the authentication into
as the bot is used it will also generate channel permission files in the `configs` folder
# Adding Commands
to register your own commands use the Command decorator:
* Using decorators
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME')
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
* you can also limit the commands to be whisper or channel chat only
(default is channel chat only)
```python
from twitchbot import Command, CommandContext, Message
# other options are CommandContext.BOTH and CommandContext.WHISPER
@Command('COMMAND_NAME', context=CommandContext.CHANNEL) # this is the default command context
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
* you can also specify if a permission is required to be able to call the command (if no permission is specified anyone
can call the command):
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME', permission='PERMISSION_NAME')
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
* you can also specify a help/syntax for the command for the help chat command to give into on it:
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME', help='this command does a very important thing!', syntax='<name>')
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
so when you do `!help COMMAND_NAME`
it will this in chat:
```
help for "!command_name",
syntax: "<name>",
help: "this command does a very important thing!"
```
* you can add aliases for a command (other command names that refer to the same command):
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME',
help='this command does a very important thing!',
syntax='<name>',
aliases=['COMMAND_NAME_2', 'COMMAND_NAME_3'])
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
`COMMAND_NAME_2` and `COMMAND_NAME_2` both refer to `COMMAND_NAME` and all three execute the same command
# SubCommands
the SubCommand class makes it easier to implement different actions based on a parameters passed to a command.
its the same as normal command except thats its not a global command
example: `!say` could be its own command, then it could have the sub-commands `!say myname` or `!say motd`.
you can implements this using something like this:
```python
from twitchbot import Command, Message
@Command('say')
async def cmd_say(msg: Message, *args):
# args is empty
if not args:
await msg.reply("you didn't give me any arguments :(")
return
arg = args[0].lower()
if arg == 'myname':
await msg.reply(f'hello {msg.mention}!')
elif arg == 'motd':
await msg.reply('the message of the day is: python is awesome')
else:
await msg.reply(' '.join(args))
```
that works, but it can be done in a nicer way using the `SubCommand` class:
```python
from twitchbot import Command, SubCommand, Message
@Command('say')
async def cmd_say(msg: Message, *args):
await msg.reply(' '.join(args))
# we pass the parent command as the first parameter
@SubCommand(cmd_say, 'myname')
async def cmd_say_myname(msg: Message):
await msg.reply(f'hello {msg.mention}!')
@SubCommand(cmd_say, 'motd')
async def cmd_say_motd(msg: Message):
await msg.reply('the message of the day is: python is awesome')
```
both ways do the same thing, what you proffer to use is up to you, but it does make it easier to manage for larger
commands to use SubCommand class
# DummyCommands
this class is basically a command that does nothing when executed, its mainly use is to be used as base command for
sub-command-only commands
it has all the same options as a regular Command
when a dummy command is executed it looks for sub-commands with a matching name as the first argument passed to it
if no command is found then it will say in chat the available sub-commands
but if a command is found it executes that command
say you want a command to greet someone, but you always want to pass the language, you can do this:
```python
from twitchbot import DummyCommand, SubCommand, Message
# cmd_greet does nothing itself when called
cmd_greet = DummyCommand('greet')
@SubCommand(cmd_greet, 'english')
async def cmd_greet_english(msg: Message):
await msg.reply(f'hello {msg.mention}!')
@SubCommand(cmd_greet, 'spanish')
async def cmd_greet_spanish(msg: Message):
await msg.reply(f'hola {msg.mention}!')
```
doing just `!greet` will make the bot say:
```text
command options: {english, spanish}
```
doing `!greet english` will make the bot say this:
```text
hello @johndoe!
```
doing `!greet spanish` will make the bot say this:
```text
hola @johndoe!
```
# Config
the default config values are:
```json
{
"nick": "nick",
"oauth": "oauth:",
"client_id": "CLIENT_ID",
"prefix": "!",
"default_balance": 200,
"loyalty_interval": 60,
"loyalty_amount": 2,
"owner": "BOT_OWNER_NAME",
"channels": [
"channel"
],
"mods_folder": "mods",
"commands_folder": "commands",
"command_server_enabled": true,
"command_server_port": 1337,
"command_server_host": "localhost",
"disable_whispers": false,
"use_command_whitelist": false,
"send_message_on_command_whitelist_deny": true,
"command_whitelist": [
"help",
"commands",
"reloadcmdwhitelist",
"reloadmod",
"reloadperms",
"disablemod",
"enablemod",
"disablecmdglobal",
"disablecmd",
"enablecmdglobal",
"enablecmd",
"addcmd",
"delcmd",
"updatecmd",
"cmd"
]
}
```
`oauth` is the twitch oauth used to login
`client_id` is the client_id used to get info like channel title, ect ( this is not required but twitch API info will
not be available without it )
`nick` is the twitch accounts nickname
`prefix` is the command prefix the bot will use for commands that dont use custom prefixes
`default_balance `is the default balance for new users that dont already have a economy balance
`owner` is the bot's owner
`channels` in the twitch channels the bot will join
`loyalty_interval` the interval for which the viewers will given currency for watching the stream, gives amount
specified by `loyalty_amount`
`loyalty_amount` the amount of currency to give viewers every `loyalty_interval`
`command_server_enabled` specifies if the command server should be enabled (see [Command Server](#command-server) for
more info)
`command_server_port` the port for the command server
`command_server_host` the host name (address) for the command server
`disable_whispers` is this value is set to `true` all whispers will be converted to regular channel messages
`use_command_whitelist` enabled or disables the command whitelist (see [Command Whitelist](#command-whitelist))
`send_message_on_command_whitelist_deny` should the bot tell users when you try to use a non-whitelisted command?
`command_whitelist` json array of commands whitelisted without their prefix (only applicable
if [Command Whitelist](#command-whitelist) is enabled)
# Permissions
the bot comes default with permission support
there are two ways to manage permissions,
1. using chat commands
2. editing JSON permission files
## managing permissions using chat commands
to add a permission group: `!addgroup <group>`, ex: `!addgroup donators`
to add a member to a group: `!addmember <group> <user>`, ex:
`!addmember donators johndoe`
to add a permission to a group: `!addperm <group> <permission>`, ex:
`!addperm donators slap`
to remove a group: `!delgroup <group>`, ex: `!delgroup donators`
to remove a member from a group: `!delmember <group> <member>`, ex:
`!delmember donators johndoe`
to remove a permission from a group: `!delperm <group> <permission>`, ex:
`!delperm donators slap`
### tip: revoking permission for a group (aka negating permissions)
to revoke a permission for a group, add the same permission but with a - in front of it
ex: you can to prevent group B from using permission `feed` from group A.
Simply add its negated version to group B: `-feed`, this PREVENTS group B from having the permission `feed` from group A
## managing permission by editing the configs
find the `configs` folder the bot generated (will be in same directory as the script that run the bot)
inside you will find `config.json` with the bot config values required for authentication with twitch and such
if the bot has joined any channels then you will see file names that look like `CHANNELNAME_perms.json`
for this example i will use a `johndoe`
so if you open `johndoe_perms.json` you will see this if you have not changed anything in it:
```json
{
"admin": {
"name": "admin",
"permissions": [
"*"
],
"members": [
"johndoe"
]
}
}
```
`name` is the name of the permission group
`permissions` is the list of permissions the group has
("*" is the "god" permission, granting access to all bot commands)
`members` is the members of the group
to add more permission groups by editing the config you can just copy/paste the default one
(be sure to remove the "god" permission if you dont them having access to all bot commands)
so after copy/pasting the default group it will look like this
(dont forget to separate the groups using `,`):
```json
{
"admin": {
"name": "admin",
"permissions": [
"*"
],
"members": [
"johndoe"
]
},
"donator": {
"name": "donator",
"permissions": [
"slap"
],
"members": [
"johndoe"
]
}
}
```
# Reloading Permissions
if the bot is running be sure to do `!reloadperms` to load the changes to the permission file
# Command Server
The command server is a small Socket Server the bot host that lets the Command Console be able to make the bot send
messages given to it through a console. (see [Command Console](#command-console))
The server can be enabled or disabled through the config (see [Config](#config)), the server's port and host are
specified by the config file
# Command Console
If the [Command Server](#command-server) is disabled in the [config](#config) the Command Console cannot be used
The Command Console is used to make the bot send chat messages and commands
To launch the Command Console make sure the bot is running, and the [Command Server](#command-server) is enabled in
the [Config](#config),
after verifying these are done, simply do `python command_console.py` to open the console, upon opening it you will be
prompted to select a twitch channel that the bot is currently connected to.
after choose the channel the prompt changes to `(CHANNEL_HERE):` and you are now able to send chat messages / commands
to the choosen channel by typing your message and pressing enter
# Database Support
to enabled database support
* open `configs/database_config.json` (if its missing run the bot and close it, this should
generate `database_config.json`)
* set `enabled` to `true`
* fill in `address`, `port`, `username`, `password`, and `database` (you will need to edit `driver`/`database_format` if
you use something other than mysql or sqlite)
* install the mysql library (if needed) FOR MYSQL INSTALL: `pip install --upgrade --user mysql-connector-python`, or any
other database supported by sqlalchemy, see the
sqlalchemy [engines](https://docs.sqlalchemy.org/en/13/core/engines.html). like for example POSTGRES:
`pip install --upgrade psycopg2`
* rerun the bot
# Command Whitelist
Command whitelist is a optional feature that only allows certain commands to be used (specified in the config)
it is disabled by default, but can be enabled by setting `use_command_whitelist` to `true` in `configs/config.json`
Command Whitelist limits what commands are enabled / usable on the bot
if a command that is not whitelisted is ran, it will tell the command caller that it is not whitelisted
if `send_message_on_command_whitelist_deny` is set to `true`, otherwise it will silently NOT RUN the command
whitelisted commands can be edited with the `command_whitelist` json-array in `configs/config.json`
to edit the command whitelist, you can add or remove elements from the `command_whitelist` json-array, do not include
the command's prefix, AKA `!command` becomes `command` in `command_whitelist`
### To reload the whitelist, restart the bot, or do `!reloadcmdwhitelist` in your the twitch chat (requires having `manage_commands` permission)
# Twitch PubSub Client
## what is pubsub?
pubsub is the way twitch sends certain events to subscribers to the topic it originates from
all topics are listed under the `PubSubTopics`
enum [found here](https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/twitchbot/pubsub/topics.py)
## Requirements
### Step 1: creating a developer application
to create a twitch developer application [generate one here](https://dev.twitch.tv/console/apps), this requires the
account have two-factor enabled
1. visit [https://dev.twitch.tv/console/apps](https://dev.twitch.tv/console/apps)
1. click `+ Register new application`
1. for redirect uri set it as `https://twitchapps.com/tmi/`, then click `add`
1. for the purpose of the application, select `Chat Bot`
1. for name, you can do anything, as long as it does not contain `twitch` in it
1. finally, create the application
## Step 2: generating a new irc oauth access token with the new client_id
this step is needed because twitch requires that oauth tokens used in API calls be generated the client_id sent in the
api request
after you create the application click it and copy its client id, then paste it into the bot's config.json file located
at `configs/config.json` for the field `client_id`, like so:
```json
{
"client_id": "CLIENT_ID_HERE"
}
```
now you need to generate a oauth for the bot's primary irc oauth that matches the client_id, there is a utility i
made [HERE](https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/util/token_utils.py) to help with token
authorization URL generation
using that utility, add this code to the bottom of the util script .py file, you would generate the URL like so:
```python
print(generate_irc_oauth('CLIENT_ID_HERE', 'REDIRECT_URI_HERE'))
```
OR just replace the values in this auth url:
```
https://id.twitch.tv/oauth2/authorize?response_type=token&client_id=<CLIENT_ID>&redirect_uri=<REDIRECT_URI>&scope=chat:read+chat:edit+channel:moderate+whispers:read+whispers:edit+channel_editor
```
open a browser window that is logged into your bot account and visit the values-replaced authorization URL
after you authorize it, copy the oauth access token and paste it into the bot's config for the value of `oauth`, ex:
```json
{
"oauth": "oauth:<OAUTH_HERE>"
}
```
this ensures that API calls still work.
## Step 3: creating the pubsub oauth access token
this oauth token is responsible for actually allowing the bot to access oauth topics on a specific channel
the list of scopes needed for different topics can be found [HERE](https://dev.twitch.tv/docs/pubsub#topics), each topic
has its own scope it needs, all the scope permissions as strings for my util script can be found here:
[https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/util/token_utils.py#L4](https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/util/token_utils.py#L4)
(if you dont want to use the util script just use this url and add the needed
info: `https://id.twitch.tv/oauth2/authorize?response_type=token&client_id={client_id}&redirect_uri={redirect}&scope={scopes}`
, scopes are separated with a + in the url)
(the following will use my util script, this also assumes you have downloaded/copied the token utility script as well)
to create the pubsub token, first decide on WHAT topics it needs to listen to, i will use `PubSubTopics.channel_points`
with this example
using the utility script, you can call `generate_auth_url` to generate the authorization URL for you
```python
print(generate_auth_url('CLIENT_ID_HERE', 'REDIRECT_URI_HERE', Scopes.PUBSUB_CHANNEL_POINTS))
```
### Required OAuth Scopes for PubSub topics
```
|____________________________|______________________________|
| TOPIC | REQUIRED OAUTH SCOPE |
|____________________________|______________________________|
followers -> channel_editor
polls -> channel_editor
bits -> bits:read
bits badge notification -> bits:read
channel points -> channel:read:redemptions
community channel points -> (not sure, seems to be included in the irc oauth)
channel subscriptions -> channel_subscriptions
chat (aka moderation actions) -> channel:moderate
whispers -> whispers:read
channel subscriptions -> channel_subscriptions
```
the `[PubSubTopics.channel_points]` is the list of scopes to add to the authorization request url
after the URL is printed, copy it and visit/send the url to owner of the channel that you want pubsub access to
in the case of it being your own channel its much more simple, since you just need to visit it on your main account and
copy the oauth access code
## Using the pubsub oauth
1. go to the bot's folder/directory on the computer running
1. look for the `mods` folder
1. create `pubsub_subscribe.py` in the `mods` directory
1. paste the following template in it:
```python
from twitchbot import PubSubTopics, Mod, get_pubsub
class PubSubSubscriberMod(Mod):
async def on_connected(self):
await get_pubsub().listen_to_channel('CHANNEL_HERE', [PubSubTopics.channel_points],
access_token='PUBSUB_OAUTH_HERE')
# only needed in most cases for verifying a connection
# this can be removed once verified
async def on_pubsub_received(self, raw: 'PubSubData'):
# this should print any errors received from twitch
print(raw.raw_data)
```
after a successful pubsub connection is established, you can override the appropriate event (some pubsub topics dont
have a event yet, so use on_pubsub_received for those)
following the above example we will override the `Event.on_pubsub_custom_channel_point_reward` event
```python
from twitchbot import PubSubTopics, Mod, get_pubsub
class PubSubSubscriberMod(Mod):
async def on_connected(self):
await get_pubsub().listen_to_channel('CHANNEL_HERE', [PubSubTopics.channel_points],
access_token='PUBSUB_OAUTH_HERE')
# only needed in most cases for verifying a connection
# this can be removed once verified
async def on_pubsub_received(self, raw: 'PubSubData'):
# this should print any errors received from twitch
print(raw.raw_data)
# twitch only sends non-default channel point rewards over pubsub
async def on_pubsub_custom_channel_point_reward(self, raw: 'PubSubData', data: 'PubSubPointRedemption'):
print(f'{data.user_display_name} has redeemed {data.reward_title}')
```
that pretty much summarized how to use pubsub, if you have any more questions, or need help, do visit my discord server
or subreddit (found at top of this readme)
%package -n python3-PythonTwitchBotFramework
Summary: asynchronous twitch-bot framework made in pure python
Provides: python-PythonTwitchBotFramework
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-PythonTwitchBotFramework
# if you have any questions concerning the bot, you can contact me in my discord server: https://discord.gg/PXrKVHp OR [r/pythontwitchbot](https://www.reddit.com/r/pythontwitchbot/) on reddit
if you would like to send a few dollars my way you can do so
here: [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=9ZVUE7CR24738)
this bot is also on PYPI: https://pypi.org/project/PythonTwitchBotFramework/
install from pip: `pip install PythonTwitchBotFramework`
# PythonTwitchBotFramework
fully async twitchbot framework/library compatible with python 3.6+
First and foremost, I want to thank anyone who uses this, or even is just reading this readme,
and to any contributors who have helped with updates/features.
## Note about the wiki and readme right now:
I am in the process of adding missing info to the wiki/readme,
and also updating to show the new command argument handling added in 2.7.0+.
(referring to the fact the command system now supporting and enforcing typehints, and not requiring *args anymore)
As well as some features i didn't put in the wiki or readme yet.
If you are any version earlier than 2.7.0, some things showcased/described on the wiki may not work for you.
## How to stop the bot
to stop the bot running, do any of these commands:
`!shutdown` or `!stop` in the twitch chat of the channel its in, this command tries to properly shutdown all the
tasks the bot is currently running and gives time to stop/cancel
these commands require the caller have permission to execute them
# Note:
### This readme only goes over basic info meant to help quickly get something working, the [GITHUB WIKI](https://github.com/sharkbound/PythonTwitchBotFramework/wiki) goes more in depth.
# Index
* [Quick Start](#quick-start)
* [Overriding Events](#overriding-events)
* [Overriding Events On Mods](#overriding-events-on-mods)
* [Adding Commands](#adding-commands)
* [SubCommands](#subcommands)
* [DummyCommands](#dummycommands)
* [Permissions](#permissions)
* [Using Chat Commands](#managing-permissions-using-chat-commands)
* [Editing The Config](#managing-permission-by-editing-the-configs)
* [Reloading Permissions](#reloading-permissions)
* [Command Server](#command-server)
* [Command Console](#command-console)
* [Database Support](#database-support)
* [Command Whitelist](#command-whitelist)
* [Twitch PubSub Client](#twitch-pubsub-client)
# Basic info
This is a fully async twitch bot framework complete with:
* builtin command system using decorators
* overridable events (message received, whisper received, ect)
* full permission system that is individual for each channel
* message timers
* quotes
* custom commands
* builtin economy
there is also mod system builtin to the bot, there is a collection of pre-made mods
here: [MODS](https://github.com/sharkbound/twitch_bot_mods)
# Quick Start
for a reference for builtin command look at the
wiki [HERE](https://github.com/sharkbound/PythonTwitchBotFramework/wiki/Builtin_Command_Reference)
the minimum code to get the bot running is this:
```python
from twitchbot import BaseBot
if __name__ == '__main__':
BaseBot().run()
```
this will start the bot.
if you have a folder with your own custom commands you can load the .py files in it with:
```python
from twitchbot import BaseBot
if __name__ == '__main__':
BaseBot().run()
```
# Overriding Events
the bots events are overridable via the following 2 ways:
## Using decorators:
```python
from twitchbot import event_handler, Event, Message
@event_handler(Event.on_privmsg_received)
async def on_privmsg_received(msg: Message):
print(f'{msg.author} sent message {msg.content} to channel {msg.channel_name}')
```
## Subclassing BaseBot
```python
from twitchbot import BaseBot, Message
class MyCustomTwitchBot(BaseBot):
async def on_privmsg_received(self, msg: Message):
print(f'{msg.author} sent message {msg.content} to channel {msg.channel_name}')
```
then you would use MyCustomTwitchBot instead of BaseBot:
```python
MyCustomTwitchBot().run()
```
## Overriding Events On Mods
Visit [***the mods wiki page***](https://github.com/sharkbound/PythonTwitchBotFramework/wiki/Mods#index)
on this repo's wiki to view how to do it via Mods
* all overridable events are:
#### when using the decorator event override way, `self` is not included, ex: `(self, msg: Message)` becomes: `(msg: Message)`
```python
from twitchbot import Event
Event.on_connected: (self)
Event.on_permission_check: (self, msg
: Message, cmd: Command) -> Optional[
bool] # return False to deny permission to execute the cmd, Return None to ignore and continue
Event.on_after_command_execute: (self, msg: Message, cmd: Command)
Event.on_before_command_execute: (self, msg: Message, cmd: Command) -> bool # return False to cancel command
Event.on_bits_donated: (self, msg: Message, bits: int)
Event.on_channel_raided: (self, channel: Channel, raider: str, viewer_count: int)
Event.on_channel_joined: (self, channel: Channel)
Event.on_channel_subscription: (self, subscriber: str, channel: Channel, msg: Message)
Event.on_privmsg_received: (self, msg: Message)
Event.on_privmsg_sent: (self, msg: str, channel: str, sender: str)
Event.on_whisper_received: (self, msg: Message)
Event.on_whisper_sent: (self, msg: str, receiver: str, sender: str)
Event.on_raw_message: (self, msg: Message)
Event.on_user_join: (self, user: str, channel: Channel)
Event.on_user_part: (self, user: str, channel: Channel)
Event.on_mod_reloaded: (self, mod: Mod)
Event.on_channel_points_redemption: (self, msg: Message, reward: str)
Event.on_bot_timed_out_from_channel: (self, msg: Message, channel: Channel, seconds: int)
Event.on_bot_banned_from_channel: (self, msg: Message, channel: Channel)
Event.on_poll_started: (self, channel: Channel, poll: PollData)
Event.on_poll_ended: (self, channel: Channel, poll: PollData)
Event.on_pubsub_received: (self, raw: 'PubSubData')
Event.on_pubsub_custom_channel_point_reward: (self, raw: 'PubSubData', data: 'PubSubPointRedemption')
Event.on_pubsub_bits: (self, raw: 'PubSubData', data: 'PubSubBits')
Event.on_pubsub_moderation_action: (self, raw: 'PubSubData', data: 'PubSubModerationAction')
Event.on_pubsub_subscription: (self, raw: 'PubSubData', data: 'PubSubSubscription')
Event.on_pubsub_twitch_poll_update: (self, raw: 'PubSubData', poll: 'PubSubPollData')
Event.on_pubsub_user_follow: (self, raw: 'PubSubData', data: 'PubSubFollow')
Event.on_bot_shutdown: (self)
Event.on_after_database_init(self) # used for triggering database operations after the bot starts
```
if this is the first time running the bot it will generate a folder named `configs`.
inside is `config.json` which you put the authentication into
as the bot is used it will also generate channel permission files in the `configs` folder
# Adding Commands
to register your own commands use the Command decorator:
* Using decorators
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME')
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
* you can also limit the commands to be whisper or channel chat only
(default is channel chat only)
```python
from twitchbot import Command, CommandContext, Message
# other options are CommandContext.BOTH and CommandContext.WHISPER
@Command('COMMAND_NAME', context=CommandContext.CHANNEL) # this is the default command context
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
* you can also specify if a permission is required to be able to call the command (if no permission is specified anyone
can call the command):
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME', permission='PERMISSION_NAME')
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
* you can also specify a help/syntax for the command for the help chat command to give into on it:
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME', help='this command does a very important thing!', syntax='<name>')
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
so when you do `!help COMMAND_NAME`
it will this in chat:
```
help for "!command_name",
syntax: "<name>",
help: "this command does a very important thing!"
```
* you can add aliases for a command (other command names that refer to the same command):
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME',
help='this command does a very important thing!',
syntax='<name>',
aliases=['COMMAND_NAME_2', 'COMMAND_NAME_3'])
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
`COMMAND_NAME_2` and `COMMAND_NAME_2` both refer to `COMMAND_NAME` and all three execute the same command
# SubCommands
the SubCommand class makes it easier to implement different actions based on a parameters passed to a command.
its the same as normal command except thats its not a global command
example: `!say` could be its own command, then it could have the sub-commands `!say myname` or `!say motd`.
you can implements this using something like this:
```python
from twitchbot import Command, Message
@Command('say')
async def cmd_say(msg: Message, *args):
# args is empty
if not args:
await msg.reply("you didn't give me any arguments :(")
return
arg = args[0].lower()
if arg == 'myname':
await msg.reply(f'hello {msg.mention}!')
elif arg == 'motd':
await msg.reply('the message of the day is: python is awesome')
else:
await msg.reply(' '.join(args))
```
that works, but it can be done in a nicer way using the `SubCommand` class:
```python
from twitchbot import Command, SubCommand, Message
@Command('say')
async def cmd_say(msg: Message, *args):
await msg.reply(' '.join(args))
# we pass the parent command as the first parameter
@SubCommand(cmd_say, 'myname')
async def cmd_say_myname(msg: Message):
await msg.reply(f'hello {msg.mention}!')
@SubCommand(cmd_say, 'motd')
async def cmd_say_motd(msg: Message):
await msg.reply('the message of the day is: python is awesome')
```
both ways do the same thing, what you proffer to use is up to you, but it does make it easier to manage for larger
commands to use SubCommand class
# DummyCommands
this class is basically a command that does nothing when executed, its mainly use is to be used as base command for
sub-command-only commands
it has all the same options as a regular Command
when a dummy command is executed it looks for sub-commands with a matching name as the first argument passed to it
if no command is found then it will say in chat the available sub-commands
but if a command is found it executes that command
say you want a command to greet someone, but you always want to pass the language, you can do this:
```python
from twitchbot import DummyCommand, SubCommand, Message
# cmd_greet does nothing itself when called
cmd_greet = DummyCommand('greet')
@SubCommand(cmd_greet, 'english')
async def cmd_greet_english(msg: Message):
await msg.reply(f'hello {msg.mention}!')
@SubCommand(cmd_greet, 'spanish')
async def cmd_greet_spanish(msg: Message):
await msg.reply(f'hola {msg.mention}!')
```
doing just `!greet` will make the bot say:
```text
command options: {english, spanish}
```
doing `!greet english` will make the bot say this:
```text
hello @johndoe!
```
doing `!greet spanish` will make the bot say this:
```text
hola @johndoe!
```
# Config
the default config values are:
```json
{
"nick": "nick",
"oauth": "oauth:",
"client_id": "CLIENT_ID",
"prefix": "!",
"default_balance": 200,
"loyalty_interval": 60,
"loyalty_amount": 2,
"owner": "BOT_OWNER_NAME",
"channels": [
"channel"
],
"mods_folder": "mods",
"commands_folder": "commands",
"command_server_enabled": true,
"command_server_port": 1337,
"command_server_host": "localhost",
"disable_whispers": false,
"use_command_whitelist": false,
"send_message_on_command_whitelist_deny": true,
"command_whitelist": [
"help",
"commands",
"reloadcmdwhitelist",
"reloadmod",
"reloadperms",
"disablemod",
"enablemod",
"disablecmdglobal",
"disablecmd",
"enablecmdglobal",
"enablecmd",
"addcmd",
"delcmd",
"updatecmd",
"cmd"
]
}
```
`oauth` is the twitch oauth used to login
`client_id` is the client_id used to get info like channel title, ect ( this is not required but twitch API info will
not be available without it )
`nick` is the twitch accounts nickname
`prefix` is the command prefix the bot will use for commands that dont use custom prefixes
`default_balance `is the default balance for new users that dont already have a economy balance
`owner` is the bot's owner
`channels` in the twitch channels the bot will join
`loyalty_interval` the interval for which the viewers will given currency for watching the stream, gives amount
specified by `loyalty_amount`
`loyalty_amount` the amount of currency to give viewers every `loyalty_interval`
`command_server_enabled` specifies if the command server should be enabled (see [Command Server](#command-server) for
more info)
`command_server_port` the port for the command server
`command_server_host` the host name (address) for the command server
`disable_whispers` is this value is set to `true` all whispers will be converted to regular channel messages
`use_command_whitelist` enabled or disables the command whitelist (see [Command Whitelist](#command-whitelist))
`send_message_on_command_whitelist_deny` should the bot tell users when you try to use a non-whitelisted command?
`command_whitelist` json array of commands whitelisted without their prefix (only applicable
if [Command Whitelist](#command-whitelist) is enabled)
# Permissions
the bot comes default with permission support
there are two ways to manage permissions,
1. using chat commands
2. editing JSON permission files
## managing permissions using chat commands
to add a permission group: `!addgroup <group>`, ex: `!addgroup donators`
to add a member to a group: `!addmember <group> <user>`, ex:
`!addmember donators johndoe`
to add a permission to a group: `!addperm <group> <permission>`, ex:
`!addperm donators slap`
to remove a group: `!delgroup <group>`, ex: `!delgroup donators`
to remove a member from a group: `!delmember <group> <member>`, ex:
`!delmember donators johndoe`
to remove a permission from a group: `!delperm <group> <permission>`, ex:
`!delperm donators slap`
### tip: revoking permission for a group (aka negating permissions)
to revoke a permission for a group, add the same permission but with a - in front of it
ex: you can to prevent group B from using permission `feed` from group A.
Simply add its negated version to group B: `-feed`, this PREVENTS group B from having the permission `feed` from group A
## managing permission by editing the configs
find the `configs` folder the bot generated (will be in same directory as the script that run the bot)
inside you will find `config.json` with the bot config values required for authentication with twitch and such
if the bot has joined any channels then you will see file names that look like `CHANNELNAME_perms.json`
for this example i will use a `johndoe`
so if you open `johndoe_perms.json` you will see this if you have not changed anything in it:
```json
{
"admin": {
"name": "admin",
"permissions": [
"*"
],
"members": [
"johndoe"
]
}
}
```
`name` is the name of the permission group
`permissions` is the list of permissions the group has
("*" is the "god" permission, granting access to all bot commands)
`members` is the members of the group
to add more permission groups by editing the config you can just copy/paste the default one
(be sure to remove the "god" permission if you dont them having access to all bot commands)
so after copy/pasting the default group it will look like this
(dont forget to separate the groups using `,`):
```json
{
"admin": {
"name": "admin",
"permissions": [
"*"
],
"members": [
"johndoe"
]
},
"donator": {
"name": "donator",
"permissions": [
"slap"
],
"members": [
"johndoe"
]
}
}
```
# Reloading Permissions
if the bot is running be sure to do `!reloadperms` to load the changes to the permission file
# Command Server
The command server is a small Socket Server the bot host that lets the Command Console be able to make the bot send
messages given to it through a console. (see [Command Console](#command-console))
The server can be enabled or disabled through the config (see [Config](#config)), the server's port and host are
specified by the config file
# Command Console
If the [Command Server](#command-server) is disabled in the [config](#config) the Command Console cannot be used
The Command Console is used to make the bot send chat messages and commands
To launch the Command Console make sure the bot is running, and the [Command Server](#command-server) is enabled in
the [Config](#config),
after verifying these are done, simply do `python command_console.py` to open the console, upon opening it you will be
prompted to select a twitch channel that the bot is currently connected to.
after choose the channel the prompt changes to `(CHANNEL_HERE):` and you are now able to send chat messages / commands
to the choosen channel by typing your message and pressing enter
# Database Support
to enabled database support
* open `configs/database_config.json` (if its missing run the bot and close it, this should
generate `database_config.json`)
* set `enabled` to `true`
* fill in `address`, `port`, `username`, `password`, and `database` (you will need to edit `driver`/`database_format` if
you use something other than mysql or sqlite)
* install the mysql library (if needed) FOR MYSQL INSTALL: `pip install --upgrade --user mysql-connector-python`, or any
other database supported by sqlalchemy, see the
sqlalchemy [engines](https://docs.sqlalchemy.org/en/13/core/engines.html). like for example POSTGRES:
`pip install --upgrade psycopg2`
* rerun the bot
# Command Whitelist
Command whitelist is a optional feature that only allows certain commands to be used (specified in the config)
it is disabled by default, but can be enabled by setting `use_command_whitelist` to `true` in `configs/config.json`
Command Whitelist limits what commands are enabled / usable on the bot
if a command that is not whitelisted is ran, it will tell the command caller that it is not whitelisted
if `send_message_on_command_whitelist_deny` is set to `true`, otherwise it will silently NOT RUN the command
whitelisted commands can be edited with the `command_whitelist` json-array in `configs/config.json`
to edit the command whitelist, you can add or remove elements from the `command_whitelist` json-array, do not include
the command's prefix, AKA `!command` becomes `command` in `command_whitelist`
### To reload the whitelist, restart the bot, or do `!reloadcmdwhitelist` in your the twitch chat (requires having `manage_commands` permission)
# Twitch PubSub Client
## what is pubsub?
pubsub is the way twitch sends certain events to subscribers to the topic it originates from
all topics are listed under the `PubSubTopics`
enum [found here](https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/twitchbot/pubsub/topics.py)
## Requirements
### Step 1: creating a developer application
to create a twitch developer application [generate one here](https://dev.twitch.tv/console/apps), this requires the
account have two-factor enabled
1. visit [https://dev.twitch.tv/console/apps](https://dev.twitch.tv/console/apps)
1. click `+ Register new application`
1. for redirect uri set it as `https://twitchapps.com/tmi/`, then click `add`
1. for the purpose of the application, select `Chat Bot`
1. for name, you can do anything, as long as it does not contain `twitch` in it
1. finally, create the application
## Step 2: generating a new irc oauth access token with the new client_id
this step is needed because twitch requires that oauth tokens used in API calls be generated the client_id sent in the
api request
after you create the application click it and copy its client id, then paste it into the bot's config.json file located
at `configs/config.json` for the field `client_id`, like so:
```json
{
"client_id": "CLIENT_ID_HERE"
}
```
now you need to generate a oauth for the bot's primary irc oauth that matches the client_id, there is a utility i
made [HERE](https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/util/token_utils.py) to help with token
authorization URL generation
using that utility, add this code to the bottom of the util script .py file, you would generate the URL like so:
```python
print(generate_irc_oauth('CLIENT_ID_HERE', 'REDIRECT_URI_HERE'))
```
OR just replace the values in this auth url:
```
https://id.twitch.tv/oauth2/authorize?response_type=token&client_id=<CLIENT_ID>&redirect_uri=<REDIRECT_URI>&scope=chat:read+chat:edit+channel:moderate+whispers:read+whispers:edit+channel_editor
```
open a browser window that is logged into your bot account and visit the values-replaced authorization URL
after you authorize it, copy the oauth access token and paste it into the bot's config for the value of `oauth`, ex:
```json
{
"oauth": "oauth:<OAUTH_HERE>"
}
```
this ensures that API calls still work.
## Step 3: creating the pubsub oauth access token
this oauth token is responsible for actually allowing the bot to access oauth topics on a specific channel
the list of scopes needed for different topics can be found [HERE](https://dev.twitch.tv/docs/pubsub#topics), each topic
has its own scope it needs, all the scope permissions as strings for my util script can be found here:
[https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/util/token_utils.py#L4](https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/util/token_utils.py#L4)
(if you dont want to use the util script just use this url and add the needed
info: `https://id.twitch.tv/oauth2/authorize?response_type=token&client_id={client_id}&redirect_uri={redirect}&scope={scopes}`
, scopes are separated with a + in the url)
(the following will use my util script, this also assumes you have downloaded/copied the token utility script as well)
to create the pubsub token, first decide on WHAT topics it needs to listen to, i will use `PubSubTopics.channel_points`
with this example
using the utility script, you can call `generate_auth_url` to generate the authorization URL for you
```python
print(generate_auth_url('CLIENT_ID_HERE', 'REDIRECT_URI_HERE', Scopes.PUBSUB_CHANNEL_POINTS))
```
### Required OAuth Scopes for PubSub topics
```
|____________________________|______________________________|
| TOPIC | REQUIRED OAUTH SCOPE |
|____________________________|______________________________|
followers -> channel_editor
polls -> channel_editor
bits -> bits:read
bits badge notification -> bits:read
channel points -> channel:read:redemptions
community channel points -> (not sure, seems to be included in the irc oauth)
channel subscriptions -> channel_subscriptions
chat (aka moderation actions) -> channel:moderate
whispers -> whispers:read
channel subscriptions -> channel_subscriptions
```
the `[PubSubTopics.channel_points]` is the list of scopes to add to the authorization request url
after the URL is printed, copy it and visit/send the url to owner of the channel that you want pubsub access to
in the case of it being your own channel its much more simple, since you just need to visit it on your main account and
copy the oauth access code
## Using the pubsub oauth
1. go to the bot's folder/directory on the computer running
1. look for the `mods` folder
1. create `pubsub_subscribe.py` in the `mods` directory
1. paste the following template in it:
```python
from twitchbot import PubSubTopics, Mod, get_pubsub
class PubSubSubscriberMod(Mod):
async def on_connected(self):
await get_pubsub().listen_to_channel('CHANNEL_HERE', [PubSubTopics.channel_points],
access_token='PUBSUB_OAUTH_HERE')
# only needed in most cases for verifying a connection
# this can be removed once verified
async def on_pubsub_received(self, raw: 'PubSubData'):
# this should print any errors received from twitch
print(raw.raw_data)
```
after a successful pubsub connection is established, you can override the appropriate event (some pubsub topics dont
have a event yet, so use on_pubsub_received for those)
following the above example we will override the `Event.on_pubsub_custom_channel_point_reward` event
```python
from twitchbot import PubSubTopics, Mod, get_pubsub
class PubSubSubscriberMod(Mod):
async def on_connected(self):
await get_pubsub().listen_to_channel('CHANNEL_HERE', [PubSubTopics.channel_points],
access_token='PUBSUB_OAUTH_HERE')
# only needed in most cases for verifying a connection
# this can be removed once verified
async def on_pubsub_received(self, raw: 'PubSubData'):
# this should print any errors received from twitch
print(raw.raw_data)
# twitch only sends non-default channel point rewards over pubsub
async def on_pubsub_custom_channel_point_reward(self, raw: 'PubSubData', data: 'PubSubPointRedemption'):
print(f'{data.user_display_name} has redeemed {data.reward_title}')
```
that pretty much summarized how to use pubsub, if you have any more questions, or need help, do visit my discord server
or subreddit (found at top of this readme)
%package help
Summary: Development documents and examples for PythonTwitchBotFramework
Provides: python3-PythonTwitchBotFramework-doc
%description help
# if you have any questions concerning the bot, you can contact me in my discord server: https://discord.gg/PXrKVHp OR [r/pythontwitchbot](https://www.reddit.com/r/pythontwitchbot/) on reddit
if you would like to send a few dollars my way you can do so
here: [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=9ZVUE7CR24738)
this bot is also on PYPI: https://pypi.org/project/PythonTwitchBotFramework/
install from pip: `pip install PythonTwitchBotFramework`
# PythonTwitchBotFramework
fully async twitchbot framework/library compatible with python 3.6+
First and foremost, I want to thank anyone who uses this, or even is just reading this readme,
and to any contributors who have helped with updates/features.
## Note about the wiki and readme right now:
I am in the process of adding missing info to the wiki/readme,
and also updating to show the new command argument handling added in 2.7.0+.
(referring to the fact the command system now supporting and enforcing typehints, and not requiring *args anymore)
As well as some features i didn't put in the wiki or readme yet.
If you are any version earlier than 2.7.0, some things showcased/described on the wiki may not work for you.
## How to stop the bot
to stop the bot running, do any of these commands:
`!shutdown` or `!stop` in the twitch chat of the channel its in, this command tries to properly shutdown all the
tasks the bot is currently running and gives time to stop/cancel
these commands require the caller have permission to execute them
# Note:
### This readme only goes over basic info meant to help quickly get something working, the [GITHUB WIKI](https://github.com/sharkbound/PythonTwitchBotFramework/wiki) goes more in depth.
# Index
* [Quick Start](#quick-start)
* [Overriding Events](#overriding-events)
* [Overriding Events On Mods](#overriding-events-on-mods)
* [Adding Commands](#adding-commands)
* [SubCommands](#subcommands)
* [DummyCommands](#dummycommands)
* [Permissions](#permissions)
* [Using Chat Commands](#managing-permissions-using-chat-commands)
* [Editing The Config](#managing-permission-by-editing-the-configs)
* [Reloading Permissions](#reloading-permissions)
* [Command Server](#command-server)
* [Command Console](#command-console)
* [Database Support](#database-support)
* [Command Whitelist](#command-whitelist)
* [Twitch PubSub Client](#twitch-pubsub-client)
# Basic info
This is a fully async twitch bot framework complete with:
* builtin command system using decorators
* overridable events (message received, whisper received, ect)
* full permission system that is individual for each channel
* message timers
* quotes
* custom commands
* builtin economy
there is also mod system builtin to the bot, there is a collection of pre-made mods
here: [MODS](https://github.com/sharkbound/twitch_bot_mods)
# Quick Start
for a reference for builtin command look at the
wiki [HERE](https://github.com/sharkbound/PythonTwitchBotFramework/wiki/Builtin_Command_Reference)
the minimum code to get the bot running is this:
```python
from twitchbot import BaseBot
if __name__ == '__main__':
BaseBot().run()
```
this will start the bot.
if you have a folder with your own custom commands you can load the .py files in it with:
```python
from twitchbot import BaseBot
if __name__ == '__main__':
BaseBot().run()
```
# Overriding Events
the bots events are overridable via the following 2 ways:
## Using decorators:
```python
from twitchbot import event_handler, Event, Message
@event_handler(Event.on_privmsg_received)
async def on_privmsg_received(msg: Message):
print(f'{msg.author} sent message {msg.content} to channel {msg.channel_name}')
```
## Subclassing BaseBot
```python
from twitchbot import BaseBot, Message
class MyCustomTwitchBot(BaseBot):
async def on_privmsg_received(self, msg: Message):
print(f'{msg.author} sent message {msg.content} to channel {msg.channel_name}')
```
then you would use MyCustomTwitchBot instead of BaseBot:
```python
MyCustomTwitchBot().run()
```
## Overriding Events On Mods
Visit [***the mods wiki page***](https://github.com/sharkbound/PythonTwitchBotFramework/wiki/Mods#index)
on this repo's wiki to view how to do it via Mods
* all overridable events are:
#### when using the decorator event override way, `self` is not included, ex: `(self, msg: Message)` becomes: `(msg: Message)`
```python
from twitchbot import Event
Event.on_connected: (self)
Event.on_permission_check: (self, msg
: Message, cmd: Command) -> Optional[
bool] # return False to deny permission to execute the cmd, Return None to ignore and continue
Event.on_after_command_execute: (self, msg: Message, cmd: Command)
Event.on_before_command_execute: (self, msg: Message, cmd: Command) -> bool # return False to cancel command
Event.on_bits_donated: (self, msg: Message, bits: int)
Event.on_channel_raided: (self, channel: Channel, raider: str, viewer_count: int)
Event.on_channel_joined: (self, channel: Channel)
Event.on_channel_subscription: (self, subscriber: str, channel: Channel, msg: Message)
Event.on_privmsg_received: (self, msg: Message)
Event.on_privmsg_sent: (self, msg: str, channel: str, sender: str)
Event.on_whisper_received: (self, msg: Message)
Event.on_whisper_sent: (self, msg: str, receiver: str, sender: str)
Event.on_raw_message: (self, msg: Message)
Event.on_user_join: (self, user: str, channel: Channel)
Event.on_user_part: (self, user: str, channel: Channel)
Event.on_mod_reloaded: (self, mod: Mod)
Event.on_channel_points_redemption: (self, msg: Message, reward: str)
Event.on_bot_timed_out_from_channel: (self, msg: Message, channel: Channel, seconds: int)
Event.on_bot_banned_from_channel: (self, msg: Message, channel: Channel)
Event.on_poll_started: (self, channel: Channel, poll: PollData)
Event.on_poll_ended: (self, channel: Channel, poll: PollData)
Event.on_pubsub_received: (self, raw: 'PubSubData')
Event.on_pubsub_custom_channel_point_reward: (self, raw: 'PubSubData', data: 'PubSubPointRedemption')
Event.on_pubsub_bits: (self, raw: 'PubSubData', data: 'PubSubBits')
Event.on_pubsub_moderation_action: (self, raw: 'PubSubData', data: 'PubSubModerationAction')
Event.on_pubsub_subscription: (self, raw: 'PubSubData', data: 'PubSubSubscription')
Event.on_pubsub_twitch_poll_update: (self, raw: 'PubSubData', poll: 'PubSubPollData')
Event.on_pubsub_user_follow: (self, raw: 'PubSubData', data: 'PubSubFollow')
Event.on_bot_shutdown: (self)
Event.on_after_database_init(self) # used for triggering database operations after the bot starts
```
if this is the first time running the bot it will generate a folder named `configs`.
inside is `config.json` which you put the authentication into
as the bot is used it will also generate channel permission files in the `configs` folder
# Adding Commands
to register your own commands use the Command decorator:
* Using decorators
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME')
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
* you can also limit the commands to be whisper or channel chat only
(default is channel chat only)
```python
from twitchbot import Command, CommandContext, Message
# other options are CommandContext.BOTH and CommandContext.WHISPER
@Command('COMMAND_NAME', context=CommandContext.CHANNEL) # this is the default command context
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
* you can also specify if a permission is required to be able to call the command (if no permission is specified anyone
can call the command):
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME', permission='PERMISSION_NAME')
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
* you can also specify a help/syntax for the command for the help chat command to give into on it:
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME', help='this command does a very important thing!', syntax='<name>')
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
so when you do `!help COMMAND_NAME`
it will this in chat:
```
help for "!command_name",
syntax: "<name>",
help: "this command does a very important thing!"
```
* you can add aliases for a command (other command names that refer to the same command):
```python
from twitchbot import Command, Message
@Command('COMMAND_NAME',
help='this command does a very important thing!',
syntax='<name>',
aliases=['COMMAND_NAME_2', 'COMMAND_NAME_3'])
async def cmd_function(msg: Message):
await msg.reply('i was called!')
```
`COMMAND_NAME_2` and `COMMAND_NAME_2` both refer to `COMMAND_NAME` and all three execute the same command
# SubCommands
the SubCommand class makes it easier to implement different actions based on a parameters passed to a command.
its the same as normal command except thats its not a global command
example: `!say` could be its own command, then it could have the sub-commands `!say myname` or `!say motd`.
you can implements this using something like this:
```python
from twitchbot import Command, Message
@Command('say')
async def cmd_say(msg: Message, *args):
# args is empty
if not args:
await msg.reply("you didn't give me any arguments :(")
return
arg = args[0].lower()
if arg == 'myname':
await msg.reply(f'hello {msg.mention}!')
elif arg == 'motd':
await msg.reply('the message of the day is: python is awesome')
else:
await msg.reply(' '.join(args))
```
that works, but it can be done in a nicer way using the `SubCommand` class:
```python
from twitchbot import Command, SubCommand, Message
@Command('say')
async def cmd_say(msg: Message, *args):
await msg.reply(' '.join(args))
# we pass the parent command as the first parameter
@SubCommand(cmd_say, 'myname')
async def cmd_say_myname(msg: Message):
await msg.reply(f'hello {msg.mention}!')
@SubCommand(cmd_say, 'motd')
async def cmd_say_motd(msg: Message):
await msg.reply('the message of the day is: python is awesome')
```
both ways do the same thing, what you proffer to use is up to you, but it does make it easier to manage for larger
commands to use SubCommand class
# DummyCommands
this class is basically a command that does nothing when executed, its mainly use is to be used as base command for
sub-command-only commands
it has all the same options as a regular Command
when a dummy command is executed it looks for sub-commands with a matching name as the first argument passed to it
if no command is found then it will say in chat the available sub-commands
but if a command is found it executes that command
say you want a command to greet someone, but you always want to pass the language, you can do this:
```python
from twitchbot import DummyCommand, SubCommand, Message
# cmd_greet does nothing itself when called
cmd_greet = DummyCommand('greet')
@SubCommand(cmd_greet, 'english')
async def cmd_greet_english(msg: Message):
await msg.reply(f'hello {msg.mention}!')
@SubCommand(cmd_greet, 'spanish')
async def cmd_greet_spanish(msg: Message):
await msg.reply(f'hola {msg.mention}!')
```
doing just `!greet` will make the bot say:
```text
command options: {english, spanish}
```
doing `!greet english` will make the bot say this:
```text
hello @johndoe!
```
doing `!greet spanish` will make the bot say this:
```text
hola @johndoe!
```
# Config
the default config values are:
```json
{
"nick": "nick",
"oauth": "oauth:",
"client_id": "CLIENT_ID",
"prefix": "!",
"default_balance": 200,
"loyalty_interval": 60,
"loyalty_amount": 2,
"owner": "BOT_OWNER_NAME",
"channels": [
"channel"
],
"mods_folder": "mods",
"commands_folder": "commands",
"command_server_enabled": true,
"command_server_port": 1337,
"command_server_host": "localhost",
"disable_whispers": false,
"use_command_whitelist": false,
"send_message_on_command_whitelist_deny": true,
"command_whitelist": [
"help",
"commands",
"reloadcmdwhitelist",
"reloadmod",
"reloadperms",
"disablemod",
"enablemod",
"disablecmdglobal",
"disablecmd",
"enablecmdglobal",
"enablecmd",
"addcmd",
"delcmd",
"updatecmd",
"cmd"
]
}
```
`oauth` is the twitch oauth used to login
`client_id` is the client_id used to get info like channel title, ect ( this is not required but twitch API info will
not be available without it )
`nick` is the twitch accounts nickname
`prefix` is the command prefix the bot will use for commands that dont use custom prefixes
`default_balance `is the default balance for new users that dont already have a economy balance
`owner` is the bot's owner
`channels` in the twitch channels the bot will join
`loyalty_interval` the interval for which the viewers will given currency for watching the stream, gives amount
specified by `loyalty_amount`
`loyalty_amount` the amount of currency to give viewers every `loyalty_interval`
`command_server_enabled` specifies if the command server should be enabled (see [Command Server](#command-server) for
more info)
`command_server_port` the port for the command server
`command_server_host` the host name (address) for the command server
`disable_whispers` is this value is set to `true` all whispers will be converted to regular channel messages
`use_command_whitelist` enabled or disables the command whitelist (see [Command Whitelist](#command-whitelist))
`send_message_on_command_whitelist_deny` should the bot tell users when you try to use a non-whitelisted command?
`command_whitelist` json array of commands whitelisted without their prefix (only applicable
if [Command Whitelist](#command-whitelist) is enabled)
# Permissions
the bot comes default with permission support
there are two ways to manage permissions,
1. using chat commands
2. editing JSON permission files
## managing permissions using chat commands
to add a permission group: `!addgroup <group>`, ex: `!addgroup donators`
to add a member to a group: `!addmember <group> <user>`, ex:
`!addmember donators johndoe`
to add a permission to a group: `!addperm <group> <permission>`, ex:
`!addperm donators slap`
to remove a group: `!delgroup <group>`, ex: `!delgroup donators`
to remove a member from a group: `!delmember <group> <member>`, ex:
`!delmember donators johndoe`
to remove a permission from a group: `!delperm <group> <permission>`, ex:
`!delperm donators slap`
### tip: revoking permission for a group (aka negating permissions)
to revoke a permission for a group, add the same permission but with a - in front of it
ex: you can to prevent group B from using permission `feed` from group A.
Simply add its negated version to group B: `-feed`, this PREVENTS group B from having the permission `feed` from group A
## managing permission by editing the configs
find the `configs` folder the bot generated (will be in same directory as the script that run the bot)
inside you will find `config.json` with the bot config values required for authentication with twitch and such
if the bot has joined any channels then you will see file names that look like `CHANNELNAME_perms.json`
for this example i will use a `johndoe`
so if you open `johndoe_perms.json` you will see this if you have not changed anything in it:
```json
{
"admin": {
"name": "admin",
"permissions": [
"*"
],
"members": [
"johndoe"
]
}
}
```
`name` is the name of the permission group
`permissions` is the list of permissions the group has
("*" is the "god" permission, granting access to all bot commands)
`members` is the members of the group
to add more permission groups by editing the config you can just copy/paste the default one
(be sure to remove the "god" permission if you dont them having access to all bot commands)
so after copy/pasting the default group it will look like this
(dont forget to separate the groups using `,`):
```json
{
"admin": {
"name": "admin",
"permissions": [
"*"
],
"members": [
"johndoe"
]
},
"donator": {
"name": "donator",
"permissions": [
"slap"
],
"members": [
"johndoe"
]
}
}
```
# Reloading Permissions
if the bot is running be sure to do `!reloadperms` to load the changes to the permission file
# Command Server
The command server is a small Socket Server the bot host that lets the Command Console be able to make the bot send
messages given to it through a console. (see [Command Console](#command-console))
The server can be enabled or disabled through the config (see [Config](#config)), the server's port and host are
specified by the config file
# Command Console
If the [Command Server](#command-server) is disabled in the [config](#config) the Command Console cannot be used
The Command Console is used to make the bot send chat messages and commands
To launch the Command Console make sure the bot is running, and the [Command Server](#command-server) is enabled in
the [Config](#config),
after verifying these are done, simply do `python command_console.py` to open the console, upon opening it you will be
prompted to select a twitch channel that the bot is currently connected to.
after choose the channel the prompt changes to `(CHANNEL_HERE):` and you are now able to send chat messages / commands
to the choosen channel by typing your message and pressing enter
# Database Support
to enabled database support
* open `configs/database_config.json` (if its missing run the bot and close it, this should
generate `database_config.json`)
* set `enabled` to `true`
* fill in `address`, `port`, `username`, `password`, and `database` (you will need to edit `driver`/`database_format` if
you use something other than mysql or sqlite)
* install the mysql library (if needed) FOR MYSQL INSTALL: `pip install --upgrade --user mysql-connector-python`, or any
other database supported by sqlalchemy, see the
sqlalchemy [engines](https://docs.sqlalchemy.org/en/13/core/engines.html). like for example POSTGRES:
`pip install --upgrade psycopg2`
* rerun the bot
# Command Whitelist
Command whitelist is a optional feature that only allows certain commands to be used (specified in the config)
it is disabled by default, but can be enabled by setting `use_command_whitelist` to `true` in `configs/config.json`
Command Whitelist limits what commands are enabled / usable on the bot
if a command that is not whitelisted is ran, it will tell the command caller that it is not whitelisted
if `send_message_on_command_whitelist_deny` is set to `true`, otherwise it will silently NOT RUN the command
whitelisted commands can be edited with the `command_whitelist` json-array in `configs/config.json`
to edit the command whitelist, you can add or remove elements from the `command_whitelist` json-array, do not include
the command's prefix, AKA `!command` becomes `command` in `command_whitelist`
### To reload the whitelist, restart the bot, or do `!reloadcmdwhitelist` in your the twitch chat (requires having `manage_commands` permission)
# Twitch PubSub Client
## what is pubsub?
pubsub is the way twitch sends certain events to subscribers to the topic it originates from
all topics are listed under the `PubSubTopics`
enum [found here](https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/twitchbot/pubsub/topics.py)
## Requirements
### Step 1: creating a developer application
to create a twitch developer application [generate one here](https://dev.twitch.tv/console/apps), this requires the
account have two-factor enabled
1. visit [https://dev.twitch.tv/console/apps](https://dev.twitch.tv/console/apps)
1. click `+ Register new application`
1. for redirect uri set it as `https://twitchapps.com/tmi/`, then click `add`
1. for the purpose of the application, select `Chat Bot`
1. for name, you can do anything, as long as it does not contain `twitch` in it
1. finally, create the application
## Step 2: generating a new irc oauth access token with the new client_id
this step is needed because twitch requires that oauth tokens used in API calls be generated the client_id sent in the
api request
after you create the application click it and copy its client id, then paste it into the bot's config.json file located
at `configs/config.json` for the field `client_id`, like so:
```json
{
"client_id": "CLIENT_ID_HERE"
}
```
now you need to generate a oauth for the bot's primary irc oauth that matches the client_id, there is a utility i
made [HERE](https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/util/token_utils.py) to help with token
authorization URL generation
using that utility, add this code to the bottom of the util script .py file, you would generate the URL like so:
```python
print(generate_irc_oauth('CLIENT_ID_HERE', 'REDIRECT_URI_HERE'))
```
OR just replace the values in this auth url:
```
https://id.twitch.tv/oauth2/authorize?response_type=token&client_id=<CLIENT_ID>&redirect_uri=<REDIRECT_URI>&scope=chat:read+chat:edit+channel:moderate+whispers:read+whispers:edit+channel_editor
```
open a browser window that is logged into your bot account and visit the values-replaced authorization URL
after you authorize it, copy the oauth access token and paste it into the bot's config for the value of `oauth`, ex:
```json
{
"oauth": "oauth:<OAUTH_HERE>"
}
```
this ensures that API calls still work.
## Step 3: creating the pubsub oauth access token
this oauth token is responsible for actually allowing the bot to access oauth topics on a specific channel
the list of scopes needed for different topics can be found [HERE](https://dev.twitch.tv/docs/pubsub#topics), each topic
has its own scope it needs, all the scope permissions as strings for my util script can be found here:
[https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/util/token_utils.py#L4](https://github.com/sharkbound/PythonTwitchBotFramework/blob/master/util/token_utils.py#L4)
(if you dont want to use the util script just use this url and add the needed
info: `https://id.twitch.tv/oauth2/authorize?response_type=token&client_id={client_id}&redirect_uri={redirect}&scope={scopes}`
, scopes are separated with a + in the url)
(the following will use my util script, this also assumes you have downloaded/copied the token utility script as well)
to create the pubsub token, first decide on WHAT topics it needs to listen to, i will use `PubSubTopics.channel_points`
with this example
using the utility script, you can call `generate_auth_url` to generate the authorization URL for you
```python
print(generate_auth_url('CLIENT_ID_HERE', 'REDIRECT_URI_HERE', Scopes.PUBSUB_CHANNEL_POINTS))
```
### Required OAuth Scopes for PubSub topics
```
|____________________________|______________________________|
| TOPIC | REQUIRED OAUTH SCOPE |
|____________________________|______________________________|
followers -> channel_editor
polls -> channel_editor
bits -> bits:read
bits badge notification -> bits:read
channel points -> channel:read:redemptions
community channel points -> (not sure, seems to be included in the irc oauth)
channel subscriptions -> channel_subscriptions
chat (aka moderation actions) -> channel:moderate
whispers -> whispers:read
channel subscriptions -> channel_subscriptions
```
the `[PubSubTopics.channel_points]` is the list of scopes to add to the authorization request url
after the URL is printed, copy it and visit/send the url to owner of the channel that you want pubsub access to
in the case of it being your own channel its much more simple, since you just need to visit it on your main account and
copy the oauth access code
## Using the pubsub oauth
1. go to the bot's folder/directory on the computer running
1. look for the `mods` folder
1. create `pubsub_subscribe.py` in the `mods` directory
1. paste the following template in it:
```python
from twitchbot import PubSubTopics, Mod, get_pubsub
class PubSubSubscriberMod(Mod):
async def on_connected(self):
await get_pubsub().listen_to_channel('CHANNEL_HERE', [PubSubTopics.channel_points],
access_token='PUBSUB_OAUTH_HERE')
# only needed in most cases for verifying a connection
# this can be removed once verified
async def on_pubsub_received(self, raw: 'PubSubData'):
# this should print any errors received from twitch
print(raw.raw_data)
```
after a successful pubsub connection is established, you can override the appropriate event (some pubsub topics dont
have a event yet, so use on_pubsub_received for those)
following the above example we will override the `Event.on_pubsub_custom_channel_point_reward` event
```python
from twitchbot import PubSubTopics, Mod, get_pubsub
class PubSubSubscriberMod(Mod):
async def on_connected(self):
await get_pubsub().listen_to_channel('CHANNEL_HERE', [PubSubTopics.channel_points],
access_token='PUBSUB_OAUTH_HERE')
# only needed in most cases for verifying a connection
# this can be removed once verified
async def on_pubsub_received(self, raw: 'PubSubData'):
# this should print any errors received from twitch
print(raw.raw_data)
# twitch only sends non-default channel point rewards over pubsub
async def on_pubsub_custom_channel_point_reward(self, raw: 'PubSubData', data: 'PubSubPointRedemption'):
print(f'{data.user_display_name} has redeemed {data.reward_title}')
```
that pretty much summarized how to use pubsub, if you have any more questions, or need help, do visit my discord server
or subreddit (found at top of this readme)
%prep
%autosetup -n PythonTwitchBotFramework-2.10.2
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-PythonTwitchBotFramework -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Tue Apr 25 2023 Python_Bot <Python_Bot@openeuler.org> - 2.10.2-1
- Package Spec generated
|