运行模块时获取“ KeyError”

时间:2018-12-30 07:06:28

标签: python python-requests

因此,我对Python代码有点陌生,因此在尝试解密此问题时我有点迷茫。

尝试运行此模块时,我不断收到此错误:

Traceback (most recent call last):
    File "C:\Users\test\OneDrive\Documents\mass.py", line 33, in <module>
      delete_all(auth_token, channel_id, username1, username2, get_all_messages(auth_token, channel_id))
  File "C:\Users\test\OneDrive\Documents\mass.py", line 29, in delete_all
     if (message["author"]["username"] == user1):

 KeyError: 'author'

这里是所有代码:

import json, requests, sys
print ("Delete all messages from specific channel")

username1 = "test"
username2 = "test#0101"
auth_token = "ZMNHFHFKJkjfja.FJDJfhsd.EJjfda"
channel_id = "35345345345451"
delete_from_all_users = "False"

def get_all_messages(auth, id, last="", prev=[]):
    if not last:
        messages = json.loads(requests.get("http://canary.discordapp.com/api/v6/channels/" + id + "/messages", headers={"authorization": auth}, params={"limit": 100}).content)
    else:
        messages = json.loads(requests.get("http://canary.discordapp.com/api/v6/channels/" + id + "/messages", headers={"authorization": auth}, params={"before" : last, "limit" : 100}).content)
    prev.append(messages)

    if len(messages) < 100:
        print ("Got to end of channel at " + str(len(prev)) + " messages")
        return prev
    else:
        oldest = sorted(messages, key=lambda x: x["timestamp"], reverse=True)[-1]

    return get_all_messages(auth, id, last=oldest["id"], prev=prev)

def delete_all(auth, id, user1, user2, messages):
    print ("Trying to delete all messages in " + id + " from username " + user1)
    for message in messages:
      # print(message["author"]["username"])
        if (message["author"]["username"] == user1):
            requests.delete("http://canary.discordapp.com/api/v6/channels/" + id + "/messages/" + message["id"],headers={"authorization": auth})
    print ("All messages were deleted")

delete_all(auth_token, channel_id, username1, username2, get_all_messages(auth_token, channel_id))

1 个答案:

答案 0 :(得分:2)

Kelsey,在代码中if条件的最后第四行,

if (message["author"]["username"] == user1):

编译器在您要迭代的json消息中找不到任何“作者”。现在,由于我们不知道您的json的结构,因此我们无法为您提供更多帮助,但是可以肯定的是,消息json不包含任何密钥(例如author)。