Search code examples
python-3.xdiscord.pybots

Why does my Python 3.x discord.py bot's purge command work in my test server but not in other servers?


I have been making a discord bot using discord.py v2.2.3 & Python v3.11.3 and I recently made a purge command. Once loaded in my test server everything worked fine, now when I try it in my other servers it worked maybe once or twice but now it just throws my error message. I have went over it and watched a few tutorials but I can't seem to get it right.

When i use the command the obvious intent is to purge / clear messages. As stated it works in my test server just not in my other servers which is very odd.. Note i am new to Python, so i did expect to run into bugs fairly early and am excited to work on fixing them. Here is my clean message method.

async def clean_message(self, interaction: Interaction, amount: int, check: Callable) -> Any:
        if isinstance((channel := interaction.channel), (CategoryChannel, ForumChannel, PartialMessageable)):
            return
        assert channel is not None
        try:
            msgs = [
                m async for m in channel.history(
                    limit=300,
                    before=Object(id=interaction.id),
                    after=None
                ) if check(m) == True and UTC.localize((datetime.now() - timedelta(days=365))) <= m.created_at  # default 14
            ][:amount]
            await channel.delete_messages(msgs)
        except Exception as e:
            msg = await self.bot.error(
                f"I'm sorry, I am unable to purge messages in **{channel}**!", interaction
            )
            if msg:
                await msg.delete(delay=5)
        else:
            if len(msgs) < 1:
                msg = await self.bot.error(
                    f"No messages found in **{channel}**!", interaction
                )
                if msg:
                    await msg.delete(delay=5)
            else:
                msg = await self.bot.success(
                    f"Succesfully purged **{len(msgs)}** messages from **{channel}**!", interaction
                )
                if msg:
                    await msg.delete(delay=5)

Which is called by the purge command here.

    @app_commands.command(
        name='purge',
        description="Purges messages in channel"
    )
    @app_commands.default_permissions(manage_messages=True)
    @app_commands.describe(
        amount='Amount of messages to purge (Default: 20)',
        user='Only purge messages by user',
        content='Only purge messages by content'
    )
    async def purge_command(self, interaction: Interaction, amount: Optional[int], user: Optional[User], content: Optional[str]):
        if not amount:
            amount = 20
        if amount < 1:
            return await self.bot.error("Can't purge messages! Amount too small!", interaction)
        if amount > 150:
            return await self.bot.error("Can't purge messages! Amount too Large!", interaction)

        if user == None and content == None:
            def check(x): return x.pinned == False
        else:
            if user != None and content != None:
                def check(x): return x.author.id == user.id and x.content.lower(
                ) == content.lower() and x.pinned == False
            elif user != None and content == None:
                def check(x): return x.author.id == user.id and x.pinned == False
            else:
                assert content is not None
                def check(x): return x.conetent.lower(
                ) == content.lower() and x.pinned == False
        await interaction.response.defer()
        await self.clean_message(
            interaction=interaction,
            amount=amount,
            check=check
        )

Solution

  • Okay... so i just realized how dumb i was. I had forgotten i was messing with the max purged messages and range limit. The max amount of purged messages was set to 300 over a 365 day range. Simple mistake that took four hours to fix. All i had to do was up the message cap to anything more than it was and decrease the range.

    try:
      msgs = [
        m async for m in channel.history(
          limit=30000,
          before=Object(id=interaction.id),
          after=None
        ) if check(m) == True and UTC.localize((datetime.now() - timedelta(days=14))) <= m.created_at  # default 14
      ][:amount]
      await channel.delete_messages(msgs)