-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
2220 lines (1875 loc) · 98.9 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function
from cProfile import label
from email import message
from errno import EPERM
from gettext import find
import json
import string
from xml.etree.ElementTree import tostring
from pandas import describe_option
import requests
from lib2to3.pytree import convert
from msilib.schema import File, TextStyle
from socket import timeout
from tkinter import Button
import requests
from requests_oauthlib import OAuth1Session
import os
import re
from datetime import datetime, timedelta
from asyncio import sleep as s, wait
# from webserver import keep_alive
import discord
from discord.ext import tasks, commands, menus
import discord.ext
from discord import Intents, InteractionMessage, InteractionResponse, Message, Reaction
from discord import app_commands
from discord import colour
from discord import Streaming
from discord.utils import get
import discord
from discord import app_commands, ui
import tweepy
import http.client
from typing import Callable, List, Optional
import sys
from dotenv import load_dotenv
load_dotenv()
#sys.stdout = open('log.txt', 'w')
class Role_Buttons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='Role 1', style=discord.ButtonStyle.gray, emoji='❓', custom_id='STRL:RoleButton1')
async def Role1(self, interaction: discord.Interaction, button: discord.ui.Button):
guild = client.get_guild(interaction.guild_id)
if guild is None:
# Check if we're still in the guild and it's cached.
print("Guild None")
return
role = guild.get_role(986714816200712223)
if role is None:
# Make sure the role still exists and is valid.
print("Role Doesn't Exist")
return
if role in interaction.user.roles:
try:
# Finally, remove the role.
await interaction.user.remove_roles(role)
except discord.HTTPException:
# If we want to do something in case of errors we'd do it here.
print("Error removing role")
pass
else:
try:
# Finally, add the role.
await interaction.user.add_roles(role)
except discord.HTTPException:
# If we want to do something in case of errors we'd do it here.
print("Error Adding Role")
pass
await interaction.response.send_message("Role updated.", ephemeral=True)
class aclient(discord.Client):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
super().__init__(intents=intents)
self.synced = False
# Need to move this far up.
async def setup_hook(self) -> None:
# Register the persistent view for listening here.
# Note that this does not send the view to any message.
# In order to do this you need to first send a message with the View, which is shown below.
# If you have the message_id you can also pass it as a keyword argument, but for this example
# we don't have one.
self.add_view(Role_Buttons())
self.persistent_views_added = True
client = aclient()
tree = app_commands.CommandTree(client)
intents = discord.Intents.all()
Intents.members = True
my_secret = os.getenv('Discord_Secret')
# Authentication with Twitch API.
client_id = os.getenv('twitch_id')
client_secret = os.getenv('twitch_secret')
body = {
'client_id': client_id,
'client_secret': client_secret,
"grant_type": 'client_credentials'
}
r = requests.post('https://id.twitch.tv/oauth2/token', body)
keys = r.json()
headers = {
'Client-ID': client_id,
'Authorization': 'Bearer ' + keys['access_token']
}
GUILD_ID = guild= discord.Object(id= 979262254958657576)
# Twitter auth
twitclient = tweepy.Client(bearer_token=os.getenv('twit_bearer_token'),
consumer_key=os.getenv('twit_consumer_key'),
consumer_secret=os.getenv('twit_consumer_secret'),
access_token=os.getenv('twit_access_token'),
access_token_secret=os.getenv('twit_access_token_secret'))
twitclient.wait_on_rate_limit=True
start_time = datetime.now()
ctx: commands.Context
@client.event
async def on_disconnect():
uptimedelta = datetime.now() - start_time
print('ShowtimeRL Bot disconnected at ' + datetime.ctime(datetime.now()) + '. ShowtimeRL Bot has been up for ' + str(timedelta(seconds=uptimedelta.seconds)))
#sys.stdout.close()
@client.event
async def on_resumed():
uptimedelta = datetime.now() - start_time
print("ShowtimeRL Bot reconnected at " + datetime.ctime(datetime.now()) + '. ShowtimeRL Bot has been up for ' + str(timedelta(seconds=uptimedelta.seconds)))
#sys.stdout = open('log.txt', 'w')
@client.event
async def on_connect():
print('ShowtimeRL Bot was connected starting at ' + datetime.ctime(datetime.now()))
def date_check(input):
pattern = re.compile(r"20[0-9]{2}-(0[0-9]|1[0-2])-(0[0-9]|1[0-9]|2[0-9]|3[0-1])", re.IGNORECASE)
return pattern.match(input)
def time_check(input):
pattern = re.compile(r"([01]?[0-9]|2[0-3]):[0-5][0-9]", re.IGNORECASE)
return pattern.match(input)
# Logs exception to .txt file.
def log_and_print_exception(e):
# Could have the bot message me any errors is encounters.
Nox = client.fetch_user(208383176781856768)
Nox.send(f'Error occurred:\n{str(e)}')
logging_file = open("log.txt", "a")
logging_file.write(f"{datetime.now()}\n{str(e)}\n\n")
logging_file.close()
print(f"Exception logged. Error:\n{e}")
# Gets a twitter account's latest tweet.
def checktwitter(twitter_name, self=None):
user = twitclient.get_user(username=twitter_name) # Takes in plain text uername (id) and turns it into user information.
tweets = twitclient.get_users_tweets(user.data.id, exclude='replies,retweets') # Takes the user information and turns it into a user id to be used for get_users_tweets. Then grabs the 10 latest tweets.
mostrecenttweet = tweets.data[0].id
return mostrecenttweet
# Returns true if online, false if not.
def checkuser(streamer_name, self=None):
try:
stream = requests.get('https://api.twitch.tv/helix/streams?user_login=' + streamer_name,
headers=headers)
if streamer_name is not None and str(stream) == '<Response [200]>':
stream_data = stream.json()
if len(stream_data['data']) == 1:
return True, stream_data
else:
return False, stream_data
else:
stream_data = None
return False, stream_data
except Exception as e:
self.log_and_print_exception(e)
stream_data = None
return False, stream_data
# Checks if the live notification has already been sent.
async def has_notif_already_sent(channel, twitch_name):
async for message in channel.history(limit=200):
if f"\nhttps://twitch.tv/{twitch_name}" in message.content:
return message
else:
return False
# Checks if a tweet has already been sent
async def has_tweet_already_sent(channel, tweet_id):
async for message in channel.history(limit=200):
if f'https://vxtwitter.com/twitter/statuses/{tweet_id}' in message.content:
return message
else:
return False
# 0=botlog, 1=tweets, 2=streams, 3=modmail, 4=announcements
def get_channel(id):
file = open('channels.txt', "r")
channels = file.read()
channel_list = channels.split(",")
try:
request = channel_list[id]
except:
print("Channel not listed listed in channel file!")
file.close()
return request
# Function to convert
def listToStringNewline(s):
# initialize an empty string
str1 = "\n"
# return string
return (str1.join(s))
def listToStringCommaSpace(s):
str1 = ", "
return (str1.join(s))
def listToStringComma(s):
str1 = ","
return (str1.join(s))
# Contains the live event loop.
@client.event
async def on_ready():
await discord.Client.wait_until_ready(client)
if not client.synced:
await tree.sync(guild= GUILD_ID)
self.synced = True
print(f"Bot has logged in.")
@tasks.loop(hours=24)
async def todays_matchs():
# Eventually place an if statement here that checks if its between certain hours.
today = datetime.today().strftime("%Y-%m-%d")
year, month, day = today.rsplit('-')
year = int(year)
month = int(month)
day = int(day)
if month == 1:
monthname = 'January'
monthlength = 31
elif month == 2:
monthname = 'February'
if year == 2024:
monthlength = 29
monthlength = 28
elif month == 3:
monthname = 'March'
monthlength = 31
elif month == 4:
monthname = 'April'
monthlength = 0
elif month == 5:
monthname = 'May'
monthlength = 31
elif month == 6:
monthname = 'June'
monthlength = 30
elif month == 7:
monthname = 'July'
monthlength = 31
elif month == 8:
monthname = 'August'
monthlength = 31
elif month == 9:
monthname = 'September'
monthlength = 30
elif month == 10:
monthname = 'October'
monthlength = 31
elif month == 11:
monthname = 'November'
monthlength = 0
elif month == 12:
monthname = 'December'
monthlength = 31
print(f'\nRemoving Matches prior to {monthname} {day} {year}.\nCurrent time is: {datetime.now()}\n')
with open('Matches.txt', 'r') as file:
data = file.readlines()
file.close()
tobedeleted = []
upcomingmatches = []
index = 0
for line in data:
if line.startswith('Date: '):
date = line.replace('Date: ', '')
MatchYear, MatchMonth, MatchDay = date.rsplit('-')
MatchYear = int(MatchYear)
MatchMonth = int(MatchMonth)
MatchDay = int(MatchDay)
remainingdays = day+7-monthlength
if remainingdays > 0:
if MatchYear < year:
tobedeleted.append(index)
elif MatchYear == year and MatchMonth < month:
tobedeleted.append(index)
elif MatchYear == year and MatchMonth == month and MatchDay < day:
tobedeleted.append(index)
elif MatchYear == year and MatchMonth == month and MatchDay == day:
upcomingmatches.append(index)
index2 = 1
while remainingdays > 0:
newmonth = month+1
if newmonth == 13:
newmonth = 1
year += 1
if MatchYear == year and MatchMonth == newmonth and MatchDay == index2:
upcomingmatches.append(index)
index2 += 1
remainingdays -=1
if remainingdays <= 0:
if MatchYear < year:
tobedeleted.append(index)
elif MatchYear == year and MatchMonth < month:
tobedeleted.append(index)
elif MatchYear == year and MatchMonth == month and MatchDay < day:
tobedeleted.append(index)
elif MatchYear == year and MatchMonth == month and MatchDay == day+1:
upcomingmatches.append(index)
elif MatchYear == year and MatchMonth == month and MatchDay == day+2:
upcomingmatches.append(index)
elif MatchYear == year and MatchMonth == month and MatchDay == day+3:
upcomingmatches.append(index)
elif MatchYear == year and MatchMonth == month and MatchDay == day+4:
upcomingmatches.append(index)
elif MatchYear == year and MatchMonth == month and MatchDay == day+5:
upcomingmatches.append(index)
elif MatchYear == year and MatchMonth == month and MatchDay == day+6:
upcomingmatches.append(index)
elif MatchYear == year and MatchMonth == month and MatchDay == day+7:
upcomingmatches.append(index)
index+=1
for i in tobedeleted:
data[i-1] = ''
data[i] = ''
data[i+1] = ''
data[i+2] = ''
data[i+3] = ''
with open('Matches.txt', 'w') as file:
file.writelines(data)
file.close()
matchname = []
matchdate = []
matchtime = []
matchproducers = []
for i in upcomingmatches:
matchname.append(data[i-1])
matchdate.append(str(data[i]).replace('Date: ', ''))
matchtime.append(str(data[i+1]).replace('Time: ', ''))
matchproducers.append(str(data[i+2]).replace('Producers: ', ''))
if len(upcomingmatches) != 0:
emb = discord.Embed(
color= discord.colour.Color.random()
)
emb.add_field(name='| **Teams**', value=listToStringNewline(matchname), inline=True)
emb.add_field(name='| **Date**', value=listToStringNewline(matchdate), inline=True)
emb.add_field(name='| **Time**', value=listToStringNewline(matchtime), inline=True)
channel = client.get_channel(int(get_channel(5)))
await channel.send('<@&986715160880242799>\nThe Matches for the next 7 days are: ', embed=emb)
index4 = 0
for i in upcomingmatches:
team1, team2 = str(data[i-1]).split(' VS. ')
with open('Teams.txt', 'r') as file:
data2 = file.readlines()
file.close()
index3 = 0
for line in data2:
if line.startswith(f'Team Name: {team1}'):
team1Cap = str(data2[index3-2]).replace('Captain: ', '')
team1Players = str(data2[index3+1]).replace('Team Players: ', '')
team1Subs = str(data2[index3+2]).replace('Team Subs: ', '')
team1Rank = data2[index3+3].replace('Average Team Rank: ', '')
if line.startswith(f'Team Name: {team2}'):
team2Cap = data2[index3-2].replace('Captain: ', '')
team2Players = data2[index3+1].replace('Team Players: ', '')
team2Subs = data2[index3+2].replace('Team Subs: ', '')
team2Rank = data2[index3+3].replace('Average Team Rank: ', '')
index3 +=1
MatchInfo = discord.Embed(
color = discord.colour.Color.random()
)
MatchInfo.add_field(name='**Team 1 Name**', value=team1, inline=True).add_field(name='**Team 2 Name**', value=team2, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Captain**', value=team1Cap, inline=True).add_field(name='**Team 2 Captain**', value=team2Cap, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Players**', value=team1Players, inline=True).add_field(name='**Team 2 Players**', value=team2Players, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Subs**', value=team1Subs, inline=True).add_field(name='**Team 2 Subs**', value=team2Subs, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Rank**', value=team1Rank, inline=True).add_field(name='**Team 2 Rank**', value=team2Rank, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Date**', value=matchdate[index4], inline=True).add_field(name='**Time**', value=matchtime[index4], inline=True).add_field(name='\u200b', value='\u200b')
if matchproducers[index4] != '\n':
MatchInfo.add_field(name="Producers", value=matchproducers[index4], inline=False)
else:
MatchInfo.add_field(name="Producers", value="None", inline=False)
# Will need to attatch a view to the message for the producers to sign up for matches.
# Will also need to create another loop for reminders about said matches. Will likely require a file to track the producers OR have them added to Matches.txt
view = ProducerSignupView(i)
await channel.send('', embed=MatchInfo, view=view)
index4 += 1
else:
channel = client.get_channel(int(get_channel(5)))
await channel.send('<@&986715160880242799>\nNo Matches in the next 7 days.')
@tasks.loop(seconds=60)
async def live_notifs_loop():
# Opens and reads the json file
with open('tweeters.txt', 'r') as file2:
tweeters = (file2.readline())
tweeterlist = tweeters.split(",")
with open('streams.txt', 'r') as file:
streams = (file.readline())
streamlist = streams.split(",")
# Makes sure the json isn't empty before continuing.
try:
if tweeters != "":
channel1 = client.get_channel(int(get_channel(1)))
for twitter_name in tweeterlist:
if twitter_name == '':
break
tweet_id = checktwitter(twitter_name)
message = await has_tweet_already_sent(channel1, tweet_id)
if message is False:
print(f"{twitter_name} tweeted. Sending a notification.")
message = 'https://vxtwitter.com/twitter/statuses/'+str(tweet_id)
await channel1.send(message)
if streams != "":
# Gets the guild, 'twitch streams' channel, and streaming role.
channel = client.get_channel(int(get_channel(2)))
# Loops through the json and gets the key,value which in this case is the user_id and twitch_name of
# every item in the json.
for twitch_name in streamlist:
if twitch_name == '':
break
# Takes the given twitch_name and checks it using the checkuser function to see if they're live.
# Returns either true or false.
status, stream_data = checkuser(twitch_name)
# Makes sure they're live
if status is True:
# Checks to see if the live message has already been sent.
message = await has_notif_already_sent(channel, twitch_name)
if message is not False:
continue
await channel.send(
f":red_circle: **LIVE**"
f"\n@here Come watch!"
f"\n{stream_data['data'][0]['title']}"
f"\nhttps://twitch.tv/{twitch_name}")
print(f"A livestream has started. Sending a notification.")
continue
# If they aren't live do this:
elif stream_data is not None:
# Checks to see if the live notification was sent.
message = await has_notif_already_sent(channel, twitch_name)
if message is not False:
print(f"A livestream has stopped. Removing the notification.")
await message.delete()
except TypeError as e:
log_and_print_exception(e)
raise e
file.close()
# Start your loop.
todays_matchs.start()
live_notifs_loop.start()
class ProducerSignupView(discord.ui.View):
def __init__(self, matchindex):
self.matchindex = matchindex
super().__init__(timeout=86400)
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='Sign Up', style=discord.ButtonStyle.green, custom_id='STRL:ProdYes')
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
with open('Matches.txt', 'r') as file:
data = file.readlines()
file.close()
if data[self.matchindex+2].find(str(interaction.user)) == -1:
data[self.matchindex+2] = str(data[self.matchindex+2]).rstrip() +str(f' {interaction.user}\n')
with open('Matches.txt', 'w') as file:
file.writelines(data)
file.close()
team1, team2 = str(data[self.matchindex-1]).split(' VS. ')
with open('Teams.txt', 'r') as file:
data2 = file.readlines()
file.close()
index3 = 0
for line in data2:
if line.startswith(f'Team Name: {team1}'):
team1Cap = str(data2[index3-2]).replace('Captain: ', '')
team1Players = str(data2[index3+1]).replace('Team Players: ', '')
team1Subs = str(data2[index3+2]).replace('Team Subs: ', '')
team1Rank = data2[index3+3].replace('Average Team Rank: ', '')
if line.startswith(f'Team Name: {team2}'):
team2Cap = data2[index3-2].replace('Captain: ', '')
team2Players = data2[index3+1].replace('Team Players: ', '')
team2Subs = data2[index3+2].replace('Team Subs: ', '')
team2Rank = data2[index3+3].replace('Average Team Rank: ', '')
index3 +=1
MatchInfo = discord.Embed(
color = discord.colour.Color.random()
)
MatchInfo.add_field(name='**Team 1 Name**', value=team1, inline=True).add_field(name='**Team 2 Name**', value=team2, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Captain**', value=team1Cap, inline=True).add_field(name='**Team 2 Captain**', value=team2Cap, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Players**', value=team1Players, inline=True).add_field(name='**Team 2 Players**', value=team2Players, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Subs**', value=team1Subs, inline=True).add_field(name='**Team 2 Subs**', value=team2Subs, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Rank**', value=team1Rank, inline=True).add_field(name='**Team 2 Rank**', value=team2Rank, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Date**', value=data[self.matchindex].replace('Date: ', ''), inline=True).add_field(name='**Time**', value=data[self.matchindex+1].replace('Time: ', ''), inline=True).add_field(name='\u200b', value='\u200b')
if data[self.matchindex+2].replace('Producers: ', '') != '\n':
MatchInfo.add_field(name="Producers", value=data[self.matchindex+2], inline=False)
else:
MatchInfo.add_field(name="Producers", value="None", inline=False)
await interaction.response.edit_message(content='', embed=MatchInfo)
await interaction.followup.send(f"{interaction.user.mention} you've signed up for the match.", ephemeral=True)
else:
await interaction.response.send_message(f'{interaction.user.mention} you are already signed up for this match.', ephemeral=True)
self.value = "✔️"
#self.stop()
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Quit', style=discord.ButtonStyle.red, custom_id='STRL:ProdNo')
async def deny(self, interaction: discord.Interaction, button: discord.ui.Button):
with open('Matches.txt', 'r') as file:
data = file.readlines()
file.close()
if data[self.matchindex+2].find(str(interaction.user)) != -1:
data[self.matchindex+2]= data[self.matchindex+2].replace(f' {str(interaction.user)}', ' ')
with open('Matches.txt', 'w') as file:
file.writelines(data)
file.close()
team1, team2 = str(data[self.matchindex-1]).split(' VS. ')
with open('Teams.txt', 'r') as file:
data2 = file.readlines()
file.close()
index3 = 0
for line in data2:
if line.startswith(f'Team Name: {team1}'):
team1Cap = str(data2[index3-2]).replace('Captain: ', '')
team1Players = str(data2[index3+1]).replace('Team Players: ', '')
team1Subs = str(data2[index3+2]).replace('Team Subs: ', '')
team1Rank = data2[index3+3].replace('Average Team Rank: ', '')
if line.startswith(f'Team Name: {team2}'):
team2Cap = data2[index3-2].replace('Captain: ', '')
team2Players = data2[index3+1].replace('Team Players: ', '')
team2Subs = data2[index3+2].replace('Team Subs: ', '')
team2Rank = data2[index3+3].replace('Average Team Rank: ', '')
index3 +=1
MatchInfo = discord.Embed(
color = discord.colour.Color.random()
)
MatchInfo.add_field(name='**Team 1 Name**', value=team1, inline=True).add_field(name='**Team 2 Name**', value=team2, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Captain**', value=team1Cap, inline=True).add_field(name='**Team 2 Captain**', value=team2Cap, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Players**', value=team1Players, inline=True).add_field(name='**Team 2 Players**', value=team2Players, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Subs**', value=team1Subs, inline=True).add_field(name='**Team 2 Subs**', value=team2Subs, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Team 1 Rank**', value=team1Rank, inline=True).add_field(name='**Team 2 Rank**', value=team2Rank, inline=True).add_field(name='\u200b', value='\u200b')
MatchInfo.add_field(name='**Date**', value=data[self.matchindex].replace('Date: ', ''), inline=True).add_field(name='**Time**', value=data[self.matchindex+1].replace('Time: ', ''), inline=True).add_field(name='\u200b', value='\u200b')
if data[self.matchindex+2].replace('Producers: ', '') != '\n':
MatchInfo.add_field(name="Producers", value=data[self.matchindex+2], inline=False)
else:
MatchInfo.add_field(name="Producers", value="None", inline=False)
await interaction.response.edit_message(content='', embed=MatchInfo)
await interaction.followup.send(f"{interaction.user.mention} you've quit the match.", ephemeral=True)
else:
await interaction.response.send_message(f'{interaction.user.mention} you are not signed up for this match.', ephemeral=True)
self.value = "❌"
#self.stop()
async def on_timeout(self, interaction: discord.Interaction):
await interaction.response.defer()
self.value = "Timeout"
self.stop()
class ModMailModal(ui.Modal, title='Mod Mail'):
Title = discord.ui.TextInput(label='Title', required=True, style=discord.TextStyle.short)
Mail = discord.ui.TextInput(label= "Message", default= "Write what you want sent here.", required=True, style=discord.TextStyle.paragraph)
Notes = discord.ui.TextInput(label= "Additional Notes", default="\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b", style=discord.TextStyle.short, required=False)
# Notes fix is definitely a band-aid. Can't find a way to let Notes just be empty without these dumb empty space characters
async def on_submit(self, interaction):
channel = client.get_channel(int(get_channel(3)))
author = interaction.user
embed = discord.Embed(
color=discord.Color.random(),
title=f"Mod Mail from {author}",)
try:
embed.set_thumbnail(url=f"{author.avatar.url}")
except:
embed.set_thumbnail(url='https://styles.redditmedia.com/t5_2qhk5/styles/communityIcon_v58lvj23zo551.jpg')
print(f'{author} did not have an avatar url.')
embed.add_field(name="**Title**", value=f"{self.Title}", inline=False)
embed.add_field(name=f"**Mail Content**", value=f"{self.Mail}", inline=False)
embed.add_field(name=f"**Additional Notes**", value=f"{self.Notes}", inline=False)
embed.timestamp = datetime.now()
await interaction.response.send_message("Your Mod Mail has been recorded and sent as follows.",embed=embed)
await channel.send(embed=embed)
# This is caled when the bot is DM'd. It displays buttons for the user.
class DM_Help(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='❓', style=discord.ButtonStyle.gray)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
color=discord.Color.random(),
title=f"Command List")
embed.add_field(name="General Commands", value='**hello** - The bot will respond back with a simple "Hello @you!"\n**help** - Sends this message.\n**ping** - Checks the latency of the bot. Responds with "Pong! **ms"', inline=False)
embed.add_field(name="Showmatch Commands", value="**create/edit/delete_team** - These three commands are used to manage your team within the Showmatch system.\n**match_request** - This commands lets you set up a match against another team within the Showmatch system.\n**cancel_match** - This command lets you cancel a match that you have already created.", inline=False)
embed.add_field(name='Information Commands', value="**team/match_info** - These commands allows you to look up a corresponding match or team and see their corresponding information.\n**list_teams/matches** - These commands let you see all teams and matches currently listed within the showmatch system.", inline=False)
embed.timestamp = datetime.now()
await interaction.response.send_message(embed=embed)
self.value = "❓"
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='💬', style=discord.ButtonStyle.blurple)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
x = ModMailModal()
await interaction.response.send_modal(x)
await TeamModal.wait(x)
self.value = "💬"
# This bit of code has the bot respond to DMs automatically, should be turned into a helpful message eventually.
@client.event
async def on_message(message):
channel = client.get_channel(int(get_channel(3)))
if message.author == client.user:
return
if not message.guild:
try:
view= DM_Help()
await message.channel.send("Hi, how can I help you?\n❓ : Command list\n💬 : Mod Mail\n", view=view)
await view.wait()
# If you want to add something to this then check the DM_Help class.
except discord.errors.Forbidden:
pass
else:
pass
# This command lets you add a twitter account to the notification list.
@tree.command(name="twitter_add", description=f'Adds a Twitter to the live notifs.', guild= GUILD_ID)
@app_commands.describe(twitter_name='Name of the twitter you want to add to the system.')
async def self(interaction: discord.Interaction, twitter_name: str):
id = int(get_channel(0))
channel = client.get_channel(id)
# Opens and reads the json file.
with open('tweeters.txt', 'a') as file:
# Assigns their given twitch_name to their discord id and adds it to the streamers.json.
file.writelines(f'{twitter_name},')
# Tells the user it worked.
await interaction.response.send_message(f"Added {twitter_name} to the notifications list.")
await channel.send (f"{twitter_name} was added to the notification list by {interaction.user.mention}.")
print(f"Added {twitter_name} to the notifications list.")
file.close()
# This command lets you remove a twitter account from the notification list.
@tree.command(name="twitter_delete", description=f'Removes a Twitter from the live notifs.', guild= GUILD_ID)
@app_commands.describe(twitter_name='Name of the twitter you want to remove from the system.')
async def self(interaction: discord.Interaction, twitter_name: str):
channel = client.get_channel(int(get_channel(1)))
channel2 = client.get_channel(int(get_channel(0)))
# Opens and reads the json file.
try:
with open('tweeters.txt', 'r') as file:
tweeters = (file.read())
tweeterlist = tweeters.split(",")
tweeterlist.remove(f'{twitter_name}')
newtweeters = ",".join(tweeterlist)
#print(newtweeters)
message = await has_notif_already_sent(channel, twitter_name)
if message is not False:
print(f"A tweeter was removed. Removing the notification. Is this needed?")
await message.delete()
file.close()
# Adds the changes we made to the json file.
with open('tweeters.txt', 'w') as file:
file.writelines(newtweeters)
file.close()
# Tells the user it worked.
await interaction.response.send_message(f"Removed {twitter_name} from the notifications list.")
await channel2.send(f"{twitter_name} was removed from the notification list by {interaction.user.mention}.")
print(f"Removed {twitter_name} from the notifications list.")
except:
await interaction.response.send_message(f"Error Occurred.")
file.close()
# This command lists twitter accounts currently within the notification list.
@tree.command(name="twitter_list", description=f'List of twitters currently being tracked.', guild= GUILD_ID)
async def self(interaction: discord.Interaction):
with open('tweeters.txt', 'r') as file:
tweeters = file.read()
await interaction.response.send_message(f'The currently tracked twitters include: {tweeters}')
file.close()
# This command lets you add a streamer to the notification list.
@tree.command(name="stream_add", description=f'Adds a Twitch to the live notifs.', guild= GUILD_ID)
@app_commands.describe(twitch_name='Name of the streamer you want to add to the system.')
async def self(interaction: discord.Interaction, twitch_name: str):
id = int(get_channel(0))
channel = client.get_channel(id)
# Opens and reads the json file.
with open('streams.txt', 'a') as file:
# Assigns their given twitch_name to their discord id and adds it to the streamers.json.
file.writelines(f'{twitch_name},')
# Tells the user it worked.
await interaction.response.send_message(f"Added {twitch_name} to the notifications list.")
await channel.send (f"{twitch_name} was added to the notification list by {interaction.user.mention}.")
print(f"Added {twitch_name} to the notifications list.")
file.close()
# This command lets you remove a streamer from the notification list.
@tree.command(name="stream_delete", description=f'Removes a Twitch from the live notifs.', guild= GUILD_ID)
@app_commands.describe(twitch_name='Name of the streamer you want to remove from the system.')
async def self(interaction: discord.Interaction, twitch_name: str):
channel = client.get_channel(int(get_channel(2)))
channel2 = client.get_channel(int(get_channel(0)))
# Opens and reads the json file.
try:
with open('streams.txt', 'r') as file:
streams = (file.read())
streamlist = streams.split(",")
streamlist.remove(f'{twitch_name}')
newstreams = ",".join(streamlist)
#print(newstreams)
message = await has_notif_already_sent(channel, twitch_name)
if message is not False:
print(f"A livestream has stopped. Removing the notification.")
await message.delete()
file.close()
# Adds the changes we made to the json file.
with open('streams.txt', 'w') as file:
file.writelines(newstreams)
file.close()
# Tells the user it worked.
await interaction.response.send_message(f"Removed {twitch_name} from the notifications list.")
await channel2.send(f"{twitch_name} was removed from the notification list by {interaction.user.mention}.")
print(f"Removed {twitch_name} from the notifications list.")
except:
await interaction.response.send_message(f"Error Occurred.")
file.close()
# This command lists streamers currently within the notification list.
@tree.command(name="stream_list", description=f'List of streams currently being tracked.', guild= GUILD_ID)
async def self(interaction: discord.Interaction):
with open('streams.txt', 'r') as file:
streams = file.read()
await interaction.response.send_message(f'The currently tracked streams include: {streams}')
file.close()
# Used in conjunction with the /setchannel command. This actually changes the channel.
async def change_channel(self, chosen_channel, chosen_function):
if chosen_function == "Bot Log":
chosen_function = 0
elif chosen_function == "Tweet Channel":
chosen_function = 1
elif chosen_function == "Stream Channel":
chosen_function = 2
elif chosen_function == "Mod Mail":
chosen_function = 3
elif chosen_function == "Announcement Channel":
chosen_function = 4
elif chosen_function == "Producer Channel":
chosen_function = 5
with open('channels.txt', 'r') as file:
channels = file.read()
channel_list = channels.split(',')
channel_list[int(chosen_function)] = str(chosen_channel)
newchannels = ",".join(channel_list)
file.close()
with open('channels.txt', "w") as file:
file.writelines(newchannels)
file.close()
# Used in /setchannel, has the info for the channel select dropdown.
class ChannelDropdown(discord.ui.Select):
def __init__(self, function):
self.function = function
text_channel_name_list = []
text_channel_id_list = []
for guild in client.guilds:
for channel in guild.channels:
if str(channel.type) == 'text':
text_channel_name_list.append(channel.name)
text_channel_id_list.append(channel.id)
if len(text_channel_name_list) > 11:
text_channel_name_list[11] = "[Next Page]"
del text_channel_name_list[12:]
options = [
discord.SelectOption(label=key)
for key in text_channel_name_list
]
super().__init__(placeholder='Choose a channel..', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
text_channel_name_list = []
text_channel_id_list = []
for guild in client.guilds:
for channel in guild.channels:
if str(channel.type) == 'text':
text_channel_id_list.append(channel.id)
text_channel_name_list.append(channel.name)
# Use the interaction object to send a response message containing
# the user's favourite colour or choice. The self object refers to the
# Select object, and the values attribute gets a list of the user's
# selected options. We only want the first one.
if self.values[0] != '[Next Page]':
id = text_channel_id_list[text_channel_name_list.index(self.values[0])]
await change_channel(self, id, self.function)
await interaction.response.send_message(f"You chose <#{id}>\nThe Bot is now updated.", ephemeral=True)
botid = int(get_channel(0))
botchannel = client.get_channel(botid)
await botchannel.send(f"{interaction.user.mention} changed the {self.function} to <#{id}>")
else:
view = ChannelDropDownExtendedView(PageNumber=2, function=self.function)
await interaction.response.edit_message(content=f"You chose the **{self.function}** function.\nNow choose which channel you'd like to attach it to.", view=view)
class ChannelDropdownExtended(discord.ui.Select):
def __init__(self, PageNumber, function):
self.PageNumber = PageNumber
self.function = function
text_channel_name_list = []
text_channel_id_list = []
for guild in client.guilds:
for channel in guild.channels:
if str(channel.type) == 'text':
text_channel_name_list.append(channel.name)
text_channel_id_list.append(channel.id)
Listings = 10*self.PageNumber
try:
text_channel_name_list[Listings+1] = "[Next Page]"
del text_channel_name_list[Listings+2:]
del text_channel_name_list[0:Listings-9]
except:
end = len(text_channel_name_list)
del text_channel_name_list[0:end-10]
options = [
discord.SelectOption(label=key)
for key in text_channel_name_list
]
super().__init__(placeholder='Choose a channel..', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
text_channel_name_list = []
text_channel_id_list = []
for guild in client.guilds:
for channel in guild.channels:
if str(channel.type) == 'text':
text_channel_id_list.append(channel.id)
text_channel_name_list.append(channel.name)
# Use the interaction object to send a response message containing
# the user's favourite colour or choice. The self object refers to the
# Select object, and the values attribute gets a list of the user's
# selected options. We only want the first one.
if self.values[0] != '[Next Page]':
id = text_channel_id_list[text_channel_name_list.index(self.values[0])]
await change_channel(self, id)
await interaction.response.send_message(f"You chose <#{id}>\nThe Bot is now updated.", ephemeral=True)
botid = int(get_channel(0))
botchannel = client.get_channel(botid)
await botchannel.send(f"{interaction.user.mention} changed the {self.function} to <#{id}>")
else:
view = ChannelDropDownExtendedView(self.PageNumber+1, function= self.function)
await interaction.response.edit_message(content = f"You chose the **{self.function}** function.\nNow choose which channel you'd like to attach it to.", view=view)
# Used in /setchannel, has the info for the function select dropdown.
class FunctionDropdown(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label='Bot Log', emoji='⬛'),
discord.SelectOption(label='Tweet Channel', emoji='🟦'),
discord.SelectOption(label='Stream Channel', emoji='🟪'),
discord.SelectOption(label='Mod Mail', emoji='🟥'),
discord.SelectOption(label="Announcement Channel", emoji='⬜'),
discord.SelectOption(label="Producer Channel", emoji='🟧')
]
# The placeholder is what will be shown when no option is chosen
# The min and max values indicate we can only pick one of the three options
# The options parameter defines the dropdown options. We defined this above
super().__init__(placeholder='Choose a function..', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
# Use the interaction object to send a response message containing
# the user's favourite colour or choice. The self object refers to the
# Select object, and the values attribute gets a list of the user's
# selected options. We only want the first one.
view = ChannelDropdownView(function = self.values[0])
await interaction.response.send_message(f"You chose the **{self.values[0]}** function.\nNow choose which channel you'd like to attach it to.", view=view, ephemeral=True)
# Creates the view for the Function Dropdown.
class FunctionDropdownView(discord.ui.View):
def __init__(self):
super().__init__()