15
15
from discord .errors import NotFound
16
16
from googletrans import Translator
17
17
18
- translator = Translator ()
18
+ SHARD_ID = 0
19
+ TOTAL_SHARDS = 1
19
20
20
- try :
21
- guild_ids = CACHE .guild_ids
22
- except :
23
- guild_ids = []
21
+ translator = Translator ()
24
22
25
23
DISCORD_TOKEN = CACHE .DISCORD_TOKEN
26
24
TWITCH_ID = CACHE .TWITCH_ID
27
25
TWITCH_SECRET = CACHE .TWITCH_SECRET
28
- CACHE_HEADER = "DISCORD_TOKEN = \' " + DISCORD_TOKEN + "\' \n TWITCH_ID = \' " + TWITCH_ID + \
29
- "\' \n TWITCH_SECRET = \' " + TWITCH_SECRET + "\' \n prefix = \' " + CACHE .prefix \
30
- + "\' \n name = \' " + CACHE .name + "\' \n desc = \' " + CACHE .desc + "\' \n guild_ids = " \
31
- + str (guild_ids ) + "\n data = "
32
26
33
27
intent = discord .Intents .default ()
34
28
intent .members = True
35
- CLIENT = commands .Bot (command_prefix = CACHE .prefix , intents = intent )
29
+ CLIENT = commands .AutoShardedBot (command_prefix = CACHE .prefix , intents = intent , shard_ids = [ SHARD_ID ], shard_count = TOTAL_SHARDS )
36
30
37
31
38
32
@CLIENT .event
@@ -195,9 +189,9 @@ def __init__(self, data, i):
195
189
def __init__ (self ):
196
190
self .data = CACHE .data
197
191
self .server_objects = []
198
- self .reload_objects (self .data , 0 )
192
+ self .reload_objects (self .data )
199
193
200
- def reload_objects (self , newdata , write = 1 ):
194
+ def reload_objects (self , newdata ):
201
195
"""Sets self.data to newdata, reloads server objects with newdata, and writes updated data to file"""
202
196
newdata = ast .literal_eval (str (newdata ))
203
197
self .data = newdata
@@ -206,16 +200,6 @@ def reload_objects(self, newdata, write=1):
206
200
# recreate server object list to match changed cache file -
207
201
# iterate through cache file, each server in it is sent to self.Server constructor that
208
202
# creates a new object with that server's attributes. The object is added to self.server_objects
209
- if write == 1 :
210
- w = False
211
- while not w :
212
- try :
213
- with open ("cache.py" , "wb" ) as cfile :
214
- cfile .write ((CACHE_HEADER + str (newdata )).encode ('utf8' ))
215
- w = True
216
- except :
217
- print ("error writing" )
218
- print (traceback .format_exc ())
219
203
220
204
@staticmethod
221
205
def get_obdated_obj_followed (serverid ):
@@ -337,7 +321,8 @@ def get_broadcaster_clips(self, broadcaster_id, limit=1, started_at=""):
337
321
start = "&started_at="
338
322
h = {'Client-ID' : self .CLIENT_ID , 'client_secret' : self .CLIENT_SECRET , 'Authorization' : "Bearer " + self .oauth }
339
323
a = requests .get (
340
- url = 'https://api.twitch.tv/helix/clips?broadcaster_id=' + str (broadcaster_id ) + '&first=' + str (limit ) + start + str (started_at ), headers = h )
324
+ url = 'https://api.twitch.tv/helix/clips?broadcaster_id=' + str (broadcaster_id ) + '&first=' + str (
325
+ limit ) + start + str (started_at ), headers = h )
341
326
return a .json ()
342
327
343
328
def get_game_name (self , game_id ):
@@ -386,7 +371,9 @@ def get_most_recent_vid(self, user_query):
386
371
try :
387
372
for u in a .json ()['data' ]:
388
373
if str (u ['display_name' ]).lower () == str (user_query ).lower ():
389
- res = requests .get ('https://api.twitch.tv/helix/videos?user_id=' + u ['id' ] + "&sort=time" , headers = h ).json ()
374
+ res = requests .get ('https://api.twitch.tv/helix/videos?user_id=' + u ['id' ] + "&sort=time" ,
375
+ headers = h ).json ()
376
+ # print(res)
390
377
return res ['data' ][0 ]['url' ]
391
378
except IndexError :
392
379
raise Exception ("novids" )
@@ -478,34 +465,30 @@ async def set_watching_activity(self, activity):
478
465
self .activity = activity
479
466
480
467
def has_role (self , serverid , userid , roleid ):
481
- guild = self .client .get_guild (int (serverid ))
482
- user = guild .get_member (userid )
483
- print (user )
468
+ user = self .get_member (serverid , userid )
484
469
for r in user .roles :
485
- print (r )
486
470
if r .id == roleid :
487
471
return True
488
472
return False
489
473
474
+ @staticmethod
475
+ def get_member (serverid , userid ):
476
+ for m in CLIENT .get_guild (int (serverid )).members :
477
+ if int (m .id ) == int (userid ):
478
+ return m
479
+ return None
480
+
490
481
async def give_role (self , serverid , userid , roleid ):
491
482
guild = self .client .get_guild (int (serverid ))
492
- user = guild .get_member (userid )
483
+ user = self .get_member (serverid , userid )
493
484
role = guild .get_role (roleid )
494
- try :
495
- if user is None :
496
- print (type (userid ))
497
- await user .add_roles (role )
498
- except discord .errors .Forbidden :
499
- pass
485
+ await user .add_roles (role )
500
486
501
487
async def remove_role (self , serverid , userid , roleid ):
502
488
guild = self .client .get_guild (int (serverid ))
503
- user = guild .get_member (userid )
489
+ user = self .get_member (serverid , userid )
504
490
role = guild .get_role (roleid )
505
- try :
506
- await user .remove_roles (role )
507
- except discord .errors .Forbidden :
508
- pass
491
+ await user .remove_roles (role )
509
492
510
493
@staticmethod
511
494
def get_msg_secs_active (msg ):
@@ -535,6 +518,9 @@ async def on_ready():
535
518
print ("logged in as" )
536
519
print ("username: " + str (CLIENT .user .name ))
537
520
print ("client id: " + str (DISCORD_TOKEN ))
521
+ print ("total shards: " + str (CLIENT .shard_count ))
522
+ print ("Running as shard: " + str (SHARD_ID ))
523
+ print ("shard guilds: " + str (len (CLIENT .guilds )))
538
524
print ("----------" )
539
525
else :
540
526
print ("ALREADY STARTED" )
@@ -577,8 +563,16 @@ async def server_background(s):
577
563
live_user = ulist [i ]
578
564
old_stat = s .followed [i ][1 ]
579
565
if stats [i ] == "True" and old_stat == "False" : # if new status = True and old status = False
566
+ send_bool = True
580
567
t_user = twitch .find_user (live_user )
581
568
dta = twitch .get_streams (live_user )
569
+ original_starttime = datetime .datetime .fromisoformat (t_user .started_at [:- 1 ]).timestamp ()
570
+ curr_time = datetime .datetime .utcnow ().timestamp ()
571
+ print (curr_time - original_starttime )
572
+ if curr_time - original_starttime > 1800 :
573
+ # theres a bug where sometimes live msgs will be repeated
574
+ # if 30 mins have passed since the user was recorded going live by twitch, assume we've already sent a msg
575
+ send_bool = False
582
576
try :
583
577
viewers = str (dta ['viewer_count' ])
584
578
except :
@@ -606,12 +600,16 @@ async def server_background(s):
606
600
post_ch = int (take_off_brackets (str (s .settings ['post_channels' ][ind ][1 ])))
607
601
else :
608
602
post_ch = int (take_off_brackets (str (s .settings ['post_channels' ][0 ][1 ])))
609
- sent_msg = await client_send (CLIENT .get_channel (post_ch ), message , 0 )
603
+ if send_bool :
604
+ try :
605
+ sent_msg = await client_send (CLIENT .get_channel (post_ch ), message , 0 )
606
+ except :
607
+ print ("send msg:" , traceback .format_exc ())
608
+ print (datetime .datetime .now (), s .name , s .id , ":\n " , message , "\n sent_msg:" , sent_msg )
610
609
try :
611
610
prev_times [i ] = round (time .time ())
612
611
except :
613
612
print (traceback .format_exc ())
614
- print (datetime .datetime .now (), s .name , s .id , ":\n " , message , "\n " )
615
613
except Exception as e :
616
614
if str (s .settings ['post_channels' ][0 ][1 ]) == "" :
617
615
print ("\n " , s .name , s .id , "- couldn't send live message (no channel set)" )
@@ -697,17 +695,22 @@ async def server_background(s):
697
695
d_usrs , t_usrs , rls = s .settings ['d' ], s .settings ['t' ], s .settings ['r' ]
698
696
livedata = twitch .check_live (t_usrs )
699
697
for i in range (len (livedata )):
700
- findex = ulist .index (t_usrs [i ])
701
- if livedata [i ] == "True" :
702
- if s .followed [findex ][6 ] == 0 :
703
- await dis .give_role (s .id , d_usrs [i ], rls [0 ])
704
- s .followed [findex ][6 ] = 1
705
- else :
706
- if s .followed [findex ][6 ] == 1 :
707
- await dis .remove_role (s .id , d_usrs [i ], rls [0 ])
708
- s .followed [findex ][6 ] = 0
709
- except ValueError :
710
- pass
698
+ if t_usrs [i ] in ulist :
699
+ findex = ulist .index (t_usrs [i ])
700
+ if livedata [i ] == "True" :
701
+ if s .followed [findex ][6 ] == 0 :
702
+ try :
703
+ await dis .give_role (s .id , d_usrs [i ], rls [0 ])
704
+ except :
705
+ pass
706
+ s .followed [findex ][6 ] = 1 # this keeps track of if the role was added already
707
+ else :
708
+ if s .followed [findex ][6 ] == 1 :
709
+ try :
710
+ await dis .remove_role (s .id , d_usrs [i ], rls [0 ])
711
+ except :
712
+ pass
713
+ s .followed [findex ][6 ] = 0
711
714
except :
712
715
print (s .id , s .name , "d_t connections:" , traceback .format_exc ())
713
716
@@ -720,13 +723,19 @@ async def server_background(s):
720
723
if stitle != "" :
721
724
if user .title != stitle and s .followed [i ][1 ] == "True" and str (user .title ) != "None" : # title change alerts
722
725
post_ch = int (take_off_brackets (str (s .settings ['post_channels' ][0 ][1 ])))
723
- if "2" in str (s .muted ):
724
- print ("old title:" + stitle , "\n new title:" , user .title )
725
- tm = await client_send (CLIENT .get_channel (post_ch ), str (s .followed [i ][0 ]) + " " + translate ("has changed their title to" , s .lang ) + " **" + str (user .title ) + "**" , 0 )
726
- delete_queue .append ([tm , time .time ()])
726
+ try :
727
+ if "2" in str (s .muted ):
728
+ print ("old title:" + stitle , "\n new title:" , user .title )
729
+ tm = await client_send (CLIENT .get_channel (post_ch ), str (s .followed [i ][0 ]) + " " + translate ("has changed their title to" , s .lang ) + " **" + str (user .title ) + "**" , 0 )
730
+ delete_queue .append ([tm , time .time ()])
731
+ except :
732
+ pass
727
733
if "3" in str (s .muted ):
728
734
# make it so it edits title in original alert
729
- ms = await CLIENT .get_channel (int (take_off_brackets (str (s .settings ['post_channels' ][0 ][1 ])))).fetch_message (s .followed [i ][2 ])
735
+ try :
736
+ ms = await CLIENT .get_channel (int (take_off_brackets (str (s .settings ['post_channels' ][0 ][1 ])))).fetch_message (s .followed [i ][2 ])
737
+ except :
738
+ pass
730
739
live_user = s .followed [i ][0 ]
731
740
title = user .title
732
741
game = twitch .get_game_name (user .game_id )
@@ -739,7 +748,10 @@ async def server_background(s):
739
748
message = str (parse_live_msg (str (live_user ), str (s .live_message ), title , game , viewers , s .settings , mention_users = True , server = s ))
740
749
else :
741
750
message = str (parse_live_msg (str (live_user ), str (s .live_message ), title , game , viewers , s .settings , mention_users = False , server = s ))
742
- await ms .edit (content = message )
751
+ try :
752
+ await ms .edit (content = message )
753
+ except :
754
+ pass
743
755
except :
744
756
print (s .id , s .name , "titles:" , traceback .format_exc ())
745
757
@@ -753,24 +765,30 @@ async def server_background(s):
753
765
if "9" in str (s .muted ):
754
766
old_game = twitch .get_game_name (sgame )
755
767
print ("old game:" + old_game , "\n new game:" + curr_game_name )
756
- tg = await client_send (CLIENT .get_channel (post_ch ), str (s .followed [i ][0 ]) + " " + translate ("is now playing" , s .lang ) + " **" + curr_game_name + "**" , 0 )
757
- delete_queue .append ([tg , time .time ()])
758
- if "3" in str (s .muted ):
759
- # make it so it edits title in original alert
760
- ms = await CLIENT .get_channel (int (take_off_brackets (str (s .settings ['post_channels' ][0 ][1 ])))).fetch_message (s .followed [i ][2 ])
761
- live_user = s .followed [i ][0 ]
762
- title = user .title
763
- game = twitch .get_game_name (user .game_id )
764
- dta = twitch .get_streams (live_user )
765
768
try :
766
- viewers = str (dta ['viewer_count' ])
769
+ tg = await client_send (CLIENT .get_channel (post_ch ), str (s .followed [i ][0 ]) + " " + translate ("is now playing" , s .lang ) + " **" + curr_game_name + "**" , 0 )
770
+ delete_queue .append ([tg , time .time ()])
767
771
except :
768
- viewers = "0"
769
- if "7" in str (s .muted ):
770
- message = str (parse_live_msg (str (live_user ), str (s .live_message ), title , game , viewers , s .settings , mention_users = True , server = s ))
771
- else :
772
- message = str (parse_live_msg (str (live_user ), str (s .live_message ), title , game , viewers , s .settings , mention_users = False , server = s ))
773
- await ms .edit (content = message )
772
+ pass
773
+ try :
774
+ if "3" in str (s .muted ):
775
+ # make it so it edits title in original alert
776
+ ms = await CLIENT .get_channel (int (take_off_brackets (str (s .settings ['post_channels' ][0 ][1 ])))).fetch_message (s .followed [i ][2 ])
777
+ live_user = s .followed [i ][0 ]
778
+ title = user .title
779
+ game = twitch .get_game_name (user .game_id )
780
+ dta = twitch .get_streams (live_user )
781
+ try :
782
+ viewers = str (dta ['viewer_count' ])
783
+ except :
784
+ viewers = "0"
785
+ if "7" in str (s .muted ):
786
+ message = str (parse_live_msg (str (live_user ), str (s .live_message ), title , game , viewers , s .settings , mention_users = True , server = s ))
787
+ else :
788
+ message = str (parse_live_msg (str (live_user ), str (s .live_message ), title , game , viewers , s .settings , mention_users = False , server = s ))
789
+ await ms .edit (content = message )
790
+ except :
791
+ pass
774
792
except :
775
793
print (s .id , s .name , "games:" , traceback .format_exc ())
776
794
@@ -811,24 +829,32 @@ async def server_background(s):
811
829
async def main ():
812
830
cache .reload_objects_nolive ()
813
831
try :
814
- # make sure the twitch oauth key is still valid
815
- user = twitch .find_user ('esl_csgo' )
832
+ user = twitch .find_user ('hesmen' )
816
833
if user is None :
817
- # if not, reset it
834
+ print ( "resetting twitch oauth" )
818
835
twitch .set_oauth ()
819
836
procs = []
820
837
for s in cache .server_objects :
821
- procs .append (asyncio .create_task (server_background (s )))
838
+ gg = CLIENT .get_guild (int (s .id ))
839
+ if gg is not None :
840
+ s = cache .binary_search_object_by_id (gg .id )
841
+ procs .append (asyncio .create_task (server_background (s )))
842
+
822
843
for p in procs :
823
844
try :
824
845
await p
825
846
except :
826
847
print (traceback .format_exc ())
848
+
827
849
global delete_queue
828
850
for m in delete_queue :
829
851
if time .time () - m [1 ] > 300 :
830
852
delete_queue .remove (m )
831
- await m [0 ].delete ()
853
+ try :
854
+ print ("deleting" , m [0 ].content )
855
+ await m [0 ].delete ()
856
+ except :
857
+ pass
832
858
except :
833
859
print (traceback .format_exc ())
834
860
0 commit comments