【发布时间】:2018-07-14 11:20:37
【问题描述】:
我得到了一个从 json 文件中解析数据的代码,但它仍然不完整。
{"people": [
{"UserID": "xxxxx123", "Name": "Steve", "Sex": "Male", "age": "30"},
{"UserID": "xxxxx124", "Name": "Rachel", "Sex": "Female", "age": "25"},
{"UserID": "xxxxx125", "Name": "George", "Sex": "Male", "age": "22"} ] }
@bot.command(pass_context=True)
async def mention(ctx, member: discord.Member):
with open('data.txt') as json_file:
data = json.load(json_file)
for p in data['people']:
if(p['UserID'] == str(member.id)):
await bot.send_message(ctx.message.channel, p)
当我们在不和谐频道中键入 ?mention @user 时,机器人会提供该用户数据。但我还需要 2 个帮助。
- bot 需要从多个 json 文件或 excel 表格 1 2 3 等获取数据。
- 应该使用
?mention xxxxx123或?mention George来获取用户数据,而不是标记用户。
在服务器中运行时更新错误:
Ignoring exception in on_ready
Traceback (most recent call last):
File "/home/bosen/.local/lib/python3.6/site-packages/discord/client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "bot.py", line 37, in on_ready
d = json.load(f)
File "/home/bosen/.local/lib/python3.6/json/__init__.py", line 296, in load
return loads(fp.read(),
File "/home/bosen/.local/lib/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
MemoryError
【问题讨论】:
-
其他 json 文件中有什么?您应该在启动机器人时加载所有这些信息(将代码放在
on_ready事件中)。然后在调用命令时循环遍历 Python 对象。 -
我可以得到一个示例代码如何做到这一点?我也试图让用户输入的名称工作,而不是用用户 ID 标记用户。
-
Python 逐行读取它们,因此文件大小并不重要。 2000 个 json 条目并没有那么大。这将允许您对单个文件名进行硬编码。如果您有多个名为
George的用户,您希望发生什么?
标签: json python-3.x discord.py