#๐ custom timer
9 messages ยท Page 1 of 1 (latest)
@obtuse forge
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
import discord as dc
from discord.ext import commands as cm, tasks as tk
from discord import app_commands as ap
import json as js
from datetime import datetime as dt, timedelta as td
GUILD_ID = x
TIMER_DATA_FILE = "tmr_data.json"
class TimerCog(cm.Cog):
def __init__(self, bot: cm.Bot):
self.bot = bot
self.load_timers()
self.save_tTimers()
def load_timers(self):
try:
with open(TIMER_DATA_FILE, "r") as f:
self.timers = js.load(f)
except FileNotFoundError:
self.timers = {}
def save_timers(self):
with open(TIMER_DATA_FILE, "w") as f:
js.dump(self.timers, f, indent=4)
async def cog_load(self):
try:
guild = dc.Object(id=GUILD_ID)
await self.bot.tree.sync(guild=guild)
self.timer_loop.start()
print("Commands synced and timer loop started.")
except dc.Forbidden as e:
print(f"Failed to sync commands or start timer loop: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
@tk.loop(seconds=60)
async def timer_loop(self):
now = dt.utcnow()
expired_timers = []
for channel_id, timer in self.timers.items():
end_time = dt.fromisoformat(timer["end_time"])
if now >= end_time:
channel = self.bot.get_channel(timer["channel_id"])
if channel:
try:
embed = dc.Embed(
title=timer.get("name", "Timer"),
description=timer.get("description", "Time's up!"),
color=dc.Color(int(timer.get("end_color", "FF0000"), 16))
)
if "footer" in timer:
embed.set_footer(text=timer["footer"])
if "thumbnail" in timer:
embed.set_thumbnail(url=timer["thumbnail"])
if "image" in timer:
embed.set_image(url=timer["image"])
await channel.send(embed=embed)
except dc.DiscordException as e:
print(f"Failed to send message in channel {channel.id}: {e}")
expired_timers.append(channel_id)
for channel_id in expired_timers:
del self.timers[channel_id]
self.save_timers()
@timer_loop.before_loop
async def before_timer_loop(self):
await self.bot.wait_until_ready()
@ap.command(name="timer", description="Set a timer for a specified number of minutes.")
async def set_timer(self, interaction: dc.Interaction, minutes: int, name: str = "Timer"):
channel_id = interaction.channel.id
end_time = dt.utcnow() + td(minutes=minutes)
self.timers[str(channel_id)] = {
"end_time": end_time.isoformat(),
"channel_id": channel_id,
"name": name,
"color": "00FF00" # Green color for the start of the timer
}
self.save_timers()
embed = dc.Embed(
title=name,
description=f"Timer set for {minutes} minutes.",
color=dc.Color.green() # Green color when the timer starts
)
await interaction.response.send_message(embed=embed, ephemeral=True)
@ap.command(name="timer_name", description="Change the name of the active timer.")
async def change_timer_name(self, interaction: dc.Interaction, name: str):
channel_id = str(interaction.channel.id)
if channel_id in self.timers:
self.timers[channel_id]["name"] = name
self.save_timers()
await interaction.response.send_message(f"Timer name changed to: {name}.", ephemeral=True)
else:
await interaction.response.send_message("No active timer found.", ephemeral=True)
@ap.command(name="timer_check", description="Check the remaining time on the active timer.")
async def check_timer(self, interaction: dc.Interaction):
channel_id = str(interaction.channel.id)
if channel_id in self.timers:
now = dt.utcnow()
end_time = dt.fromisoformat(self.timers[channel_id]["end_time"])
minutes_left = (end_time - now).total_seconds() // 60
await interaction.response.send_message(f"Time remaining: {int(minutes_left)} minutes.", ephemeral=True)
else:
await interaction.response.send_message("No active timer found.", ephemeral=True)
@ap.command(name="customize_timer", description="Customize the embed for the active timer.")
async def customize_timer(self, interaction: dc.Interaction, description: str = None, color: str = None, footer: str = None, thumbnail: str = None, image: str = None, end_color: str = None):
channel_id = str(interaction.channel.id)
if channel_id in self.timers:
# Update the timer with the provided customization
if description:
self.timers[channel_id]["description"] = description
if color:
self.timers[channel_id]["color"] = color.lstrip('#')
if footer:
self.timers[channel_id]["footer"] = footer
if thumbnail:
self.timers[channel_id]["thumbnail"] = thumbnail
if image:
self.timers[channel_id]["image"] = image
if end_color:
self.timers[channel_id]["end_color"] = end_color.lstrip('#')
self.save_timers()
await interaction.response.send_message("Timer customization updated.", ephemeral=True)
else:
await interaction.response.send_message("No active timer found.", ephemeral=True)
async def setup(bot: cm.Bot):
await bot.add_cog(TimerCog(bot))
if __name__ == "__main__":
import os
import logging
logging.basicConfig(level=logging.INFO)
intents = dc.Intents.default()
intents.message_content = True
bot = cm.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}!')
async def main():
await bot.load_extension("cogs.timer")
await bot.start(os.getenv('DISCORD_TOKEN'))
import asyncio
asyncio.run(main())
async def setup(bot: commands.Bot):
await bot.add_cog(timer(bot))
INFO:main:------
INFO:main:Loading cogs...
INFO:main:Successfully loaded cog: CC-Panel
ERROR:main:Failed to load cog timer. Error: Extension 'cogs.timer' raised an error: Forbidden: 403 Forbidden (error code: 50001): Missing Access
INFO:main:Successfully synced 3 commands.
is the error message
All intents are on
@obtuse forge
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.