I am having difficulties figuring out how to code my Discord bot to clear messages from a specified user (ex. /purge [user] [num]
). I have been able to get it to clear messages in general but keep running into issues with specifying the user.
#Purge command
@commands.has_permissions(administrator=True)
@bot.slash_command(
name="purge", description="Purge messages from channel",
guild_ids=[1222114873962663967]
)
async def purge(ctx, number: int):
await ctx.channel.purge(limit=number+1)
await ctx.respond(f"Purged {number} messages")
This code works fine for purging the messages, but I am at a loss on how to code this with the optional "user" parameter.
The TextChannel.purge() method also has a check
parameter through which you can configure a function to filter the messages that will be deleted. For example:
#Purge command
@commands.has_permissions(administrator=True)
@bot.slash_command(
name="purge", description="Purge messages from channel",
guild_ids=[1222114873962663967]
)
async def purge(ctx, number: int, member: discord.Member = None):
# deleting several messages may take more than 3 seconds
# it is recommended to defer the interaction to respond later
await interaction.response.defer(ephemeral=True)
if member:
deleted = await ctx.channel.purge(limit=number, check=lambda m: m.author == member)
else:
deleted = await ctx.channel.purge(limit=number)
await interaction.followup.send(f"Purged {len(deleted)} messages")