不明白为什么出现这种TypeError:只能将列表(而不是“ dict”)连接到开始出现的列表

时间:2018-12-30 05:31:23

标签: 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 16, in get_all_messages
prev = prev + messages

TypeError: can only concatenate list (not "dict") to list

代码:

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

username1 = "test"
username2 = "test#0001"
auth_token = "RWYFHyrtYRY.RYYR_jqj114452E"
channel_id = "345634345364"
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 = prev + 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))

我不确定发生了什么变化。该脚本有效。一个月后,我再次运行它,出现了此错误。

2 个答案:

答案 0 :(得分:3)

如果您希望保留接收到的内容本身是列表时的平坦列表的旧行为,而且还能够将未接收到的消息作为单个项附加,请考虑:

if isinstance(messages, list):
    prev.extend(messages)
else:  # messages is not really a list!
    prev.append(messages)

否则,如果您只是想将新接收到的邮件批处理作为单个项目附加到列表中,则无论如何,这看起来像:

prev.append(messages)

如果右侧也是列表,则只能将+与左侧的列表一起使用。错误消息表明这里不是这种情况(在今天您从服务器获得的响应中,右侧的内容是字典而不是列表)。

答案 1 :(得分:1)

messages应该是列表,在您的情况下,这是一个字典级联,应该是list + list

如果您需要附加int或任何其他单个元素,则始终可以使用[]或直接使用append将其转换为单个元素列表。

prev = prev + [messages]

OR

prev.append(messages)