You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py on_server_join报错:缺少必需位置参数'server',求解决

解决Discord机器人on_server_join事件的参数缺失错误

看起来你遇到的问题是Discord.py事件函数的参数定义不对导致的,我来帮你一步步排查和修复:

错误原因分析

Discord.py的on_server_join(在v1.0+版本中改名为on_guild_join)事件只会传入一个参数——机器人刚加入的服务器/公会对象,而你定义的函数写了(ctx, server),这就导致了参数不匹配的TypeError:因为事件触发时只会传递一个对象,而你的函数期望两个参数,所以报错说缺少server。

另外你的代码里还有两个小问题:

  • 你试图通过ctx.message.server.members获取成员,但on_server_join触发时并没有对应的消息上下文(ctx),这个写法完全无效
  • 邀请链接的Markdown格式写反了,正确的链接格式应该是[显示文本](链接地址)

修复后的代码

如果你使用的是Discord.py v0.16.x(旧版本,用server):

@bot.event
async def on_server_join(server):
    bot_invite_link = 'https://discordapp.com/oauth2/authorize?client_id=413782934009675776&permissions=8&scope=bot'
    # 遍历服务器所有成员
    for member in server.members:
        try:
            # 发送私信,修正链接格式
            await bot.send_message(member, f"Thanks for using MBot! Click [here]({bot_invite_link}) to invite me to other servers!")
        except Exception as e:
            # 捕获发送失败的错误(比如用户关闭了私信),避免机器人崩溃
            print(f"Failed to send message to {member.name}: {e}")

如果你使用的是Discord.py v1.0+(新版本,用guild):

注意新版本API有变化,而且需要启用成员意图才能获取到所有成员:

import discord
from discord.ext import commands

# 启用成员意图
intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_guild_join(guild):
    bot_invite_link = 'https://discordapp.com/oauth2/authorize?client_id=413782934009675776&permissions=8&scope=bot'
    for member in guild.members:
        try:
            await member.send(f"Thanks for using MBot! Click [here]({bot_invite_link}) to invite me to other servers!")
        except Exception as e:
            print(f"Failed to send message to {member.name}: {e}")

# 运行机器人
bot.run('你的机器人令牌')

额外注意事项

  1. 成员权限/意图:在新版本Discord.py中,默认无法获取服务器成员列表,你需要在Discord开发者门户的机器人页面开启"Server Members Intent",否则guild.members可能是空的
  2. 私信限制:有些用户可能设置了拒绝接收陌生人私信,所以一定要加try-except捕获错误,不然机器人可能因为发送失败而崩溃
  3. 避免被标记为垃圾邮件:频繁发送大量私信可能会导致你的机器人被Discord限制,建议谨慎使用这个功能,或者添加一些限制逻辑

内容的提问来源于stack exchange,提问作者Moog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:33:23