Discord Python Rewrite - help command error (custom) - discord

So, I've made a help that works, but I want it to say something if the category that the user entered is invalid. I got a working code without the error if the category is invalid. The code:
#client.command()
async def help(ctx, *, category = None):
if category is not None:
if category == 'mod' or 'moderation' or 'Mod' or 'Moderation':
modhelpembed = discord.Embed(
title="Moderation Help",
timestamp=datetime.datetime.now(),
colour=discord.Color.green()
)
modhelpembed.add_field(name='kick', value="Kicks a member from the server", inline=False)
modhelpembed.add_field(name='ban', value='bans a member from the server', inline=False)
modhelpembed.add_field(name='unban', value='unbans a member from the server', inline=False)
modhelpembed.add_field(name="nuke", value="Nukes a channel :>", inline=False)
modhelpembed.add_field(name='mute', value="Mute a member", inline=False)
modhelpembed.add_field(name="purge", value='purges (deletes) a certain number of messages', inline=False)
await ctx.send(f'{ctx.author.mention}')
await ctx.send(embed=modhelpembed)
elif category == 'fun' or 'Fun':
funembed = discord.Embed(
title="Fun Help",
timestamp=datetime.datetime.now(),
colour=discord.Color.green()
)
funembed.add_field(name='meme', value='shows a meme from r/memes', inline=False)
funembed.add_field(name='waifu', value='shows a waifu (pic or link) from r/waifu', inline=False)
funembed.add_field(name='anime', value='shows a anime (image or link) from r/anime', inline=False)
funembed.add_field(name='spotify', value='Tells you the targeted user listening on', inline=False)
funembed.add_field(name="song", value="Tells you the whats the targeted user listening in Spotify", inline=False)
funembed.add_field(name="album", value="Tells you whats the targeted user album", inline=False)
funembed.add_field(name="timer", value="Sets a Timer for you.", inline=False)
await ctx.send(f'{ctx.author.mention}')
await ctx.send(embed=funembed)
else:
nonembed = discord.Embed(
title="Help list",
timestamp=datetime.datetime.now(),
colour=discord.Color.green(),
description='Category:\nmod\nfun'
)
await ctx.send(f'{ctx.author.mention}')
await ctx.send(embed=nonembed)
It works, but when i tried inputing a invalid category it sends Moderation.

You erros comes from your second if statement. You just have to replace it with either:
if category == ('mod' or 'moderation' or 'Mod' or 'Moderation'):
if category in ['mod', 'moderation', 'Mod', 'Moderation']:
Here's why your statement is triggered when you input an invalid category:
An empty string returns False (eg. "") and a string returns True (eg. "TEST").
If you don't put brackets, it will separate each or as a condition (if category == 'mod' / if 'mod' / if 'moderation' / if 'Mod' / if 'Moderation').
Since a non empty string returns True, when you input an invalid category, your second if statement gets triggered and it gives you the Moderation help message.
You can also use commands.Command attributes to make some refactoring:
#client.command(description='Say hi to the bot')
async def hello(ctx):
await ctx.send(f'Hi {ctx.author.mention}')
#client.command(description='Test command')
async def test(ctx):
await ctx.send('TEST')
#client.command()
async def help(ctx, *, category = None):
categories = {
'fun': ['hello',],
'testing': ['test',],
}
if category is None:
desc = '\n'.join(categories.keys())
embed = discord.Embed(
title="Help list",
timestamp=datetime.datetime.now(),
colour=discord.Color.green(),
description=f'Categories:\n{desc}'
)
else:
category = category.lower()
if not category in categories.keys():
await ctx.send('Category name is invalid!')
return
embed = discord.Embed(
title=f"{category.capitalize()} Help",
timestamp=datetime.datetime.now(),
colour=discord.Color.green()
)
for cmd in categories[category]:
cmd = client.get_command(cmd)
embed.add_field(name=cmd.name, value=cmd.description)
await ctx.send(ctx.author.mention, embed=embed)

Related

I wanted to write a mute command for a bot in the discord

