So far what I've got is this:
#Bot.command()
async def unpin(ctx, amount = None):
await ctx.message.delete()
channel = str(ctx.channel)
x = 0
amount = int(amount)
if amount == 0:
await ctx.send("How many messages do you want to unpin, max is 50.")
else:
pins = await channel.pins()
for message in pins:
await message.unpin()
x+=1
x1 = str(x)
await ctx.send(f"Unpinned {x} messages from #{channel}")
My problem is at pins = await channel.pins() - I don't know how to access the pinned messages in the channel. If someone could help that would be greatly appreciated.
The problem is this line:
channel = str(ctx.channel)
This line returns the string value of the channel object.
You use it in the following code:
pins = await channel.pins() # i.e. get string.pins()
Because strings dont have the pins() function. It throws an error, or wont function correctly.
In order to fix this you should assign the ctx.channel object to the channel variable. This way we dont convert it to a string by using str().
Now we have a channel object, we can correctly use the pins() function with, and do what you wanted it to do.
#Bot.command()
async def unpin(ctx, amount = None):
await ctx.message.delete()
channel = ctx.channel
x = 0
amount = int(amount)
if amount == 0:
await ctx.send("How many messages do you want to unpin, max is 50.")
else:
pins = await channel.pins()
for message in pins:
await message.unpin()
x+=1
x1 = str(x)
await ctx.send(f"Unpinned {x} messages from #{channel}")
You returned the ctx.channel in to a string. That's why you can't access the pins. If you change the line channel = str(ctx.channel) to channel = ctx.channel, your problem will be solved.
And also, you should change the parameter amount=None as amount=0.
Related
I have a command which allows people to react to a message to enter into a "battle". Then with another command, 2 people are chosen. This is my code:
#client.command(aliases=['start', 'g'])
async def startbattle(ctx):
msg = await ctx.send("React to enter battle")
await msg.add_reaction("🎉")
await asyncio.sleep(10000000000000000)
message = await ctx.fetch_message(msg.id)
for reaction in message.reactions:
if str(reaction.emoji) == "🎉":
users = await reaction.users().flatten()
if len(users) == 1:
return await msg.edit(embed=discord.Embed(title="Nobody has won the giveaway."))
try:
user1 = random.choice(users)
user2 = random.choice(users)
except ValueError:
return await ctx.send("not enough participants")
await ctx.send(f'Battle will be against {user1} and {user2}')
#client.command()
async def pick(ctx):
async for message in ctx.channel.history(limit=100, oldest_first=False):
if message.author.id == client.user.id and message.embeds:
reroll = await ctx.fetch_message(message.id)
users = await reroll.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner1 = random.choice(users)
winner2 = random.choice(users)
await ctx.send(f"The battle will be against {winner1.mention} and {winner2.mention}")
break
else:
await ctx.send("No giveaways going on in this channel.")
This is the error which I get while using the "pick" command,
users = await reroll.reactions[0].users().flatten()
IndexError: list index out of range
the error is in the for loop as it gets the msg and the msg doesnt have any reaction so it there is no list so list is out of range to fix this u have to add try and except there so it skips the msg with no reactions.
code :
#client.command()
async def pick(ctx):
async for message in ctx.channel.history(limit=100, oldest_first=False):
if message.author.id == client.user.id and message.embeds:
reroll = await ctx.fetch_message(message.id)
try:
users = await reroll.reactions[0].users().flatten()
except:
break
users.pop(users.index(client.user))
winner1 = random.choice(users)
winner2 = random.choice(users)
await ctx.send(f"The battle will be against {winner1.mention} and {winner2.mention}")
return # <--- was the break
else:
await ctx.send("No giveaways going on in this channel.")
and a suggestion dont add break in the if statement as it will continuously check for msg if already it got one
How do I remove mark down in discord.py?
I was making an eval command but I realized that sending it with markdown eg. '```py print("example code")```', breaks it.
I want to make it easier for me and the other admin/mod to use it for debugging purposes in my bot.
#client.command()
async def eval(ctx, *, code):
out, err = io.StringIO(), io.StringIO()
sys.stdout = out
sys.stderr = err
await ctx.channel.trigger_typing()
await aexec(code)
results = out.getvalue()
errors = err.getvalue()
await ctx.send(embed = discord.Embed(title = "Eval", description=f"Output Is \n```bash\n{results}```"))
await ctx.send(embed = discord.Embed(title = "Code", description=f"Input Is \n```py\n{code}```"))
the above code is what I've tried so far..
I've been playing with your code for the past hours, I wanted to figured it out :P
This is the only way i could access the code when there was markdown in the command input.
#client.command()
async def eval(ctx, *, code):
raw = f'{ctx.message.content}'[12:-3] # Get rid of markdown + py and last 3 ```
#Might want to add if statements in case the input doesn't include py / something else.
print (raw) # Testing purpose
out, err = io.StringIO(), io.StringIO()
sys.stdout = out
sys.stderr = err
await ctx.channel.trigger_typing()
exec(raw) # no need for await
results = out.getvalue()
errors = err.getvalue()
await ctx.send(embed = discord.Embed(title = "Eval", description=f"Output Is \n```bash\n{results}```"))
await ctx.send(embed = discord.Embed(title = "Code", description=f"Input Is \n```py\n{raw}```"))
await ctx.send(embed = discord.Embed(title = "Errors", description=f"Errors are \n```py\n{errors}```")) #Added this output to see errors
I have this
async def deletechar(ctx):
em = discord.Embed(title = f"Are you sure you want to erase your character?",color = discord.Color.red())
em.add_field(name = "Yes, delete it please",value = "Y")
em.add_field(name = "Nevermind",value = "N")
await ctx.send(embed = em)
response = await client.wait_for_message('message')
if response.content == 'Y' and ctx.author == response.author:
await ctx.send("Successfully Deleted Character")
elif response.content == 'N' and ctx.author == response.author:
await ctx.send("Not Deleted")
this may be poorly written, though it works it's just that if a message is not by the author it'll kick out of the function. I want to await a response by the author within the context while ignoring other messages but not using too much CPU while doing it. Any suggestions?
I don't want it to hang in this function because I want it to be able to process messages from other users while it waits for this one
Using a check
response = await client.wait_for_message('message', check=lambda m: m.author.id == ctx.author.id)
How do I have a static timer where the user can just say ??abc and the bot does a countdown from lets say 300s I want the bot to edit the same mssg and not send multiple mssgs thanks
import asyncio
#bot.command
async def countdown(ctx, sec:int):
msg = await ctx.send(f'{sec}s')
for second in range(sec, 0, -1):
await msg.edit(f'{second}s')
await asyncio.sleep(1)
#client.command(help="Countdown from specified seconds!")
async def countdown(ctx, t: int):
msg = await ctx.send(f'Counting down from {t}!')
while t > 0:
t -=1
await msg.edit(content=f'{t} seconds remaining')
await asyncio.sleep(1)
await ctx.send(f'Countdown end reached! {ctx.message.author.mention}')
Do understand what all this means don't want to spoon-feed anybody ;).
GL
Kind of new to Discordpy moderation commands and would like to know why this code doesn't work,
as I get no errors while trying to run it. it's supposed to temp mute a user for a specific amount of time depending on the unit and if no muted role was created it, creates one.
#commands.command()
async def mute(self , ctx, user : discord.Member, duration = 0,*, unit = None):
guild = ctx.guild
for role in guild.roles:
if role.name =="Muted":
await member.add_roles(role)
await ctx.send("{} Has been muted by {} for {duration}{unit} " .format(member.mention,ctx.author.mention))
return
overwrite = discord.PermissionsOverwrite(send_messages=False)
newRole = await guild.create_role(name="Muted")
for channel in guild.text_channels:
await channel.set_permissions(newRole,overwrite=overwrite)
await member.add_roles(newRole)
await ctx.send("{} Has been muted by {} for {duration}{unit} " .format(member.mention,ctx.author.mention))
if unit == "s":
wait = 1 * duration
await asyncio.sleep(wait)
elif unit == "m":
wait = 60 * duration
await asyncio.sleep(wait)
await user.remove_roles(roleobject)
await ctx.send(f":white_check_mark: {user} was unmuted")
```
All the code after your return statement is useless, as it will never be executed. Maybe you indented that part too far.
Make a list of the role names and check it through that instead of having a big loop
rolenames = {role.name: role for role in guild.roles}
if 'Muted' not in rolenames.keys():
# Make the new role
role = new_role_you_created
else:
role = rolenames['Muted']
# Add the role to the user
await member.add_roles(role)
All the code written after a return statement will NEVER be executed, so the last part of your code is unreachable.
You can use discord.utils.get to get a role based on the name, insted of looping over every role in the guild.
Then, if there isn't any role under that name, you create a new one (I'm guessing that's the behaviour you're looking for)
#commands.command()
async def mute(self , ctx, member : discord.Member, duration: int = 0, unit: str = None):
guild = ctx.guild
role = discord.utils.get(guild.roles, name="Muted")
if role is None:
overwrite = discord.PermissionsOverwrite(send_messages=False)
role = await guild.create_role(name="Muted")
for channel in guild.text_channels:
await channel.set_permissions(role, overwrite=overwrite)
await member.add_roles(role)
await ctx.send(f"{member.mention} Has been muted by {ctx.author.mention} for {duration}{unit} ")
if unit == "s":
wait = 1 * duration
await asyncio.sleep(wait)
elif unit == "m":
wait = 60 * duration
await asyncio.sleep(wait)
await member.remove_roles(role)
await ctx.send(f":white_check_mark: {member} was unmuted")
You should consider checking if the unit is valid before executing the command, because wait will not be defined if unit is not s or m, causing the command to raise an error, and the user will be muted forever.
Also, using asyncio.sleep in a tempmute command is not recommended. If the bot crashes or is turns off, the user will never be unmuted. Instead, store the tempmutes in a database and check them every X time.
As the others already stated, the code after the return statement won't be executed. So basically the whole command ends if there is a role called "Muted". Also you seem to create a new role called "Muted" if there is a role called Muted in which you disable sending messages. Also I am not sure, if you can't just set the global role permissions to send_messages=True
Do you maybe mean something like this?
#commands.command()
async def mute(self , ctx, user : discord.Member, duration = 0,*, unit = None):
guild = ctx.guild
muted_role = None
for role in guild.roles:
if role.name =="Muted":
muted_role = role
if muted_role == None:
overwrite = discord.PermissionsOverwrite(send_messages=False)
muted_role = await guild.create_role(name="Muted")
for channel in guild.text_channels:
await channel.set_permissions(muted_role,overwrite=overwrite)
await member.add_roles(muted_role)
await ctx.send("{} Has been muted by {} for {duration}{unit} " .format(member.mention,ctx.author.mention))
if unit == "s":
wait = 1 * duration
await asyncio.sleep(wait)
elif unit == "m":
wait = 60 * duration
await asyncio.sleep(wait)
await user.remove_roles(roleobject)
await ctx.send(f":white_check_mark: {user} was unmuted")
I hope I could help!