Discord.py运行时错误与词典

时间:2018-03-22 00:17:10

标签: python discord members

所以,我一直在尝试制作一个循环遍历服务器中所有成员的机器人。我使用get_all_members()生成器来执行此操作。

for member in client.get_all_members():
      userName = str(member.name)
      userGame = str(member.game)
      userID = str(member.id)
      print(userName, userGame, userID)
      await client.send_message(message.channel, "User " + userName + " 
      (<@" + userID + ">) is playing " + userGame)

我在运行时随机出现了这个错误:

File "C:\Program Files\Python36\lib\site-packages\discord\client.py", line 307, in _run_event 
    yield from getattr(self, event)(*args, **kwargs) 
File "C:\Users\Stefan\Source\Repos\AABot3\AABot3\AABot3.py", line 41, in on_message 
    for member in client.get_all_members(): 
File "C:\Program Files\Python36\lib\site-packages\discord\client.py", line 595, in get_all_members 
    for member in server.members: 
RuntimeError: dictionary changed size during iteration – 

如何避免此错误?

1 个答案:

答案 0 :(得分:1)

尝试在循环之前从get_all_members中创建一个列表。

for member in list(client.get_all_members()):
    ...

正在发生的事情是Server个对象将他们的Member存储在字典中。当您await一个协程时,您允许其他协同程序在您等待时运行,其中一个协程会使Server个对象保持最新状态。每当Server的成员资格发生变化时,字典也会发生变化。因为在更改时不应该迭代某些东西,Python会检测到并终止程序。

首先将值读入列表,我们不会注意到字典何时发生变化。

最新版本改变了这种行为,讨论了here