【问题标题】:Discord.py | Error with the voice channel不和谐.py |语音通道出错
【发布时间】:2021-09-27 15:49:41
【问题描述】:

此代码的目的是当参与者加入某个语音频道时,会创建他的个人语音频道。并且当语音通道为空时,它会被自动删除。该代码完美地执行其任务,但我在控制台中收到错误。我该如何解决这个问题?

代码:

@Bot.event
async def on_voice_state_update(member,before,after):
    if after.channel.id == 826351221145206855:
        for guild in Bot.guilds:
            maincategory = discord.utils.get(guild.categories, id=816323445213626368)
            channel2 = await guild.create_voice_channel(name=f'HALL {member.display_name}',category = maincategory)
            await channel2.set_permissions(member,connect=True,mute_members=True,move_members=True,manage_channels=True)
            await member.move_to(channel2)
            def check(x, y, z):
                return len(channel2.members) == 0
            await Bot.wait_for('voice_state_update', check=check)
            await channel2.delete()

控制台出错:

Ignoring exception in on_voice_state_update
Traceback (most recent call last):
  File "C:\Users\Маки\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "d:\import discord.py", line 242, in on_voice_state_update
    if after.channel.id == 826351221145206855:
AttributeError: 'NoneType' object has no attribute 'id'

【问题讨论】:

  • 错误显示after.channelNone。首先,您可以使用print() 查看after 中的内容

标签: python discord discord.py


【解决方案1】:

如果成员离开语音频道,voice_state_update 事件将被触发,after.channel 将变为 None,因为用户不再处于任何语音频道中。因此,您的第一个 if-statement 评估为

if None.id == 826351221145206855:

并产生您看到的错误。一个干净的解决方法是将行修改为

if after.channel and after.channel.id == 826351221145206855:

这样,您的机器人将首先检查用户是否在语音频道中,如果是这种情况,则仅尝试查看 id。这利用了if None 评估为Falseif "actual channel" 评估为True 的Python 机制,并且也不会干扰您的其余代码,因为当用户离开任何语音通道时不需要新的操作

【讨论】:

    猜你喜欢
    • 2021-01-18
    • 2021-03-11
    • 2021-11-17
    • 2021-02-10
    • 2021-04-06
    • 1970-01-01
    • 2020-06-20
    • 2021-05-12
    • 2021-12-24
    相关资源
    最近更新 更多