Delete messages from specifc user using Discord py - discord

I wanted to create a clear command where if example .clear #user#0000 100 it will clear the last 100 messages #user#0000 sent. Here is my code:
#commands.command()
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, amount=1):
await ctx.channel.purge(limit=amount + 1)
#clear.error
async def clear_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('Sorry, you are missing the ``MANAGE_MESSAGES`` permission to use this command.')
This code i provided only deletes depeneding how many messages will be deleted in a channel. I want to make a code where the bot will delete messages from a specific user. If this is possible, please let me know. I will use the code as future reference. Much appreciated.

You can use check kwarg to purge messages from specific user:
from typing import Optional
#commands.command()
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, member: Optional[discord.Member], amount: int = 1):
def _check(message):
if member is None:
return True
else:
if message.author != member:
return False
_check.count += 1
return _check.count <= amount
_check.count = 0
await ctx.channel.purge(limit=amount + 1 if member is None else 1000, check=_check)

Related

Making an optional Argument in discord py

I want to make a code where if no one is mentioned then it should consider the person using it as a target.
Here is what I tried so far.
`#bot.command()
async def bal(ctx,*,member: discord.Member= None):
if member == None:
member = ctx.message.author
purse = db.get(member)
await ctx.send(purse)
`
But it's not working 🐱
first of all it should be
ctx.author
not
ctx.message.author
and u should put the * at the end I think
it should like sth like this
#bot.command()
async def bal(ctx,member: discord.Member= None,*):
if member == None:
member = ctx.author
purse = db.get(member)
await ctx.send(purse)
using * means that you are forcing the user to input keyword only arguements, but in your case it's not needed and i think is probably giving you an error since it's a bare *
so following on what bishoy did
#bot.command()
async def bal(ctx,member: discord.Member= None):
if member == None:
member = ctx.author
purse = db.get(member)
await ctx.send(purse)
this will remove the error, no need for the *

How can I change the permissions of a specific role of a channel in discord.py

I'm trying to make a command that takes a channel name as input (or argument) and locks that channel but for only the students in the channel. Here's the code:
# bot.GUILD = bot.get_channel(guild_id) [In on_ready method in bot class]
#bot.command()
async def lock(ctx, channel_name):
user_dm = await bot.create_dm(ctx.author)
channels = await bot.GUILD.fetch_channels()
roles = await bot.GUILD.fetch_roles()
channels = list(filter(lambda c: c.name.lower() == channel_name.lower(), channels))
student_roles = list(filter(lambda r: r.name.endswith("students"), roles))
# print(channels, roles) [This works fine]
if channels:
for channel in channels:
for role in student_roles:
await channel.set_permissions(role, send_messages=False)
await user_dm.send(f"✅ {channel_name} has been locked!")
else:
await user_dm.send(f"❌ {channel_name} does not exist!")
I don't know why it's not sending any message to my dm. Because it's an if-else statement so at least I get a message from the bot whether positive or negative but that doesn't happen. And yes my bot has the necessary permissions. I really hope you can help me with this 😕🥺

Problems with a discord.py bot

