【发布时间】: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