I wanted to write a mute command for a bot in the discord. The command does not work. Here's the code and the error
#bot.tree.command(name="mute", description="Мьют участника")
#app_commands.checks.has_permissions( administrator = True )
async def mute( interaction: discord.Interaction, member: discord.Member,reason: str = None ):
await interaction.response.defer( thinking = True )
await interaction.channel.purge( limit = 1 )
mute_role = discord.utils.get ( interaction.guild.roles, id = '1061014280922746887', name = 'muted' )
await member.add_roles( mute_role )
await interaction.channel.send( embed = discord.Embed(
title="Участник успешно замьючен",
description= ( f"{member.mention} **был замьючен модератором** {interaction.user.mention}! "),
color=discord.Color.from_str("#C3F")
))
error
I was trying to recreate the role of mute. Change interaction.guild.roles to interaction.message.guild.roles
ID's are ints, not strings. You're passing a string to utils.get, so nothing is found and mute_role is None, as your error message is telling you.
discord.utils.get(interaction.guild.roles,id='1061014280922746887',name='muted')
# ^^^^^^^^^^^^^^^^^^^^^ string
Pass the ID as an int instead.
Docs for Role.id: https://discordpy.readthedocs.io/en/stable/api.html#discord.Role.id
Type:
int

EMBED SYSTEM [IDLE PYTHON]

So i have an embed system working in the below code:
#client.event
async def on_message(message):
if message.content.startswith('!emsay'):
embedVar = discord.Embed(title="Title", description="desc", color=0x00ff00)
await message.channel.send(embed=embedVar)
My problem is yes when i do !emsay it dose put the embed in but is there a way that after i put !emsay i can change the title and description without going into python to type out a whole new embed?
This is what i currently have:(im fine with this)Discord screenshot of embed I would like to make it so after i use the command !emsay i can enter a title and description through discord.
Thanks : )
sorry if iv overcomplicated this
Try this:
#client.event
async def on_message(message):
if message.content.startswith('!emsay'):
count = 0
def check(author):
def inner_check(message):
if message.author != author:
return False
return inner_check
while count < 2:
if (count == 0):
await message.channel.send("Write a title for embed")
title = await client.wait_for("message", check=check, timeout=30)
elif (count == 1):
await message.channel.send("Write a desc for embed")
desc = await client.wait_for("message", check=check, timeout=30)
count += 1
embedVar = discord.Embed(title = title.content, description = desc.content, color = 0x00ff00)
await message.channel.send(embed=embedVar)
If you don't write title and desc, you can get a TimeoutError and you can change timeout if you want.
How to use?

Reroll Giveaway command not responding when command run?

