few changes

This commit is contained in:
2025-03-21 23:36:56 +01:00
parent 14c3807719
commit d2205a0207
+52 -18
View File
@@ -1,4 +1,5 @@
import asyncio
import discord import discord
from discord.ext import commands, tasks from discord.ext import commands, tasks
from discord import app_commands from discord import app_commands
@@ -10,12 +11,12 @@ from os import environ as env
# Channel ids # Channel ids
CUSTOM_CHANNELS = set([ CUSTOM_CHANNELS = set([
1352404223127588924 int(env['CHANNEL_ID'])
]) ])
TOKEN = env['TOKEN'] TOKEN = env['TOKEN']
HOURS = 10 MINUTES = 10
ROLE = env['ROLE'] ROLE = int(env['ROLE'])
CHANNELS = set([]) CHANNELS = set([])
def decode(value): def decode(value):
@@ -37,37 +38,70 @@ async def on_ready():
CHANNELS.add(bot.get_channel(cc)) CHANNELS.add(bot.get_channel(cc))
check_inactivity.start() check_inactivity.start()
@tasks.loop(seconds=HOURS) active_trivia = {} # Format: {message_id: {"correct_answer": answer, "count": 0}}
@tasks.loop(seconds=150)
async def check_inactivity(): async def check_inactivity():
if ROLE is not None: if ROLE is not None:
current_time = datetime.now(timezone.utc)
print(f"{current_time.strftime('%H:%M:%S')} - Running inactivity check")
current_question = None current_question = None
for channel in CHANNELS: for channel in CHANNELS:
print(f"{datetime.now(timezone.utc).strftime('%H:%M:%S')} - Checking channel {channel.name}")
async for message in channel.history(limit=1): async for message in channel.history(limit=1):
if (datetime.now(timezone.utc) - message.created_at).total_seconds() > HOURS: # seconds_since = (current_time - message.created_at).total_seconds()
# print(f"{datetime.now(timezone.utc).strftime('%H:%M:%S')} - Time since last message: {seconds_since} seconds")
minutes_since = (current_time - message.created_at).total_seconds() / 60
print(f"{datetime.now(timezone.utc).strftime('%H:%M:%S')} - Time since last message: {minutes_since} minutes")
if minutes_since > MINUTES:
print(f"{datetime.now(timezone.utc).strftime('%H:%M:%S')} - Channel is inactive, sending message")
if current_question is None: if current_question is None:
current_question = requests.get(OPENTDB_URL).json()['results'][0] current_question = requests.get(OPENTDB_URL).json()['results'][0]
decoded_data = {k: decode(v) if isinstance(v, str) else [decode(i) for i in v] for k, v in current_question.items()} decoded_data = {k: decode(v) if isinstance(v, str) else [decode(i) for i in v] for k, v in current_question.items()}
answers = list(decoded_data['incorrect_answers']) + [decoded_data['correct_answer']]
answers: list[str] = list(decoded_data['incorrect_answers'] + [decoded_data['correct_answer']])
shuffle(answers) shuffle(answers)
role_mention = f"<@&{ROLE}>" role_mention = f"<@&{ROLE}>"
embedVar = discord.Embed(title=decoded_data['question'], description="", color=0x00ff00) embedVar = discord.Embed(title=decoded_data['question'], description="", color=0x00ff00)
embedVar.add_field(name="Difficulty", value=decoded_data['difficulty'].capitalize(), inline=False) embedVar.add_field(name="Difficulty", value=str(decoded_data['difficulty']).capitalize(), inline=False)
embedVar.add_field(name="Answers", value='**'+('\n'.join(['- '+a for a in answers]))+'**', inline=False) embedVar.add_field(name="Answers", value='**'+('\n'.join(['- '+str(a) for a in answers]))+'**', inline=False)
msg = await channel.send(role_mention, embed=embedVar) msg = await channel.send(role_mention, embed=embedVar)
def check(m): # Store this question in our tracking dict
return m.reference and m.reference.message_id == msg.id and m.author != bot.user active_trivia[msg.id] = {
"correct_answer": str(decoded_data['correct_answer']).lower(),
"count": 0,
"max_replies": 10
}
print(f"{datetime.now(timezone.utc).strftime('%H:%M:%S')} - Added trivia question ID {msg.id}")
for _ in range(0, 10):
reply = await bot.wait_for("message", check=check)
if reply.content.lower() == decoded_data['correct_answer'].lower(): @bot.event
await reply.add_reaction("✅") async def on_message(message):
else: # Process commands first (important for command handling)
await reply.add_reaction("❌") await bot.process_commands(message)
# Skip if it's a bot message
if message.author.bot:
return
# Check if this is a reply to a trivia question
if message.reference and message.reference.message_id in active_trivia:
trivia_data = active_trivia[message.reference.message_id]
# Check answer
if message.content.lower() == trivia_data["correct_answer"]:
await message.add_reaction("✅")
else:
await message.add_reaction("❌")
# Increment the count
trivia_data["count"] += 1
# If we've reached max replies, remove this question from tracking
if trivia_data["count"] >= trivia_data["max_replies"]:
del active_trivia[message.reference.message_id]
print(f"{datetime.now(timezone.utc).strftime('%H:%M:%S')} - Removed trivia question ID {message.reference.message_id} after {trivia_data['max_replies']} replies")
bot.run(TOKEN) bot.run(TOKEN)