On a discord bot I'm trying to continually clear some channels with the code below so that you can add channels and set a scheduled clear specified for it with time interval in hours or in minutes. So, when I type
!cc channelid1 3h
!cc channelid2 12h
,
it will add 2 separated channels to be cleared at their specific time
When I do !start
in Discord, I get Scheduled clear started. But no message is deleted and there is no error in output, terminal or logs
The code is below. What did I do wrong? Something not logical ? in the code any other approach ?
import discord
import pytz
from datetime import datetime, timedelta
from discord.ext import commands, tasks
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
channels_to_clear = {} # Dictionary of channel IDs and their clear frequencies
hours_between_clears = 24 # The default number of hours between clearings is 24 hours
channel_clear_frequencies = {} # Dictionary to store the clear frequencies for each channel
# Define the scheduled clear task
@tasks.loop(minutes=1)
async def scheduled_clear():
now = datetime.now(pytz.utc)
for channel_id in channels_to_clear:
channel = bot.get_channel(channel_id)
clear_frequency = channels_to_clear[channel_id]['clear_frequency']
if (now - channels_to_clear[channel_id]['last_cleared']).total_seconds() / 3600 >= clear_frequency:
messages = []
two_weeks_ago = datetime.now(pytz.utc) - timedelta(days=14)
async for message in channel.history(limit=None):
if not message.pinned and message.created_at > two_weeks_ago:
messages.append(message)
for i in range(0, len(messages), 100):
try:
await channel.delete_messages(messages[i:i+100])
except discord.HTTPException as e:
print(f"An error occurred while deleting messages: {e}")
channels_to_clear[channel_id]['last_cleared'] = now
# Define the add and remove channel commands, and set_clear_frequency
@bot.command(aliases=['cc'])
@commands.has_permissions(administrator=True)
async def clear_channel(ctx, channel_id: int, time_interval: str):
'''!cc channelid time in hours or minutes. !cc 12345678 3m'''
global channels_to_clear
try:
if time_interval.endswith("h"):
hours = int(time_interval[:-1])
if channel_id in channels_to_clear:
channels_to_clear[channel_id]['clear_frequency'] = hours
await ctx.send(f"Clear frequency for <#{channel_id}> set to {hours} hours.")
else:
channels_to_clear[channel_id] = {'clear_frequency': hours, 'last_cleared': datetime.now(pytz.utc)}
await ctx.send(f"Added channel <#{channel_id}> to the list of channels to clear with a clear frequency of {hours} hours.")
elif time_interval.endswith("m"):
minutes = int(time_interval[:-1])
hours = minutes / 60
if channel_id in channels_to_clear:
channels_to_clear[channel_id]['clear_frequency'] = hours
await ctx.send(f"Clear frequency for <#{channel_id}> set to {minutes} minutes ({hours} hours).")
else:
channels_to_clear[channel_id] = {'clear_frequency': hours, 'last_cleared': datetime.now(pytz.utc)}
await ctx.send(f"Added channel <#{channel_id}> to the list of channels to clear with a clear frequency of {minutes} minutes ({hours} hours).")
else:
await ctx.send("Invalid time interval. Please specify a time interval in hours (h) or minutes (m).")
except Exception as e:
await ctx.send(f"An error occurred while processing your request: {e}")
@bot.command(aliases=['rc'])
@commands.has_permissions(administrator=True)
async def remove_channel(ctx, channel_id: int):
if channel_id in channels_to_clear:
channels_to_clear.pop(channel_id)
await ctx.send(f"Removed channel <#{channel_id}> from the list of channels to clear.")
else:
await ctx.send(f"Channel <#{channel_id}> is not in the list of channels to clear.")
# Define the start and stop commands
@bot.command()
@commands.has_permissions(administrator=True)
async def start(ctx): #start the clearing command
try:
for channel_id in channels_to_clear:
scheduled_clear.change_interval(hours=channel_clear_frequencies.get(channel_id, hours_between_clears))
scheduled_clear.start()
await ctx.send("Scheduled clear started.")
except Exception as e:
await ctx.send(f"An error occurred while starting the scheduled clear: {e}")
@bot.command()
@commands.has_permissions(administrator=True)
async def stop(ctx): #stop the clearing command
scheduled_clear.stop()
await ctx.send("Scheduled clear stopped.")
@bot.command(aliases=['scf'])
@commands.has_permissions(administrator=True)
async def set_clear_frequency(ctx, channel_id: int, time_interval: str):
try:
if channel_id in channels_to_clear:
if time_interval.endswith("h"):
hours = int(time_interval[:-1])
channel_clear_frequencies[channel_id] = hours
scheduled_clear.change_interval(hours=hours)
await ctx.send(f"Clear frequency for channel <#{channel_id}> set to {hours} hours.")
elif time_interval.endswith("m"):
minutes = int(time_interval[:-1])
hours = minutes / 60
channel_clear_frequencies[channel_id] = hours
scheduled_clear.change_interval(minutes=minutes)
await ctx.send(f"Clear frequency for channel <#{channel_id}> set to {minutes} minutes.")
else:
await ctx.send("Invalid time interval. Please specify a time interval in hours (h) or minutes (m).")
else:
await ctx.send(f"Channel <#{channel_id}> is not in the list of channels to clear.")
except Exception as e:
await ctx.send(f"An error occurred while setting clear frequency: {e}")
# Define the list_channels command
@bot.command(aliases=['lc'])
@commands.has_permissions(administrator=True)
async def list_channels(ctx):
if channels_to_clear:
embed = discord.Embed(title="Channels to Clear", color=0x00ff00)
for channel_id in channels_to_clear:
channel = bot.get_channel(channel_id)
clear_frequency = channels_to_clear[channel_id]['clear_frequency']
clear_frequency_str = f"{clear_frequency} hours"
if clear_frequency < 1:
clear_frequency_str = f"{clear_frequency * 60} minutes"
embed.add_field(name=f"{channel.name} ({channel.id})", value=f"Clear frequency: {clear_frequency_str}")
await ctx.send(embed=embed)
else:
await ctx.send("There are no channels to clear.")
bot.run('Token')
source https://stackoverflow.com/questions/75779586/message-doesnt-get-deleted-in-discord-but-i-dont-get-any-error
Comments
Post a Comment