I have been trying to code a Discord bot for my own server.
However, it seems like, whenever I add more commands to the code, the ban, and kick functions no longer work correctly.
I've tried rewriting the code multiple times, but it did not work.
I've tried rearranging the codes, and that did not work as well.
client = commands.Bot(command_prefix = '!')
#client.command()
async def kick(ctx, member : discord.Member, *, reason = None):
await member.kick(reason = reason)
#client.command()
async def ban(ctx, member : discord.Member, *, reason = None):
await member.ban(reason = reason)
curseWord = ['die', 'kys', 'are you dumb', 'stfu', 'fuck you', 'nobody cares', 'do i care', 'bro shut up']
def get_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)
#ready
#client.event
async def on_ready():
print('LOGGED IN as mr MF {0.user}'.format(client))
#client.event
#detect self messages
async def on_message(message):
if message.author == client.user:
return
#greeting
if message.content.startswith('hello'):
await message.channel.send('ay whatup ma gamer')
#help
if message.content.startswith('!therapy'):
quote = get_quote()
await message.channel.send(quote)
#toxicity begone
msg_content = message.content.lower()
if any(word in msg_content for word in curseWord):
await message.delete()
#environment token
token = os.environ['token']
client.run(token)
You have overwritten the on_message event, which by default processes commands (those marked with the #client.command() decorator). You need to explicitly tell the library to process commands when you overwrite it. As noted in the discord.py documentation, you should add this line at the end of the on_message event:
await client.process_commands(message)

Discord.py bot clear

Alright so guys i need some help. Basically i am making an discord bot. I'm having problems with clear(purge) command. So this is my code so far:
#client.command(aliases= ['purge','delete'])
#commands.has_permissions(manage_messages=True)
async def clear(ctx, amount : int):
if amount == None:
await ctx.channel.purge(limit=1000000)
else:
await ctx.channel.purge(limit=amount)
my problem here is this if amount == None .
Please help me!
Im getting an error that i have missing requied argument...
That's because you're not giving amount the default value None. This is how you should define the function:
#client.command(aliases= ['purge','delete'])
#commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=None): # Set default value as None
if amount == None:
await ctx.channel.purge(limit=1000000)
else:
try:
int(amount)
except: # Error handler
await ctx.send('Please enter a valid integer as amount.')
else:
await ctx.channel.purge(limit=amount)
This one is working for me
#client.command()
#has_permissions(manage_messages = True)
async def clear(ctx , amount=5):
await ctx.channel.purge(limit=amount + 1)
I got it from a youtuber channel, you can put the number of the messages u want to clear after the clear command, EX:
-clear 10
Try this:
#client.command(aliases = ['purge', 'delete'])
#commands.has_permissions(manage_messages = True)
async def clear(ctx, amount: int = 1000000):
await ctx.channel.purge(limit = amount)
This should work, as I have a clear command that looks almost exactly like this. The amount param is being converted to an int and if the client doesn't give parameters, the amount will be set at 1000000.
This is the one I'm using atm.
#bot.command(name='clear', help='this command will clear msgs')
async def clear(ctx, amount = 50): # Change amount
if ctx.message.author.id == (YOUR USER ID HERE):
await ctx.channel.purge(limit=amount)
else:
await ctx.channel.send(f"{ctx.author.mention} you are not allowed")
I've just added an 'if' statement for being the only one who can use that command. You can also allow an specific role.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='>')
#client.event
async def on_ready():
print("Log : "+str(client.user))
#client.command()
#commands.has_permissions(manage_messages=True)
async def clear(ctx, amount: int):
await ctx.channel.purge(limit=amount+1)
await ctx.message.delete()
client.run("token")
you can do this:
#client.command(aliases= ['purge','delete'])
#commands.has_permissions(manage_messages=True)
async def clear(ctx, amount :int = -1):
if amount == -1:
await ctx.channel.purge(limit=1000000)
else:
await ctx.channel.purge(limit=amount)
I think it should work, if the client doesn't give parameters, the amount will be set at "-1"

Using Discord.py rewrite to delete messages

As the title states, I'm trying to delete messages using my !purge command. I have this down already:
#bot.command()
#commands.has_permissions(manage_messages=True)
async def purge(ctx):
await delete_messages(ctx, member)
await ctx.send("Deleted messages")
It's saying that delete_messages is not defined. Please help me!
So we are in year 2019. I'll help you with your code.
delete_messages is a method of a TextChannel object.
In your line await delete_messages(ctx, member), add ctx.message.channel. just before delete_messages.
Your line would then go like this:
await ctx.message.channel.delete_messages(ctx, member)
Hope that clears things up.
If it did, don't hesitate to 'accept' the answer by clicking the check mark.
This will delete only up to 99 messages (+ the purge command) at a time and the messages must be under 14 days old.
#bot.command(pass_context=True, name='purge', aliases=['purgemessages'], no_pm=True)
async def purge(ctx, number):
number = int(number)
if number > 99 or number < 1:
await ctx.send("I can only delete messages within a range of 1 - 99", delete_after=10)
else:
author = ctx.message.author
authorID = author.id
mgs = []
number = int(number)
channel = ctx.message.channel
async for x in bot.logs_from((channel), limit = int(number+1)):
mgs.append(x)
await delete_messages(mgs)
await ctx.send('Success!', delete_after=4)

Resources