Skip to main content

Message doesn't get deleted in Discord but I dont get any error

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

Popular posts from this blog

Prop `className` did not match in next js app

I have written a sample code ( Github Link here ). this is a simple next js app, but giving me error when I refresh the page. This seems to be the common problem and I tried the fix provided in the internet but does not seem to fix my issue. The error is Warning: Prop className did not match. Server: "MuiBox-root MuiBox-root-1" Client: "MuiBox-root MuiBox-root-2". Did changes for _document.js, modified _app.js as mentioned in official website and solutions in stackoverflow. but nothing seems to work. Could someone take a look and help me whats wrong with the code? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console