如何"catch"一个对象在Discord.py中没有属性?

How to "catch" a object has no attribute in Discord.py?

所以我得到了以下代码,我正在尝试查看他们正在播放或停止播放的内容,并在服务器中从中获取统计信息,例如:“彩虹六号当前正在播放:8”。但是,当脚本出错并关闭“循环”时,这确实有效。

if before.activity != after.activity:

    #Stats for Rainbow
    afteractivity_name = str(after.activity.name) if after.activity.name else None

    #When someone started playing
    if afteractivity_name == "Rainbow Six Siege":

        #Getting the current amount and setting variables
        rainbow_stats = await bot.fetch_channel(971830717292101722)
        rainbow_stats_str = str(rainbow_stats)
        rainbow_stats_split = rainbow_stats_str.split(" ")
        last_count = rainbow_stats_split[3]
        last_count = int(last_count)

        #Making and setting the new one
        new_count = last_count + 1
        await rainbow_stats.edit(name=f"\U0001F4CA Currently Playing: {new_count}" )

错误如下:

Traceback (most recent call last):
  File "F:\.1 Bot Test\venv\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "F:\.1 Bot Test\Bot\Bot Skript.py", line 459, in on_member_update
    beforeactivity_name = str(before.activity.name) if after.activity.name else None
AttributeError: 'NoneType' object has no attribute 'name'

这一行

afteractivity_name = str(after.activity.name) if after.activity.name else None

实际上并没有按照您的意愿去做。

你想设置 afteractivity_name 为名字,如果它存在,否则如果 after.activityNone,设置它为 None.

但是,在评估条件时,您已经访问了 after.activity.name。这将导致错误,因为您试图获取 None

name 属性

相反,尝试

afteractivity_name = str(after.activity.name) if (after.activity is not None) and (after.activity.name is not None) else None

这将在尝试访问 name.

之前检查 after.activity 是否为 None

最好明确检查它不是 None,而不仅仅是测试真实性,这可能是 False,具体取决于库的计算方式。