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

Discord语音频道角色机器人报错:on_voice_state_update参数不匹配

Discord机器人语音频道角色分配异常问题解决

嘿,我来帮你搞定这个机器人的问题!你开发的这款Discord机器人本来想实现「用户进入语音频道自动分配角色,离开时移除角色」的功能,但运行时触发了参数错误,我来一步步给你分析和修正。

你的原始代码

@client.event
async def on_voice_state_update(before, after):
    role = discord.utils.get(after.server.roles, name="glosowy")
    if not before.voice.voice_channel and after.voice.voice_channel:
        await client.add_roles(after, role)
    elif before.voice.voice_channel and not after.voice.voice_channel:
        await client.remove_roles(after, role)

收到的错误信息

Ignoring exception in on_voice_state_update
Traceback (most recent call last):
  File "C:\Users\aaa\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
TypeError: on_voice_state_update() takes 2 positional arguments but 3 were given

问题分析

这个错误的核心原因是**on_voice_state_update事件的参数数量不匹配**!在Discord.py的事件机制里,这个回调函数需要接收三个参数:member(触发状态变化的用户)、before(变化前的语音状态)、after(变化后的语音状态),但你只写了before和after两个参数,所以Python会抛出「参数数量不符」的错误。

另外还有两个Discord版本适配的小问题:

  1. 新版本Discord.py里,server属性已经被更名为guild,用after.server会报错
  2. voice.voice_channel属性也被简化成了channel,旧属性已经被弃用

修正后的完整代码

@client.event
async def on_voice_state_update(member, before, after):
    # 获取名为"glosowy"的角色,使用新版本的guild属性
    role = discord.utils.get(after.guild.roles, name="glosowy")
    # 判断用户是否刚进入语音频道
    if not before.channel and after.channel:
        await member.add_roles(role)
    # 判断用户是否刚离开语音频道
    elif before.channel and not after.channel:
        await member.remove_roles(role)

关键改动说明

  • 给回调函数新增了第一个参数member,这是事件触发时必须传递的用户对象
  • 将after.server替换为after.guild,适配Discord.py v1.0+的版本规范
  • 把before.voice.voice_channel和after.voice.voice_channel改成before.channel和after.channel,使用当前支持的属性
  • 添加/移除角色的方法调用对象从after改为member,更直接准确地操作目标用户

如果你的Discord.py版本非常老旧(比如v0.16.x),虽然server还能使用,但on_voice_state_update的参数依然需要三个,建议你升级到最新版本的Discord.py,因为旧版本已经停止维护,会有安全和功能兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:52:36