Я пытаюсь создать бота с файлом модерации. Сначала я добавил бан и разбан, но это не работает. мои файлы выглядят так. Я думаю, что файлы находятся на правильных позициях.
Основная команда:
import discord
from discord.ext import commands
from .cogs import ban
intents = discord.Intents.default()
intents.members = True # Required for on_member_join listener
client = commands.Bot(intents=intents)
@client.event
async def on_ready():
print("Move Move Move")
def setup(bot):
ban(bot)
setup(client)
client.run("token")
запретить винтик:
import discord
from discord import interactions
from discord.ext import commands
client = 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))
ошибка:
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
Я изменил команды.slash_command на client.tree.command.






Вы должны загружать свои процессоры в асинхронном контексте.
В файле запрета cog:
import discord
from discord import app_commands
from discord.ext import commands
class BanCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name = "ban", description = "Bans a member from the server.")
@commands.has_permissions(ban_members=True)
async def ban(self, ctx: commands.Context, 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}")
@app_commands.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: commands.Context, 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}")
async def setup(bot):
await bot.add_cog(BanCog(bot))
В основном файле:
import discord
from discord.ext import commands
import asyncio
intents = discord.Intents.default()
intents.members = True # Required for on_member_join listener
bot = commands.Bot(intents=intents)
@bot.event
async def on_ready():
print("Move Move Move")
async def main():
async with bot:
await bot.load_extension("cogs.ban")
await bot.start("TOKEN")
asyncio.run(main())