-
Notifications
You must be signed in to change notification settings - Fork 0
/
botScript.py
362 lines (272 loc) · 14.1 KB
/
botScript.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
import discord
from discord.ext import commands
from apscheduler.schedulers.asyncio import AsyncIOScheduler
import perms
import pytz
import logic
import file_functions
import leaderboard
import datetime
from datetime import datetime
import traceback
import API
scheduler = AsyncIOScheduler()
intents = discord.Intents.default()
intents.members = True
intents.reactions = True
intents.message_content = True
intents.guilds = True
bot = commands.Bot(command_prefix="!", intents=intents)
channel_id = perms.CHANNEL_ID
timezone = pytz.timezone('Europe/Oslo')
@bot.event
async def on_ready():
print(f"Bot has started and is in {len(bot.guilds)} guild(s)")
scheduler.start()
await bot.tree.sync() # Synchronizing slash commands with Discord
print(f'Logged in as {bot.user}')
# Debugging: List all commands in the command tree
print("Registered Commands:")
for command in bot.tree.get_commands():
print(f"- {command.name} (Type: {'Slash Command' if isinstance(command, discord.app_commands.Command) else 'Text Command'})")
await logic.map_emojis_to_teams(bot, logic.teams)
print("Emojis fetched")
# Fetch and print all roles in each guild
for guild in bot.guilds:
print(f"Roles in guild: {guild.name} ({guild.id})")
for role in guild.roles:
print(f"- {role.name} (Position: {role.position})")
if role.name == "Bodø/Glimt":
logic.MAX_ROLE_VALUE = role.position
# Check for any scheduled jobs
scheduled_jobs = file_functions.read_file(logic.scheduled_jobs)
if scheduled_jobs:
channel = await bot.fetch_channel(channel_id)
for job in scheduled_jobs:
scheduler.add_job(
leaderboard.StorePredictions,
'cron',
day_of_week=job['date'],
hour=job['hour'],
minute=job['minute'],
timezone=timezone,
args=[job['message_id'], channel, bot],
id=str(job['message_id'])
)
print(f"Job ID: {job['message_id']}, Scheduled Time: {job['date']} at {job['hour']}:{job['minute']}, Function: {leaderboard.StorePredictions.__name__}")
@bot.tree.command(name='sendmsg', description='Sender melding til en kanal av ditt valg')
@commands.has_permissions(manage_messages=True) # Ensure only authorized users use this command
async def SendMessageToChannel(interaction: discord.Interaction, channel: discord.TextChannel, *, message: str):
if logic.check_if_valid_server(interaction.guild_id):
try:
await channel.send(message)
await interaction.response.send_message(f"Melding sent til {channel.name}.", ephemeral=True)
except discord.Forbidden:
await interaction.response.send_message("Jeg har ikke tilgang til å sende melding i denne kanalen.", ephemeral=True)
except Exception as e:
await interaction.response.send_message(f"An error occurred: {e}", ephemeral=True)
else:
await interaction.response.send_message("Denne kommandoen kan kun brukes i en spesifikk server.", ephemeral=True)
@bot.tree.command(name='ukens_kupong', description='Send ukens kupong for de neste dagene')
@commands.has_permissions(manage_messages=True)
async def SendUkensKupong(interaction: discord.Interaction, days: int, channel: discord.TextChannel):
if logic.check_if_valid_server(interaction.guild_id):
await interaction.response.defer(ephemeral=True)
emoji_data = file_functions.read_file(logic.team_emojis_file)
try:
await channel.send("Ukens kupong:")
fixtures = API.get_matches(days) # Fetch matches for the next x days
messages = []
for fixture in fixtures:
message_content, home_team_emoji, away_team_emoji = logic.FormatMatchMessge(fixture, emoji_data)
message = await channel.send(message_content)
messages.append((str(message.id), fixture['match_id']))
for reaction in (home_team_emoji, '🇺', away_team_emoji):
await message.add_reaction(reaction)
file_functions.write_file(logic.tracked_messages, messages)
date_start, hour_start, minute_start, messages_id = get_day_hour_minute(days)
anyGames = await update_jobs(date_start, hour_start, minute_start, messages_id, channel)
if not anyGames:
await interaction.followup.send(f"Ingen kamper de neste {days} dagene", ephemeral=True)
return
await interaction.followup.send("Kupong sendt!", ephemeral=True)
return
except discord.errors.Forbidden:
await interaction.followup.send(f"Missing permissions to send message in channel {channel.name}", ephemeral=True)
except Exception as e:
await interaction.followup.send(f"An error occurred: {e}. Ta kontakt med Runar (trunar)", ephemeral=True)
traceback.print_exc()
else:
await interaction.response.send_message("Denne kommandoen kan kun brukes i en spesifikk server.", ephemeral=True)
@bot.tree.command(name="total_ledertavle", description="Vis totale resultater")
async def total_leaderboard(interaction: discord.Interaction):
if logic.check_if_valid_server(interaction.guild_id):
await interaction.response.defer(ephemeral=True)
if interaction.guild_id != perms.guild_id:
await interaction.followup.send("Denne kommandoen kan kun brukes i en spesifikk server", ephemeral=True)
return
# Sort user scores by points (descending order)
scores = file_functions.read_file(logic.user_scores)
guild = interaction.guild
if isinstance(scores, dict):
leaderboard_message = await leaderboard.total_leaderboard_message(scores, guild)
else:
await interaction.followup.send("Det oppsto en feil med å hente poengene.", ephemeral=True)
return
# Send the leaderboard message to the Discord channel
if leaderboard_message == "Tippekupongen 2024:\n":
await interaction.followup.send("Vær litt tålmodig da, det ekke registrert poeng enda.")
else:
messages = logic.split_message(leaderboard_message)
for m in messages:
await interaction.followup.send(m, ephemeral=True)
else:
await interaction.response.send_message("Denne kommandoen kan kun brukes i en spesifikk server.", ephemeral=True)
@bot.tree.command(name="ukens_resultater", description="Vis resultatene fra forrige uke, og totale resultater. Kall denne FØR ukens kupong")
@commands.has_permissions(manage_messages=True)
async def send_leaderboard_message(interaction: discord.Interaction):
if logic.check_if_valid_server(interaction.guild_id):
await interaction.response.defer()
try:
guild = await bot.fetch_guild(perms.guild_id)
message = await leaderboard.format_leaderboard_message(guild)
print(message)
if message and message.strip():
messages = logic.split_message(message)
for m in messages:
await interaction.followup.send(m)
else:
await interaction.followup.send("Det har ikke vært noen kamper de siste dagene, eller så er det ikke data å hente ut. Prøv igjen senere.", ephemeral=True)
# Send "Task completed!" message after other responses
except discord.errors.Forbidden:
await interaction.followup.send("Du kanke bruke denne kommandoen tjommi.", ephemeral=True)
except Exception as e:
await interaction.followup.send(f"An error occurred: {e}. Ta kontakt med Runar (trunar)", ephemeral=True)
traceback.print_exc()
# Send "Task completed!" message after all other responses
await interaction.followup.send("Task completed!", ephemeral=True)
else:
await interaction.response.send_message("Denne kommandoen kan kun brukes i en spesifikk server.", ephemeral=True)
@bot.tree.command(name="lagre_tips_manuelt", description="Kopier meldingen for kampen sine reaksjoner du vil lagre")
@commands.has_permissions(manage_messages=True)
async def find_message_by_content(interaction: discord.Interaction, content: str):
if logic.check_if_valid_server(interaction.guild_id):
channel = await bot.fetch_channel(channel_id)
await interaction.response.defer(ephemeral=True)
message_data = file_functions.read_file(logic.tracked_messages) # List of (message_id, match_id)
found = False
for message_id, _ in message_data:
message = await channel.fetch_message(int(message_id))
if content in message.content:
await interaction.followup.send(f"Message found: {message.jump_url}", ephemeral=True)
await leaderboard.StorePredictions(message_id, channel, bot)
found = True
break
else:
await interaction.response.send_message("Denne kommandoen kan kun brukes i en spesifikk server.", ephemeral=True)
@bot.tree.command(name="se_scheduled_events", description="Se når kupongen for en kamp blir lagret")
@commands.has_permissions(manage_messages=True)
async def print_scheduled_event(interaction: discord.Interaction):
jobs = file_functions.read_file(logic.scheduled_jobs)
message_ids = [job['message_id'] for job in jobs]
channel = await bot.fetch_channel(channel_id)
await interaction.response.defer(ephemeral=True)
for job in scheduler.get_jobs():
if job.id in message_ids:
try:
match_message = await channel.fetch_message(job.id)
match_content = match_message.content # Get the content of the message
await interaction.followup.send(f"{match_content} sin kupong vil bli hentet ut {job.next_run_time}", ephemeral=True)
except discord.NotFound:
await interaction.followup.send(f"Message with ID {job.id} not found in channel.", ephemeral=True)
continue
except Exception as e:
await interaction.followup.send(f"An error occurred: {e}. Ta kontakt med Runar (trunar)", ephemeral=True)
traceback.print_exc()
continue
@bot.tree.command(name='clear_cache', description='Tømmer json-filer')
@commands.has_permissions(manage_messages=True)
async def clear_cache(interaction: discord.Integration):
if logic.check_if_valid_server(interaction.guild_id):
await interaction.response.defer(ephemeral=True)
file_functions.clear_file(logic.predictions_file, {})
file_functions.clear_file(logic.tracked_messages, [])
file_functions.clear_file(logic.scheduled_jobs, [])
await interaction.followup.send("Cache tømt", ephemeral=True)
else:
await interaction.response.send_message("Denne kommandoen kan kun brukes i en spesifikk server.", ephemeral=True)
@bot.tree.command(name='sjekk_lagret_data', description='Sjekker predictions-fila')
@commands.has_permissions(manage_messages=True)
async def check_predictions_stored(interaction: discord.Integration):
await interaction.response.defer(ephemeral=True)
channel = await bot.fetch_channel(channel_id)
predictions_file = file_functions.read_file(logic.predictions_file)
message_list = []
for message_id, _ in predictions_file.items():
message = await channel.fetch_message(int(message_id))
if message:
msg = f"Reactions for match {message} has been stored."
message_list.append(msg)
if message_list:
await interaction.followup.send("\n".join(message_list), ephemeral=True)
else:
await interaction.followup.send("No stored predictions found.", ephemeral=True)
def get_day_hour_minute(days):
day_of_week = []
hour = []
minute = []
data = API.get_matches(days)
message_id_and_match_id = file_functions.read_file(logic.tracked_messages)
message_ids = [message_id for message_id, _ in message_id_and_match_id]
# Extract the message IDs as a list
for date in data:
# Parse the date string into a datetime object
date_time = datetime.fromisoformat(date['date'])
# Get the day of the week
day_of_week_add = date_time.strftime('%A')[:3].lower()
day_of_week.append(day_of_week_add)
# Get the hour and minute
hour_add = int(date_time.strftime('%H'))
hour.append(str(hour_add))
minute_add = int(date_time.strftime('%M'))
minute.append(str(minute_add))
return day_of_week, hour, minute, message_ids
async def update_jobs(date_start, hour_start, minute_start, message_ids, channel):
# Remove existing jobs
if scheduler.get_jobs():
scheduler.remove_all_jobs()
print("Old jobs removed")
if not date_start: # Check if there are no new jobs to schedule
print("No new jobs to schedule.")
return False
job_details_list = [] # List to hold details of each job
existing_jobs = file_functions.read_file(logic.scheduled_jobs)
if not isinstance(existing_jobs, list):
existing_jobs = []
# Schedule new jobs
for date, hour, minute, message_id in zip(date_start, hour_start, minute_start, message_ids):
scheduler.add_job(
leaderboard.StorePredictions,
'cron',
day_of_week=date,
hour=hour,
minute=minute,
timezone=timezone,
args=[message_id, channel, bot],
id=str(message_id)
)
save_schedule_to_json = {
"message_id": message_id,
"date": date,
"hour": hour,
"minute": minute
}
existing_jobs.append(save_schedule_to_json)
job_details = f"Job ID: {message_id}, Scheduled Time: {date} at {hour}:{minute}, Function: {leaderboard.StorePredictions.__name__}"
job_details_list.append(job_details)
file_functions.write_file(logic.scheduled_jobs, existing_jobs)
print("Jobs added.")
for details in job_details_list:
print(details)
return True
bot.run(perms.TOKEN)