Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23276

Discord.Py Cogs And Slash Command

$
0
0

I'm trying to make a bot with moderation cog file. Firstly I added ban and unban but it is not working.my files look like. I think files are in correct positions.

files

Main command:

import discordfrom discord.ext import commandsfrom .cogs import banintents = discord.Intents.default()intents.members = True  # Required for on_member_join listenerclient = commands.Bot(intents=intents)@client.eventasync def on_ready():    print("Move Move Move")def setup(bot):    ban(bot)setup(client)client.run("token")

ban cog:

import discordfrom discord import interactionsfrom discord.ext import commandsclient = commands.Bot(command_prefix=".", intents=discord.Intents.all())class ban(commands.Cog):  def __init__(self, bot):    self.bot = bot  @client.tree.command(name="ban", description="Bans a member from the server.")  @commands.has_permissions(ban_members=True)  async def ban(self, ctx, member: discord.Member, reason=None):"""Bans a member from the server.    Args:        ctx (discord.ext.commands.Context): The command context.        member (discord.Member): The member to ban.        reason (str, optional): The reason for banning the member. Defaults to None."""    if member == ctx.author:      await ctx.respond("You can't ban yourself!")      return    if member == ctx.guild.owner:      await ctx.respond("I can't ban the server owner!")      return    if member.top_role >= ctx.author.top_role:      await ctx.respond("You can't ban someone with a higher role than you!")      return    try:      await member.ban(reason=reason)      await ctx.respond(f"{member} has been banned!")    except discord.HTTPException as e:      await ctx.respond(f"Failed to ban {member}. Error: {e}")  @client.tree.command(name="unban", description="Unbans a member from the server.")  @commands.has_permissions(ban_members=True)  # Requires "Ban Members" permission  async def unban(self, ctx, user: discord.User, *, reason=None):"""Unbans a member from the server.    Args:        ctx (discord.ext.commands.Context): The command context.        user (discord.User): The user to unban (use their ID).        reason (str, optional): The reason for unbanning the member. Defaults to None."""    try:      guild = ctx.guild      banned_users = await guild.bans()      member = [ban for ban in banned_users if ban.user == user]      if not member:        await ctx.respond(f"{user} is not banned from this server.")        return      await guild.unban(user, reason=reason)      await ctx.respond(f"{user} has been unbanned!")    except discord.HTTPException as e:      await ctx.respond(f"Failed to unban {user}. Error: {e}")def setup(bot):  bot.add_cog(ban(bot))

error:

Traceback (most recent call last):  File "C:\Users\playe\PycharmProjects\pythonProject3\cogs\ban.py", line 8, in <module>    class ban(commands.Cog):  File "C:\Users\playe\PycharmProjects\pythonProject3\cogs\ban.py", line 12, in ban    @client.tree.command(name="ban", description="Bans a member from the server.")     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  File "C:\Users\playe\PycharmProjects\pythonProject3\.venv\Lib\site-packages\discord\app_commands\tree.py", line 887, in decorator    command = Command(              ^^^^^^^^  File "C:\Users\playe\PycharmProjects\pythonProject3\.venv\Lib\site-packages\discord\app_commands\commands.py", line 666, in __init__    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)                                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  File "C:\Users\playe\PycharmProjects\pythonProject3\.venv\Lib\site-packages\discord\app_commands\commands.py", line 371, in _extract_parameters_from_callback    raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}')TypeError: parameter 'reason' is missing a type annotation in callback 'ban.ban'Process finished with exit code 1

I changed commands.slash_command with client.tree.command.


Viewing all articles
Browse latest Browse all 23276

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>