Discord.py 字典运行时错误
Discord.py Runtime error with dictionaries
所以,我一直在尝试制作一个循环遍历我服务器中所有成员的机器人。我正在使用 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 –
如何避免这个错误?
尝试从 get_all_members
中创建一个列表,然后再遍历它。
for member in list(client.get_all_members()):
...
发生的事情是 Server
对象将它们的 Member
存储在字典中。当你 await
一个协程时,你允许其他协程在你等待时 运行,其中之一使 Server
对象保持最新。每当 Server
的成员发生变化时,字典也会发生变化。因为您永远不应该在某些东西发生变化时对其进行迭代,所以 Python 会检测到这一点并终止程序。
通过先将值读入列表,我们不会注意到字典何时更改。
最新版本改变了这个行为,讨论here
所以,我一直在尝试制作一个循环遍历我服务器中所有成员的机器人。我正在使用 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 –
如何避免这个错误?
尝试从 get_all_members
中创建一个列表,然后再遍历它。
for member in list(client.get_all_members()):
...
发生的事情是 Server
对象将它们的 Member
存储在字典中。当你 await
一个协程时,你允许其他协程在你等待时 运行,其中之一使 Server
对象保持最新。每当 Server
的成员发生变化时,字典也会发生变化。因为您永远不应该在某些东西发生变化时对其进行迭代,所以 Python 会检测到这一点并终止程序。
通过先将值读入列表,我们不会注意到字典何时更改。
最新版本改变了这个行为,讨论here