简体   繁体   English

为什么我的 on_member_update 运行不止一次

[英]Why is my on_member_update running more than once

I'm trying to make a bot that tracks playtime on discord. The first if runs when a game is detected on discord. The second if runs when the game is closed.我正在尝试制作一个机器人来跟踪 discord 上的游戏时间。第一个 if 在 discord 上检测到游戏时运行。第二个 if 在游戏关闭时运行。

@client.event
async def on_member_update(before, after):

 if (before.activity is None) and (after.activity is not None):

   uname = after.name
   disc = after.discriminator
   usertag = f"{uname}#{disc}"
   uid = str(after.id)
   gamestarted = str(datetime.utcnow())

   await funcs.storestart(uid, usertag, gamestarted, col)

 if (before.activity is not None) and (after.activity is None):

   uid = str(before.id)
   gname = before.activity.name

   now = str(datetime.utcnow())

   await funcs.addplaytime(uid, gname, now, col)

But when I open a game, the on member update event seems to run three times.但是当我打开一个游戏时,on member update 事件似乎运行了 3 次。 I put print inside the first if to check if this was the case and turns out it runs three times every time.我将 print 放在第一个 if 中以检查是否是这种情况,结果每次运行 3 次。 Anyone know the reasoning for this?有人知道这样做的原因吗? Am I doing something wrong?难道我做错了什么?

Turns out its running three times because the bot is in 3 guilds.结果它运行了 3 次,因为该机器人在 3 个公会中。 The on member update is firing for each guild the user is in. on member 更新针对用户所在的每个公会触发。

I just wanted to clarify an answer in case anyone comes across this like I did since I had a similar issue (and didn't read the API carefully).我只是想澄清一个答案,以防有人像我一样遇到这个问题,因为我遇到了类似的问题(并且没有仔细阅读 API)。 Keywords 'before' and 'after' under the function 'on_member_update' are the same as saying 'member'. function 'on_member_update' 下的关键字 'before' 和 'after' 等同于说 'member'。 If you want the bot to run one time and it's in multiple guilds, you can have it look at the change in activity in only one guild.如果您希望机器人运行一次并且它在多个公会中,您可以让它只查看一个公会中的活动变化。 Below is an example:下面是一个例子:

if (before.guild.name == "AGuildNameTheBotIsIn"):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM