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
Related
I just switched to Discord.py v2 after switching using nextcord for 1 or 2 months.
Im having a issue where no commands work
like no commands at all
i changed everything from "nextcord" to "discord" and even changed the setups in the cogs to the new async versions
events work, but commands themselves dont
i tried everything i knew but still didnt fix it
i tried looking in the discord doc but still couldnt find a soloution
my current code:
import discord
from discord.ext import commands
from discord.ext.commands.core import has_permissions
import asyncio
import os
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='+', intents=intents)
##COGS
#bot.event
async def on_ready():
await asyncio.sleep(1)
print(f'We have logged in as {bot.user}')
await bot.change_presence(activity=discord.Game(name="in the Mountains"))
#bot.command()
#has_permissions(administrator = True)
async def load(ctx, arg, extension):
if ctx.author.id == 498839148904579092:
bot.load_extension(f"{arg}.{extension}")
embed = discord.Embed(description=f"{extension} module loaded!", colour=discord.Colour.dark_green())
await ctx.send(embed = embed)
print(f"{extension} loaded")
#bot.command()
#has_permissions(administrator = True)
async def unload(ctx, arg, extension):
if ctx.author.id == 498839148904579092:
bot.unload_extension(f"{arg}.{extension}")
embed = discord.Embed(description=f"{extension} module unloaded!", colour=discord.Colour.dark_green())
await ctx.send(embed = embed)
print(f"{extension} unloaded")
#bot.command()
#has_permissions(administrator = True)
async def reload(ctx, arg, extension):
if ctx.author.id == 498839148904579092:
bot.reload_extension(f"{arg}.{extension}")
embed = discord.Embed(description=f"{extension} module reloaded!", colour=discord.Colour.dark_green())
await ctx.send(embed = embed)
print(f"{extension} reloaded")
#load.error
async def alreadyloaded(ctx, error):
if isinstance(error, commands.CommandInvokeError):
embed = discord.Embed(colour=discord.Colour.dark_red())
embed.set_author(icon_url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png", name="Command Invoke Error! [LOAD]")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png")
embed.add_field(name="commands.CommandInvokeError", value=error, inline=True)
embed.add_field(name="Maybe...", value="The Extension is Non-Exsistant or cannot be Loaded", inline=True)
embed.set_footer(text="get a list of Modules with [+modules]!")
await ctx.send(embed = embed, delete_after = 10)
elif isinstance(error, commands.MissingPermissions):
await ctx.message.delete()
await ctx.send(f"{ctx.author.mention}, that Command is Admin only!", delete_after = 3)
return
#unload.error
async def alreadyunloaded(ctx, error):
if isinstance(error, commands.CommandInvokeError):
embed = discord.Embed(colour=discord.Colour.dark_red())
embed.set_author(icon_url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png", name="Command Invoke Error! [UNLOAD]")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/883349890921545748/927946906271887430/W0019f8UlvqD3dDC5.png")
embed.add_field(name="commands.CommandInvokeError", value=error, inline=True)
embed.add_field(name="Maybe...", value="The Extension is Non-Exsistant or cannot be Unloaded", inline=True)
embed.set_footer(text="get a list of Modules with [+modules]!")
await ctx.send(embed = embed, delete_after = 10)
return
elif isinstance(error, commands.MissingPermissions):
await ctx.message.delete()
await ctx.send(f"{ctx.author.mention}, that Command is Admin only!", delete_after = 3)
return
#bot.command()
async def online(ctx):
print("1")
await ctx.channel.send("online")
print("hello")
async def main():
async with bot:
#await load_extensions()
await bot.start("bot auth code")
asyncio.run(main())
Discord.py v2.0 has migrated to api v10, and with this has come the introduction of Intents.message_content, which is disabled by default.
This means that you will need to explicitly enable it in code and in the panel, at https://discord.com/developers/applications.
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='+', intents=intents)
This question already has an answer here:
Discord.py Banning members not in my server
(1 answer)
Closed 11 months ago.
When I try to use the command it says "user is a required argument"
#commands.command(aliases=['hban'])
#commands.has_permissions(ban_members=True)
#commands.cooldown(1, 3, BucketType.user)
async def hackban(self, ctx, user: discord.User):
if user in ctx.guild.members:
embed = discord.Embed(description=":oxmark: "+f"Unsuccessful, the user is in this guild. [-help ban]", color=discord.Color.orange())
await ctx.reply(embed=embed, mention_author=False)
else:
await ctx.guild.ban(user)
embed = discord.Embed(title=":ocheckmark: "+f"Successfully hack banned {user.name}", color=discord.Color.orange())
await ctx.reply(embed=embed, mention_author=False)
#client.command()
#check(check_if_user_has_premium)
#commands.has_permissions(ban_members=True)
async def hackban(ctx, user: discord.User = None):
guild = ctx.guild
if user == None:
await ctx.send("Please enter a member to ban")
return()
else:
await guild.ban(user)
embed = discord.Embed(title=":ocheckmark: "+f"Successfully hack banned {user.name}", color=discord.Color.orange())
await ctx.reply(embed=embed, mention_author=False)
Works
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)
I want my bot when someone says something the bot to say the author's name without hashtag and also the content of the message.
But this embedVar = discord.Embed(title='The', (message.author), 'posted', description=message.content, color=0x0000FF) doesn't work.
Can you help me please
#client.event
async def on_message(message):
if str(message.channel) in ['general']:
if not message.author == client.user:
embedVar = discord.Embed(title='The', (message.author), 'posted', description=message.content, color=0x0000FF)
embedVar.set_author(name=message.author)
embedVar.set_footer(text='Facebook-')
await message.delete()
await message.channel.send(embed=embedVar)```
You can do:
async def on_message(message):
if not message.author == client.user:
await message.channel.send(message.content)
await client.delete_message(message)
I'm setting up a discord bot, and I want to have the bot send a confirmation or error message after the commands "ban" and "kick", can anyone help?
I have tried creating another separate command with the same arguments, except just having it send the expected message.
#client.event
async def on_ready():
print('Bot is ready!')
#client.event
async def on_member_join(ctx, member):
print(f'{member} has joined {ctx.guild.name}.')
#client.event
async def on_member_remove(ctx, member):
print(f'{member} has left {ctx.guild.name}.')
#client.event
async def on_member_join(member):
role = discord.utils.get(member.server.roles, name="Member")
await client.add_roles(member, role)
#client.command()
async def ping(ctx):
await ctx.send(f'Pong! :ping_pong: **{round(client.latency * 1000)}ms** ')
#client.command()
async def purge(ctx, amount):
await ctx.channel.purge(limit=amount)
await ctx.send(f'{member.display_name} has been kicked.')
#client.command()
async def kick(ctx, member : discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'{member.display_name} has been kicked.'')
#client.command()
async def ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'The Ban Hammer has Spoken! {member.display_name} has been banned!')
#client.command()
async def pardon(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.banned_users
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {member.display_name}')
In actuality, I think it would be great, because they clash with each other and probably will send a message, but it went wrong.
At the end of the kick command delete that last '. And also do {member.name} or {member}