Using Discord.py rewrite to delete messages - discord

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)

Related

Delete messages from specifc user using Discord py

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)

How to index into the channel.members list and take out the name? Closed

So I'm trying to get the names of all the people in a voice channel, but the bot returns a list like so:
[<Member id=704069756717629472 name='Eedward' discriminator='8402' bot=False nick=None guild=<Guild id=807690875802878003 name='lfg testing' shard_id=None chunked=True member_count=3>>]
Is there any way I can take that "name" part out of the list? Or is there a better way to do something like this? This is my code:
#client.command()
async def lfg(ctx, game, *,extra=None):
if not ctx.message.author.voice:
await ctx.send(f"{ctx.author.name}, you need to connect to a voice channel first to use this command.")
return
else:
channel = ctx.message.author.voice.channel
link = await channel.create_invite(max_age = 300)
members = len(ctx.message.author.voice.channel.members)
members1 = ctx.message.author.voice.channel.members
max_ = channel.user_limit
if max_ == 0:
max_ = 'None'
if max_ == 'None':
p = f'{members}, No Limit'
else:
p = f"{members} out of {max_}"
em = Embed(color=discord.Color.gold())
em.add_field(name='LFG Request', value=f"**{ctx.author.mention} is looking for a group in voice channel `#{channel}`**:\n\n**Game: {game}**\n\n**Extra Info:** {extra}\n\n**Connected Users:**{(members1)} ({p})\n\n**VC Invite: [Click here to join]({link})**")
em.set_footer(text=f'Type !lfg (message) to create this embed | This LFG request was made by {ctx.author.name}')
await ctx.send(embed=em)
Sorry if it's a bit hard to read, thanks in advance! :D (Btw I'm trying to display the names of the users in the vc in the "Connected Users" section of the embed)
Edit: I figured it out, for those who want the code, here it is:
members = len(ctx.message.author.voice.channel.members)
count = 0
members1 = ""
for _ in range(int(members)):
members1 += f"{ctx.message.author.voice.channel.members[count].mention}"
count += 1
try adding .name to the member. This should get the name from the member.

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"

EOL while scanning string literal, Unknown Emoji

Command raised an exception: HTTP Exception: 400 Bad Request (error code: 10014): Unknown Emoji and EOL while scanning string literal are the 2 errors I have having while trying to add a reaction to an embed msg with python (discord.py)
Here is the full code, the problem is around the exclamation mark
#client.command()
async def ask(ctx, *, question=None):
try:
page = urllib.request.urlopen(f'http://askdiscord.netlify.app/b/{ctx.message.author.id}.txt')
if page.read():
embed = discord.Embed(color=0xFF5555, title="Error", description="You are banned from using AskDiscord!")
await ctx.send(embed=embed, content=None)
return
except urllib.error.HTTPError:
pass
if question:
channel = client.get_channel(780111762418565121)
embed = discord.Embed(color=0x7289DA, title=question, description=f"""
Question asked by {ctx.message.author} ({ctx.message.author.id}). If you think this question violates our rules, click ❗️ below this message to report it
""")
embed.set_footer(text=f"{ctx.message.author.id}")
message = await channel.send(content=None, embed=embed)
for emoji in ('❗️'):
await message.add_reaction(emoji)
for emoji in ('🗑'):
await message.add_reaction(emoji)
embed = discord.Embed(color=0x55FF55, title="Question asked", description="Your question has been send! You can view in the answer channel in the [AskDiscord server](https://discord.gg/KwUmPHKmwq)")
await ctx.send(content=None, embed=embed)
else:
embed = discord.Embed(title="Error", description=f"Please make sure you ask a question...", color=0xFF5555)
await ctx.send(content=None, embed=embed)
Tuple need to have a , at the end if there is only one element in it else its considered as a string in your case change ('❗️') to ('❗️',)

How to get how many messages has been sent by a user

How to get how many messages have been sent by a user, I tried doing it myself but it didn't work out for me can anyone help me.
This is what I came up with:
#client.command(aliases =["m"])
async def messages(ctx, Discord.user=User):
counter = 0
async for message in channel.history():
if message.author == client.user:
counter += 1
await ctx.send(f'{ctx.author.mention} sent {counter} messages.')
Your user parameter is not valid. = indicates default, what you want to use are type hints which are indicated with a :. This is the correct way to pass your user parameter: user: discord.Member.
#client.command(aliases=["m"])
async def messages(ctx, user: discord.Member):
channel = ctx.message.channel
counter = 0
async for message in channel.history():
if message.author == user:
counter += 1
await ctx.send(f'{ctx.author.mention} sent {counter} messages.')

Resources