-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtwitch.py
More file actions
4135 lines (2994 loc) · 132 KB
/
Copy pathtwitch.py
File metadata and controls
4135 lines (2994 loc) · 132 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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
# %%
'''
TO DO:
The EventSub is so complex to keep going...OAUTH, reverse DNS, Packet Riot, LetsEncrypt, custom domain....
I might just read the chat and react there.
Read StreamElements messages
- X has been a s-ranked ninja for y months in a row
- X just threw down X bits!
- X gifted a Tier 1 sub
- X just smoke-bombed into lurk mode. They're still here, but as silent as a feather in the wind.... and will be back when you least expect it!
- X is raiding
Others
!lurk
KofiStreamBot
- visit XtianNinja page
'''
print("")
print("=============================================")
print("== Twitch.py =")
print("=============================================")
print("")
import os
#os.system('cls||clear')
import sys
import re # regular expression
import LEDarcade as LED
#from rgbmatrix import graphics
#from rgbmatrix import RGBMatrix, RGBMatrixOptions
import random
from configparser import ConfigParser
import requests
import traceback
import socket
#multi processing
import asyncio
import multiprocessing
from multiprocessing import Process, Queue
import time
from flask import Flask, request, abort
from multiprocessing.connection import Client
import json
#Twitch
import twitchio
from twitchio.ext import commands, eventsub
#from twitchAPI.eventsub.webhook import EventSubWebhook
#from twitchAPI.object.eventsub import ChannelFollowEvent
from twitchAPI.twitch import Twitch
#Webhooks
#import patreon
#import flask
#from flask import Flask, request, abort
import pprint
import copy
import irc.bot
import select
#list of connection messages
from CustomMessages import ConnectionMessages
from CustomMessages import ChatStartMessages
import time
from datetime import datetime, timezone
#games
#import DotInvaders as DI
#import Outbreak as OB
#import Defender as DE
#import Tron as TR
#import SpaceDot as SD
#---------------------------------------
#Variable declaration section
#---------------------------------------
ScrollSleep = 0.025
TerminalTypeSpeed = 0.02 #pause in seconds between characters
TerminalScrollSpeed = 0.02 #pause in seconds between new lines
CursorRGB = (0,255,0)
CursorDarkRGB = (0,50,0)
RotateClockDelay = 10 #minutes between each clock rotation (launch an LEDarcade display every X minutes using LEDcommander)
ClockDuration = 1
#TWITCH VARIABLES
#LEDARCADE_APP_ACCESS_TOKEN = ''
#REFRESH_TOKEN = ''
#LEDARCADE_APP_CLIENT_ID = ''
#LEDARCADE_APP_CLIENT_SECRET = ''
BROADCASTER_CHANNEL = ''
CHANNEL_BIG_TEXT = ''
CHANNEL_LITTLE_TEXT = ''
BROADCASTER_USER_ID = ''
BROADCASTER_ID = ''
PROFILE_IMAGE_URL = ''
VIEW_COUNT = ''
THECLOCKBOT_CHANNEL = ''
THECLOCKBOT_ACCESS_TOKEN = ''
THECLOCKBOT_REFRESH_TOKEN = ''
CLOCKBOT_X_ACCESS_TOKEN = ''
CLOCKBOT_X_REFRESH_TOKEN = ''
#BOT_REFRESH_TOKEN = ''
THECLOCKBOT_CLIENT_ID = ''
THECLOCKBOT_USER_ID = ''
THECLOCKBOT_SECRET = ''
TWITCH_WEBHOOK_URL = ''
TWITCH_WEBHOOK_SECRET = ''
#PATREON VARIABLES
PATREON_CLIENT_ID = ''
PATREON_CLIENT_SECRET = ''
PATREON_CREATOR_ACCESS_TOKEN = ''
PATREON_WEBHOOK_URL = ''
PATREON_WEBHOOK_SECRET = ''
#User / Channel Info
GameName = ''
Title = ''
# Stream Info
StreamStartedAt = ''
StreamStartedTime = ''
StreamStartedDateTime = ''
StreamDurationHHMMSS = ''
StreamType = ''
ViewerCount = 0
StreamActive = False
#Follower Info
Followers = 0
Subs = 0
ChatUserListCount = 25
ChatUserListWaitSeconds = 30
#HypeTrain info
HypeTrainStartTime = ''
HypeTrainExpireTime = ''
HypeTrainGoal = ''
HypeTrainLevel = 0
HypeTrainTotal = ''
HatHeight = 32
HatWidth = 64
StreamBrightness = 80
GifBrightness = 80
MaxBrightness = 100
#Configurations
SHOW_VIEWERS = True
SHOW_FOLLOWERS = False
SHOW_SUBS = True
SHOW_VIEWS = True
SHOW_CHATBOT_MESSAGES = False
#Files
KeyConfigFileName = "KeyConfig.ini"
MyConfigFileName = "MyConfig.ini"
#Colors
TerminalRGB = (0,200,0)
CursorRGB = (0,75,0)
#Data structures
#EventQueue = asyncio.Queue() #used to store and process chat messages
# Global variables for LEDcommander
CommandQueue = None
CommandProcess = None
#----------------------------------------------------------------------------
# FUNCTIONS
#----------------------------------------------------------------------------
def get_viewer_message(viewer_count):
templates = [
"There are currently {} viewers enjoying the show.",
"You're not alone—{} people are tuned in right now!",
"{} awesome folks are watching this stream.",
"Look at that! {} viewers are here with us.",
"{} viewers, one amazing broadcast.",
"Shoutout to all {} viewers joining us!",
"Currently, {} fine folks are watching.",
"{} legends are watching this epic moment.",
"{} people are vibing with us live!",
"Streaming live to {} amazing fans.",
"We've got {} watchers on deck.",
"Audience check: {} viewers present!",
"{} people can’t be wrong—this stream rocks.",
"{} online and counting!",
"Roll call: {} people are in the stream.",
"This just in—{} viewers locked in!",
"Bringing joy to {} viewers at the moment.",
"{} people decided to spend their time here. Excellent choice!",
"Thank you to our {} viewers!",
"{} streamers strong and going!",
"Currently captivating {} eyeballs.",
"Lighting up screens for {} people.",
"{} people are enjoying the pixel party.",
"This moment is shared with {} viewers.",
"Hats off to all {} watching this live.",
"{} tuned in for this adventure!"
]
message = random.choice(templates).format(viewer_count)
return message
def get_personal_hello_response(user_name):
responses = [
f"Hello there, {user_name}!",
f"Hey hey, {user_name}!",
f"What's up, {user_name}?",
f"Howdy partner, {user_name}!",
f"Greetings, {user_name}.",
f"Yo, {user_name}!",
f"Hiya, {user_name}!",
f"Ahoy, {user_name}!",
f"Hey you, {user_name}!",
f"Well well well, look who's here: {user_name}!",
f"Oh no, it's you again... {user_name}.",
f"Welcome back, {user_name}!",
f"Hey, it's nice to see you, {user_name}!",
f"You're just in time, {user_name}!",
f"Brace yourself, {user_name} is here!",
f"Hi {user_name}. Need anything?",
f"Let's get this party started, {user_name}!",
f"Oh wow, hello {user_name}!",
f"What's crackin', {user_name}?",
f"Hola amigo, {user_name}!",
f"Bonjour, {user_name}!",
f"Ciao, {user_name}!",
f"Kon'nichiwa, {user_name}!",
f"Why hello there, {user_name}, fancy meeting you here.",
f"Greeeetingssss... from the void, {user_name}.",
]
return random.choice(responses)
def GetElapsedSeconds(starttime):
elapsed_seconds = time.time() - starttime
return elapsed_seconds
#
#We are now spawning a separate process to control the LED display
'''
def SpawnClock(EventQueue, AnimationDelay, StreamActive, SharedState):
try:
import LEDarcade as LED
LED.Initialize()
LED.ReinitializeMatrix()
LED.InitializeColors()
LED.TheMatrix.brightness = 100 # force brightness again
LED.ClearBigLED()
LED.ClearBuffers()
print("SpawnClock: Matrix brightness =", LED.TheMatrix.brightness)
print("Red:",LED.MedRed," ShadowRed: ",LED.ShadowRed)
print("SpawnClock - Begin")
SharedState['DigitalClockSpawned'] = True
print(f"DigitalClockSpawned set to: {SharedState['DigitalClockSpawned']}")
r = random.choice([1, 3])
zoom = 3 if StreamActive else 2
print(f"ClockStyle: {r}, Zoom: {zoom}")
LED.DisplayDigitalClock(
ClockStyle=1, # change back to r later
CenterHoriz=True,
v=1,
hh=24,
RGB=(255,0,0),
ShadowRGB=(255,255,255),
ZoomFactor=zoom,
AnimationDelay=AnimationDelay,
RunMinutes=1,
EventQueue=EventQueue
)
except Exception as e:
print(f"[ERROR] SpawnClock crashed: {e}")
traceback.print_exc()
finally:
SharedState['DigitalClockSpawned'] = False
print("SpawnClock - Completed")
print(f"DigitalClockSpawned set to: {SharedState['DigitalClockSpawned']}")
'''
class Bot(commands.Bot ):
#This started out as a Twitch Bot but has grown into a more complex program
CursorH = 0
CursorV = 0
CursorRGB = (0,255,0)
CursorDarkRGB = (0,50,0)
AnimationDelay = 30
LastMessageReceived = time.time()
LastUserJoinedChat = time.time()
ChatUsers = []
SecondsToWaitChat = 30
LastStreamCheckTime = time.time()
LastChatInfoTime = time.time()
MinutesToWaitBeforeCheckingStream = 5 #check the stream this often
MinutesToWaitBeforeChatInfo = 180 #send info message to viewers about clock commands
MinutesToWaitBeforeClosing = 0 #close chat after X minutes of inactivity
#MinutesMaxTime = 10 #exit chat terminal after X minutes and display clock
BotStartTime = time.time()
SendStartupMessage = True
BotTypeSpeed = TerminalTypeSpeed
BotScrollSpeed = TerminalScrollSpeed
MessageCount = 0
SpeedupMessageCount = 5
ChatTerminalOn = False
Channel = ''
ClockRunning = False # <== Added flag to show if uptime clock is running
def __init__(self,EventQueue=None):
self.EventQueue = EventQueue #old, being replaced
# Initialise our Bot with our access token, prefix and a list of channels to join on boot...
# prefix can be a callable, which returns a list of strings or a string...
# initial_channels can also be a callable which returns a list of strings...
# Note: the bot client id is from Twitch Dev TheClockBot.
print("Bot Initialization")
print("THECLOCKBOT_CLIENT_ID: ",THECLOCKBOT_CLIENT_ID)
print("THECLOCKBOT_CLIENT_ID: ",THECLOCKBOT_USER_ID)
print("THECLOCKBOT_SECRET: ",THECLOCKBOT_SECRET)
print("THECLOCKBOT_CHANNEL: ",THECLOCKBOT_CHANNEL)
print("THECLOCKBOT_CODE: ",THECLOCKBOT_CODE)
print("THECLOCKBOT_ACCESS_TOKEN: ",THECLOCKBOT_ACCESS_TOKEN)
print("THECLOCKBOT_REFRESH_TOKEN:",THECLOCKBOT_REFRESH_TOKEN)
print("")
print("")
print("")
print("=====================================================")
print("Initiating client object to connect to twitch")
print("Initial_Channels:",BROADCASTER_CHANNEL)
super().__init__(token=THECLOCKBOT_ACCESS_TOKEN, prefix='?', initial_channels=[BROADCASTER_CHANNEL])
self.BotStartTime = time.time()
LastMessageReceived = time.time()
#time.sleep(3)
print("=====================================================")
print("")
async def my_custom_startup(self):
global CommandQueue
await asyncio.sleep(1)
self.Channel = self.get_channel(BROADCASTER_CHANNEL)
#channel2 = self.fetch_channel(CHANNEL_ID)
#Check Twitch advanced info
await self.CheckStream()
if(StreamActive == True and SHOW_CHATBOT_MESSAGES == True):
self.ChatTerminalOn = True
elif(StreamActive == False and SHOW_CHATBOT_MESSAGES == True):
#Explain the main intro is not live
CommandQueue.put({
"Action": "ShowTitleScreen",
"BigText": "404",
"BigTextRGB": LED.MedPurple,
"BigTextShadowRGB": LED.ShadowPurple,
"LittleText": "NO STREAM",
"LittleTextRGB": LED.MedRed,
"LittleTextShadowRGB": LED.ShadowRed,
"ScrollText": BROADCASTER_CHANNEL + " not active. Try again later...",
"ScrollTextRGB": LED.MedYellow,
"ScrollSleep": ScrollSleep / 2,
"DisplayTime": 1,
"ExitEffect": 5,
"LittleTextZoom": 1
})
#---------------------------------------
#- Check Stream Info --
#---------------------------------------
# check to see if the stream is live or not
async def CheckStream(self):
print("Checking if stream is active")
GetBasicTwitchInfo()
self.LastStreamCheckTime = time.time()
#Show title info if Main stream is active
#---------------------------------------
#- Send Chat Message --
#---------------------------------------
async def SendChatMessage(self,Message):
await self.Channel.send(Message)
#---------------------------------------
#- Perform Time Based Actions --
#---------------------------------------
async def PerformTimeBasedActions(self):
global DigitalClockSpawned
loop = asyncio.get_running_loop()
if(StreamActive == True):
await self.DisplayRandomConnectionMessage()
while True:
await asyncio.sleep(5)
print("Stream Status:",StreamActive)
if(StreamActive == True):
if (self.ChatTerminalOn == True):
h,m,s = LED.GetElapsedTime(self.LastMessageReceived,time.time())
if (m >= self.MinutesToWaitBeforeClosing ):
CommandQueue.put({"Action": "terminalmessage", "Message": "No chat activity detected. Did everyone fall asleep?", "RGB": (100, 100, 0), "ScrollSleep": 0.03 })
CommandQueue.put({"Action": "terminalmessage", "Message": "Closing Terminal", "RGB": (100, 100, 0), "ScrollSleep": 0.03 })
CommandQueue.put({"Action": "terminalmessage", "Message": "................", "RGB": (100, 100, 0), "ScrollSleep": 0.03 })
CommandQueue.put({"Action": "terminalmode_off"})
self.ChatTerminalOn = False
self.ClockRunning = False # Reset clock flag when terminal closes
if(self.ChatTerminalOn == False and self.ClockRunning == False):
#print("[Twitch] Creating multiprocess DisplayDigitalClock()")
#self.DisplayDigitalClock()
self.ClockRunning = True
await self.RotateClockDisplays(RotateClockDelay)
#-------------------------------------------------------------------------
#-- If stream is not active, run a series of displays for X minutes each
#-------------------------------------------------------------------------
if (StreamActive == False):
print("[Twitch] StreamActive == False")
await self.RotateClockDisplays(RotateClockDelay)
h,m,s = LED.GetElapsedTime(self.LastChatInfoTime,time.time())
if (m >= self.MinutesToWaitBeforeChatInfo):
await self.SendChatMessage("Don't forget to interact with the LED display. Type ?clock for a list of commands.")
self.LastChatInfoTime = time.time()
h,m,s = LED.GetElapsedTime(self.LastStreamCheckTime,time.time())
if (m >= self.MinutesToWaitBeforeCheckingStream):
await self.CheckStream()
if(StreamActive == True):
self.LastStreamCheckTime = time.time()
#---------------------------------------
#- Event Ready --
#---------------------------------------
async def event_ready(self):
global CommandQueue
# Notify us when everything is ready!
# We are logged in and ready to chat and use commands...
#UserList = self.fetch_users()
print("")
print("=================================================")
print(f'Logged in as | {self.nick}')
#print("Channels logged in:', self.connected_channels.__len__())
#Channel = self.fetch_channel(CHANNEL)
#print(Channel)
print("=================================================")
print("")
#My custom startup code runs here
await self.my_custom_startup()
#await self.Sleep()
if(StreamActive == True):
#skip my own channel for testing purposes
if(BROADCASTER_CHANNEL != 'datagod' and BROADCASTER_CHANNEL.upper() != 'XTIANNINJA'):
# INTRO FOR MAIN CHANNEL
CommandQueue.put({
"Action": "ShowTitleScreen",
"BigText": CHANNEL_BIG_TEXT,
"BigTextRGB": LED.MedPurple,
"BigTextShadowRGB": LED.ShadowPurple,
"LittleText": CHANNEL_LITTLE_TEXT,
"LittleTextRGB": LED.MedRed,
"LittleTextShadowRGB": LED.ShadowRed,
"ScrollText": Title,
"ScrollTextRGB": LED.MedYellow,
"ScrollSleep": ScrollSleep,
"DisplayTime": 1,
"ExitEffect": 5,
"LittleTextZoom": 2
})
# SHOW FOLLOWERS
if SHOW_FOLLOWERS:
BigTextZoom = 2 if Followers > 9999 else 3
CommandQueue.put({
"Action": "ShowTitleScreen",
"BigText": str(Followers),
"BigTextRGB": LED.MedPurple,
"BigTextShadowRGB": LED.ShadowPurple,
"BigTextZoom": BigTextZoom,
"LittleText": "FOLLOWS",
"LittleTextRGB": LED.MedRed,
"LittleTextShadowRGB": LED.ShadowRed,
"ScrollText": "",
"ScrollTextRGB": LED.MedYellow,
"ScrollSleep": ScrollSleep,
"DisplayTime": 1,
"ExitEffect": 0
})
# SHOW VIEWERS
if SHOW_VIEWERS:
CommandQueue.put({
"Action": "ShowTitleScreen",
"BigText": str(ViewerCount),
"BigTextRGB": LED.MedPurple,
"BigTextShadowRGB": LED.ShadowPurple,
"BigTextZoom": 3,
"LittleText": "Viewers",
"LittleTextRGB": LED.MedRed,
"LittleTextShadowRGB": LED.ShadowRed,
"ScrollText": f"Now Playing: {GameName}",
"ScrollTextRGB": LED.MedYellow,
"ScrollSleep": ScrollSleep,
"DisplayTime": 1,
"ExitEffect": 1
})
# CHAT TERMINAL INTRO
CommandQueue.put({
"Action": "ShowTitleScreen",
"BigText": "CHAT",
"BigTextRGB": LED.MedRed,
"BigTextShadowRGB": LED.ShadowRed,
"LittleText": "TERMINAL",
"LittleTextRGB": LED.MedBlue,
"LittleTextShadowRGB": LED.ShadowBlue,
"ScrollText": f"TUNING IN TO {BROADCASTER_CHANNEL}",
"ScrollTextRGB": LED.MedOrange,
"ScrollSleep": ScrollSleep,
"DisplayTime": 1,
"ExitEffect": 0,
"LittleTextZoom": 1
})
await self.SendRandomChatGreeting()
await self.PerformTimeBasedActions()
#---------------------------------------
# Rotate Clock Displays --
#---------------------------------------
async def RotateClockDisplays(self, RotateClockDelay: int = 5):
#Blasteroids clock (style=5)
CommandQueue.put({ "Action": "showclock", "Style": 5, "Zoom": 1, "duration": 10, "Delay": 10 })
await asyncio.sleep(RotateClockDelay * 60)
CommandQueue.put({"Action": "retrodigital", "duration": 10 })
await asyncio.sleep(RotateClockDelay * 60)
#StarryNight clock display (style=3)
CommandQueue.put({ "Action": "showclock", "Style": 3, "Zoom": 2, "duration": 10, "Delay": 10 })
await asyncio.sleep(RotateClockDelay * 60)
self.DisplayDigitalClock(ClockDuration)
CommandQueue.put({"Action": "launch_defender2", "duration": 10 })
await asyncio.sleep(RotateClockDelay * 60)
self.DisplayDigitalClock(ClockDuration)
CommandQueue.put({"Action": "launch_dotinvaders", "duration": 10 })
await asyncio.sleep(RotateClockDelay * 60)
self.DisplayDigitalClock(ClockDuration)
CommandQueue.put({"Action": "launch_gravitysim", "duration": 10 })
await asyncio.sleep(RotateClockDelay * 60)
self.DisplayDigitalClock(ClockDuration)
CommandQueue.put({"Action": "launch_tron", "duration": 10 })
await asyncio.sleep(RotateClockDelay * 60)
self.DisplayDigitalClock(ClockDuration)
CommandQueue.put({"Action": "launch_outbreak", "duration": 10 })
await asyncio.sleep(RotateClockDelay * 60)
self.DisplayDigitalClock(ClockDuration)
CommandQueue.put({"Action": "launch_spacedot", "duration": 10 })
await asyncio.sleep(RotateClockDelay * 60)
self.DisplayDigitalClock(ClockDuration)
CommandQueue.put({"Action": "launch_fallingsand", "duration": 10 })
await asyncio.sleep(RotateClockDelay * 60)
self.DisplayDigitalClock(ClockDuration)
CommandQueue.put({"Action": "launch_skyfall", "duration": 10 })
await asyncio.sleep(RotateClockDelay * 60)
self.DisplayDigitalClock(ClockDuration)
#---------------------------------------
# READ CHAT MESSAGES --
#---------------------------------------
async def event_message(self, message):
print("Reading chat messages")
# Messages with echo set to True are messages sent by the bot...
# For now we just want to ignore them...
if message.echo:
return
# Since we have commands and are overriding the default `event_message`
# We must let the bot know we want to handle and invoke our commands...
await self.handle_commands(message)
# Check for special key words
#Remove emoji from message
message.content = LED.deEmojify(message.content)
author = message.author.display_name
#Log Chat
print('CHAT| ',author,':',message.content)
#---------------------------------------
# KOFI --
#---------------------------------------
if (author.upper() == 'KOFISTREAMBOT' and "VISIT" in message.content.upper()):
print("CHAT| KofiBot detected")
message = "Time for a Kofi"
await self.Channel.send(message)
Text1 = "KOFI"
Text2 = "WE APPRECIATE YOUR SUPPORT"
Text3 = "KOFI IS THE PREFERRED WAY TO SUPPORT THIS CHANNEL"
CommandQueue.put({"Action": "StarryNightDisplayText",
"text1": Text1,
"text2": Text2,
"text1": Text3}
)
#---------------------------------------
# Stream Elements --
#---------------------------------------
#TACO
if (author.upper() == 'STREAMELEMENTS' and "GROWING" in message.content.upper()):
print("CHAT| TACO detected")
Text1 = "TACO"
Text2 = "The Alliance for creative outreach"
Text3 = "visit taconetwork.org to learn all about us"
CommandQueue.put({"Action": "starrynightdisplaytext",
"text1": Text1,
"text2": Text2,
"text3": Text3}
)
#Dragon Coffee
if (author.upper() == 'STREAMELEMENTS' and "COFFEE" in message.content.upper()):
print("CHAT| TACO detected")
Text1 = "dragon roast coffee"
Text2 = "Great Nerd Coffee"
Text3 = "the thing that makes everything better"
CommandQueue.put({"Action": "starrynightdisplaytext",
"text1": Text1,
"text2": Text2,
"text3": Text3}
)
# Check for S-Ranked Ninja message
match = re.search(r'^(?P<username>\w+).+?S-Ranked Ninja for (?P<duration>\d+ months)', message.content)
if match:
username = match.group('username')
duration = match.group('duration')
print(f"CHAT| S-Ranked Ninja detected: {username}, {duration}")
CommandQueue.put({
"Action": "starrynightdisplaytext",
"text1": f"{username}",
"text2": "S-Ranked Ninja!",
"text3": f"{duration} strong!"
})
#BITS
#if (author == 'StreamElements' and message.content.upper() == ""):
if (author.upper() == 'STREAMELEMENTS' and "JUST THREW DOWN" in message.content.upper()):
print("CHAT| BITS detected")
words = message.content.split(" ")
BitGiver = words[0]
bits = words[4]
print("CHAT|",BitGiver,"just threw down ",bits," bits")
#LED.ClearBigLED()
#LED.ClearBuffers()
Text1 = BitGiver + " just threw down " + bits + " bits"
Text2 = "Thank you " + BitGiver
Text3 = "Bits are an important part of the economy. Your contribution is appreciated!"
CommandQueue.put({"Action": "StarryNightDisplayText",
"text1": Text1,
"text2": Text2,
"text1": Text3}
)
#FOLLOWING
#if (author == 'StreamElements' and message.content.upper() == "is raiding"):
if (author.upper() == 'STREAMELEMENTS' and "THANK YOU FOR FOLLOWING" in message.content.upper()):
print("CHAT| follow detected")
words = message.content.split(" ")
follower = words[4]
print("CHAT|",follower,"is now following")
Text1 = follower + " is now following"
Text2 = "Thank you " + follower
Text3 = "Welcome to our community. We appreciate you joining us!",
CommandQueue.put({"Action": "StarryNightDisplayText",
"text1": Text1,
"text2": Text2,
"text3": Text3}
)
#RAIDING
#if (author == 'StreamElements' and message.content.upper() == "is raiding"):
if (author.upper() == 'STREAMELEMENTS' and "IS RAIDING" in message.content.upper()):
print("CHAT| Raid detected")
words = message.content.split(" ")
raider = words[0]
print("CHAT|",raider,"is raiding")
Text1 = raider + " is raiding"
Text2 = "Thank you " + raider
Text3 = "Welcome to our community. Stick around and have fun!"
CommandQueue.put({"Action": "StarryNightDisplayText",
"text1": Text1,
"text2": Text2,
"text3": Text3}
)
#Subscriber for X months
if (author.upper() == 'STREAMELEMENTS' and "MONTHS IN A ROW" in message.content.upper()):
print("CHAT| SUBscriber detected")
words = message.content.split(" ")
Subscriber = words[0]
Months = words[6]
print("CHAT|",Subscriber," has been a subscriber for ",Months, " months")
print("Get user profile info:",Subscriber)
API_ENDPOINT = "https://api.twitch.tv/helix/users?login=" + Subscriber
head = {
#'Client-ID': CLIENT_ID,
'Client-ID': THECLOCKBOT_CLIENT_ID,
'Authorization': 'Bearer ' + THECLOCKBOT_ACCESS_TOKEN
}
#print ("URL: ",API_ENDPOINT, 'data:',head)
r = requests.get(url = API_ENDPOINT, headers = head)
results = r.json()
pprint.pprint(results)
#print(" ")
UserProfileURL = ''
DataDict = results.get('data','NONE')
if (DataDict != 'NONE'):
print("Data found. Processing...")
try:
UserProfileURL = results['data'][0]['profile_image_url']
except Exception as ErrorMessage:
TraceMessage = traceback.format_exc()
AdditionalInfo = "Getting CHANNEL info from API call"
LED.ErrorHandler(ErrorMessage,TraceMessage,AdditionalInfo)
if (UserProfileURL != ""):
LED.GetImageFromURL(UserProfileURL,"UserProfile.png")
CommandQueue.put({"Action": "showimagezoom",
"image": "UserProfile.png",
"zoommin" : 1,
"zoommax":256,
"zoomfinal" : 32,
"sleep" : 0.01,
"step" : 1})
#LURK
if (message.content.upper() == "!LURK"):
print("LURK MODE ACTIVATED: ",author)
#LED.ClearBigLED()
#LED.ClearBuffers()
CommandQueue.put({
"Action": "ShowTitleScreen",
"BigText": "LURK",
"BigTextRGB": LED.MedGreen,
"BigTextShadowRGB": LED.ShadowGreen,
"BigTextZoom": 3,
"LittleText": "",
"LittleTextRGB": LED.MedRed,
"LittleTextShadowRGB": LED.ShadowRed,
"LittleTextZoom": 2,
"ScrollText": author + " has gone into lurk mode",
"ScrollTextRGB": LED.MedYellow,
"ScrollSleep": ScrollSleep,
"DisplayTime": 1,
"ExitEffect": 1
})
'''
LED.ShowTitleScreen(
BigText = "LURK",
BigTextRGB = LED.MedGreen,
BigTextShadowRGB = LED.ShadowGreen,
BigTextZoom = 3,
LittleText = '',
LittleTextRGB = LED.MedRed,
LittleTextShadowRGB = LED.ShadowRed,
ScrollText = author + " has gone into lurk mode",
ScrollTextRGB = LED.MedYellow,
ScrollSleep = ScrollSleep, # time in seconds to control the scrolling (0.005 is fast, 0.1 is kinda slow)
DisplayTime = 0, # time in seconds to wait before exiting
ExitEffect = 1 # 0=Random / 1=shrink / 2=zoom out / 3=bounce / 4=fade /5=fallingsand
)
'''
print("LURK MODE DEACTIVATED")
#----------------------------------------
#-- Trigger Words
#----------------------------------------