I am trying to make a discord giveaway reroll command.
The problem is that when the command is run it is not responding/rerolling the giveaway.
I've looked on multiple sites with the same command and all of them did not work/have a fix for this.
I also tried without the embeds to see if that was the problem with the code.
Below is the reroll command code -
(if the giveaway command code is needed I can provide it)
#client.command()
#commands.has_permissions(kick_members=True)
async def reroll(ctx, channel : discord.TextChannel, id_ : int):
try:
new_msg = await channel.fetch_message(id_)
except:
embed = discord.Embed(title="Command Error ⛔ - GameBot", description=f"**The Id Of A Channel Was Entered Incorrectly!** 🎉", color=0x992d22)
await ctx.send(embed=embed)
return
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
embed = discord.Embed(title="Giveaways 🎉 - GameBot", description=f"**Giveaway Has Been Rerolled!** \n \n**Winner -** \n`{winner.mention}`", color=0xe74c3c)
await ctx.send(embed=embed)
Below is the giveaway command code -
#client.command()
#commands.has_permissions(kick_members=True)
async def giveaway(ctx):
embed = discord.Embed(title="Giveaway Setup 🎉 - GameBot", description=f'**{ctx.author.mention} Giveaway Setup Is Now Starting... Please Answer These Questions Within 30 Seconds!**', color=0xe74c3c)
await ctx.send(embed=embed)
questions = ["**What Channel Should The Giveaway Be Hosted In?** `EX : #general` 🎉",
"**What Is The Duration Of The Giveaway?** `EX : S/M/H/D` 🎉",
"**What Is The Giveaway Prize?** `EX : Gift Card` 🎉"]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await client.wait_for('message', timeout=30.0, check=check)
except asyncio.TimeoutError:
embed = discord.Embed(title="Command Error ⛔ - GameBot", description=f"**Please Answer All Of The Questions In Time... Be Prepared!** 🎉", color=0x992d22)
await ctx.send(embed=embed)
else:
answers.append(msg.content)
try:
c_id = int(answers[0][2:-1])
except:
embed = discord.Embed(title="Command Error ⛔ - GameBot", description=f"**Please Provide A Valid Channel For Me To Host The Giveaway In!** `EX : #general` 🎉", color=0x992d22)
await ctx.send(embed=embed)
return
channel = client.get_channel(c_id)
time = convert(answers[1])
if time == -1:
embed = discord.Embed(title="Command Error ⛔ - GameBot", description=f"**The Time Constraint You Answered With Was Not A Valid Unit!** `EX : S/M/H/D` 🎉", color=0x992d22)
await ctx.send(embed=embed)
return
elif time == -2:
embed = discord.Embed(title="Command Error ⛔ - GameBot", description=f"**The Time Must Include An Integer!** `EX : 1S, 1M, 1H, 1D` 🎉", color=0x992d22)
await ctx.send(embed=embed)
return
prize = answers[2]
embed = discord.Embed(title="Giveaway Setup 🎉 - GameBot", description=f'**Giveaway Channel -** \n`{channel.mention}` \n**Duration -** \n`{answers[1]}`', color=0xe74c3c)
await ctx.send(embed=embed)
givembed = discord.Embed(title="Giveaways 🎉 - GameBot", description=f'**Giveaway Prize/Description -** \n`{prize}`', color=0x2ecc71)
givembed.add_field(name = "**Host -**", value=ctx.author.mention)
givembed.set_footer(text = f"Ending {answers[1]} From Now! 🎉")
my_msg = await channel.send(embed=givembed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(time)
new_msg = await channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
embed = discord.Embed(title="Giveaways 🎉 - GameBot", description=f"**Giveaway Has Ended!** \n \n**Winner -** \n`{winner.mention}` \n**Prize -** \n`{prize}`", color=0xe74c3c)
await ctx.send(embed=embed)
Almost everything about the code is correct. However I guess you are requesting the users in a wrong/not working way. You can try to request the users in another way, this seems to be the source where the error comes from.
Try out the following:
users = [u for u in await new_msg.reactions[0].users().flatten() if u != client.user]
winner = random.choice(users)
The full code would be:
#client.command()
#commands.has_permissions(kick_members=True)
async def giveaway(ctx):
# Giveaway code
#client.command()
#commands.has_permissions(kick_members=True)
async def reroll(ctx, channel: discord.TextChannel, id_: int):
try:
new_msg = await channel.fetch_message(id_)
except:
embed = discord.Embed(title="Command Error ⛔ - GameBot",
description=f"**The Id Of A Channel Was Entered Incorrectly!** 🎉", color=0x992d22)
await ctx.send(embed=embed)
return
user_list = [u for u in await new_msg.reactions[0].users().flatten() if u != client.user]
winner = random.choice(user_list)
embed = discord.Embed(title="Giveaways 🎉 - GameBot",
description=f"**Giveaway Has Been Rerolled!** \n \n**Winner -** \n`{winner.mention}`",
color=0xe74c3c)
await ctx.send(embed=embed)

Trying to ask user confirmation for discord.py bot command, but doing so neglects the "if and elif block" entirely

I have imported everything needed for the command.
So, the issue here is, in the condition for executing the command (checking if the user said yes/no or something weird which terminates the command)
#commands.command()
#commands.has_permissions(manage_channels=True)
async def nuke(self, ctx,*, channel = None, reason = None):
if reason is None:
reason = "No reason was specified!"
if channel is None:
channel = ctx.channel
p = time.strftime(f'Today at %H:%M %p')
embei = discord.Embed(color=0xa3a3ff, title = ":warning: ALERT ALERT ALERT :warning: ", description=f"{ctx.author.mention} Are you sure you want to delete {ctx.channel.mention}? y/n")
await ctx.send(embed=embei)
msg = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id)
if msg.content.lower in ("y", "yes"):
embedis = discord.Embed(color=0xa3a3ff, title=f"Channel ({ctx.channel.name}) has been nuked :boom:", description=f"Nuked by: {ctx.author.name}#{ctx.author.discriminator} \n **Reason:** {reason}")
embedis.set_image(url = "https://66.media.tumblr.com/23dad7011515a9c21647fefb07e1c0e0/dd0cbd9bb94e2a45-1e/s640x960/a02fc34abff6953c59adafc190de6e5276969175.gif")
embedis.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.channel.delete(reason=reason)
channel = await ctx.channel.clone()
await channel.send(embed=embedis)
elif msg.content.lower in ("n", "no"):
embegs = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = f"{ctx.channel.mention} was not nuked!")
embegs.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embegs)
else:
embers = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = "No proper response was given, action was terminated")
embers.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embers)
The part with the issue
msg = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id)
if msg.content.lower in ("y", "yes"):
embedis = discord.Embed(color=0xa3a3ff, title=f"Channel ({ctx.channel.name}) has been nuked :boom:", description=f"Nuked by: {ctx.author.name}#{ctx.author.discriminator} \n **Reason:** {reason}")
embedis.set_image(url = "https://66.media.tumblr.com/23dad7011515a9c21647fefb07e1c0e0/dd0cbd9bb94e2a45-1e/s640x960/a02fc34abff6953c59adafc190de6e5276969175.gif")
embedis.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.channel.delete(reason=reason)
channel = await ctx.channel.clone()
await channel.send(embed=embedis)
elif msg.content.lower in ("n", "no"):
embegs = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = f"{ctx.channel.mention} was not nuked!")
embegs.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embegs)
else:
embers = discord.Embed(color=0xa3a3ff, title = ":red_circle: NOTICE :red_circle:", description = "No proper response was given, action was terminated")
embers.set_footer(text=f"Rylie - Thanks for using this bot! - {p} - {self.client.version}", icon_url = str(self.client.user.avatar_url))
await ctx.send(embed=embers)
when I execute the command, it does ask me for the confirmation as expected, however, the reply here doesn't matter as it always executes the else statement. I thought the issue was with indentation and so I tried fixing that but that too didn't work. Does anyone know about the issue here I might be facing?
Extra: Before Adding user confirmation, the code was working absolutely fine! (It created a clone of the channel, sent the embed there saying it nuked the original channel, and deleted the original channel)
For this question of mine, the string.lower() is a method which I need to call, which was mentioned to me by Lukasz. I was using the string.lower() in the wrong way.
To Fix the problem I had, I declared two lists a and b
a=["y", "yes"]
b = ["n", "no"]
and changed
if msg.content.lower in ("y", "yes"):
elif msg.content.lower in ("n", "no"):
to
if msg.content in a:
elif msg.content in b:
and the issue was fixed.

Discord Python Rewrite - Mute "Role not found"

i was making a mute command, i want it to create the role if the role is not found. Here's my code
#client.command()
async def mute(ctx, member: discord.Member , time, *, reason):
guild = ctx.guild
for role in guild.roles:
if role.name == 'muted' or 'Muted':
await member.add_roles(role)
perms = channel.overwrites_for(member)
perms.send_messages=False
await channel.set_permissions(member, overwrite=perms, reason="Muted!")
mutedembed = discord.Embed(
title=f"Muted {member.name}",
description="For the reason {}".format(reason),
timestamp=datetime.datetime.now()
)
await ctx.send(embed=mutembed)
else:
perms = discord.Permissions(send_messages=False, read_messages=True)
newRole = await guild.create_role(name="Muted", permissions=perms)
await member.add_roles(newRole)
mutedembed = discord.Embed(
title=f"Muted {member.name}",
description="For the reason {}".format(reason),
timestamp=datetime.datetime.now()
)
await ctx.send(embed=mutembed)
await asyncio.sleep(to_seconds(time))
await member.role_remove(newRole)
return
i want it to make the role if it's not on the role list, how to do that?
Use discord.utils.get(guild.roles, name='Muted') to find if there is a muted role in the guild, and run your "else" case if not

Resources