discord.py无参数!info命令获取Server对象报错求助
Fixing the MissingRequiredArgument Error for Your !info Command
It looks like the main issue here stems from using an older version of discord.py where commands don’t automatically pass the context (ctx) to your function unless you explicitly enable it. Let’s walk through the fixes step by step:
Key Issues in Your Code
- Missing
pass_context=True: In discord.py v0.16.x (the version your error traceback points to), you need to addpass_context=Trueto the@bot.command()decorator to make the context available to your function. Without this, the bot doesn’t passctx, hence the "MissingRequiredArgument" error. - Outdated Coroutine Syntax: Using
@asyncio.coroutinewith a regulardefis legacy syntax—switching toasync defis cleaner and aligns with modern async Python practices. - Incorrect Server Access:
ctx.message.author.serverisn’t the right way to get the server where the command was sent. Usectx.message.serverinstead (since the message itself is tied to the server’s channel). - Unformatted Output: Your print statement concatenates strings without spaces or newlines, making the output hard to read.
Corrected Code
@bot.command(pass_context=True) async def info(ctx): # Retrieve the server from the message context server = ctx.message.server server_name = server.name server_id = server.id server_owner = server.owner.name # Print neatly formatted server information print(f"Server Name: {server_name}") print(f"Server ID: {server_id}") print(f"Server Owner: {server_owner}")
Additional Notes
- If you upgrade to a newer discord.py version (v1.0+),
serverwas renamed toguild, so you’d usectx.message.guildinstead. Also,pass_context=Trueis no longer required—context is passed automatically in v1.0+. - Basic commands like this don’t need special bot permissions, but ensure your bot is properly invited to the server with standard access.
Content of the question originates from Stack Exchange, asked by TermoZour
相关产品推荐
相关产品推荐

