【问题标题】:How to check time spent on voice channel of a particular user?[Discord.py]如何查看特定用户在语音频道上花费的时间?[Discord.py]
【发布时间】:2022-01-15 04:33:03
【问题描述】:

我正在使用此代码检查在特定用户的语音频道上花费的时间

    async def on_voice_state_update(self, member, before, after):
        if member.bot:
            return
        with open('voice_data.json', 'r') as file: 
            voice_data = json.load(file)
        new_user = str(member.id)
        guild_id = str(member.guild.id)
        if new_user not in voice_data[guild_id]:
            voice_data[guild_id][new_user] = {
                "total_time" : 0,
                "join_time" : None} 
        userdata = voice_data[guild_id][new_user]
       
        if(before.channel == None):
            join_time = round(time.time())
            userdata["join_time"] = join_time
        
        elif(str(after.channel.guild.id) != guild_id):
            leave_time = time.time()
            passed_time = leave_time - userdata["join_time"]
            userdata["total_time"] += passed_time
            userdata["join_time"] = None
        with open('voice_data.json', 'w') as update_user_data:
            json.dump(voice_data, update_user_data, indent=4)

但由于某种原因,我收到此属性错误,它在 after.channel 中没有返回任何内容

Ignoring exception in on_voice_state_update
Traceback (most recent call last):
  File "C:\Users\hires\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "d:\Freelance Giveaway Bot\Commands\voice.py", line 28, in on_voice_state_update
    elif(str(after.channel.guild.id) != guild_id):
AttributeError: 'NoneType' object has no attribute 'guild'
{
    "884811895884894218": {
        "555463650358329354": {
            "total_time": 0,
            "join_time": 1639144293
        }
    }
}

这里是voice_data.json的摘录

【问题讨论】:

  • 当用户断开频道时会发生这种情况吗?如果是这样,那么after.channel 将是None。您可能需要执行类似于 if(before.channel == None)... 的操作,但改用 after.channel

标签: python json discord.py


【解决方案1】:

如果用户离开语音频道,after.channel 可以是None。因此,您应该编写以下内容:

elif after.channel is not None and str(after.channel.guild.id) != guild_id:

代替

elif(str(after.channel.guild.id) != guild_id):

检查after.channel 是否不是None

【讨论】:

  • 它没有显示任何错误,但它仍然什么也不做
  • 我只是发现当我加入任何其他语音频道而不是断开连接时,它会更改 total_time 并将 voice_data.json 中的 join_time 更改为 null
猜你喜欢
  • 2021-09-08
  • 2021-03-30
  • 1970-01-01
  • 2020-10-04
  • 2021-04-05
  • 1970-01-01
  • 2018-04-04
  • 2020-06-11
  • 2021-05-03
相关资源
最近更新 更多