使用 python/Tweepy 从 Twitter 获取最新的直接消息

Get latest direct message from Twitter using python/Tweepy

我刚开始使用 Tweepy,我正在尝试构建一个非常简单的机器人,它将使用 Twitter 来自动化我家中的一些事情(主要是为了好玩和学习 Tweepy)。我浏览了 Tweepy 文档,但无法找到如何在不知道消息 ID 的情况下从我自己的帐户检索最新的直接消息。

我假设我可以使用 API.get_direct_messages() 方法,但它需要一个消息 ID(我不知道)。谁能告诉我正确的方法来做到这一点?我正在使用 Python3

谢谢!

您似乎混淆了两种不同的方法。 direct_messages() method(没有 get_)应该会给你一个直接消息列表。

get_direct_message()(单数)returns 来自其 ID 的一条直接消息。

来自 Tweepy Docs ~ "API.list_direct_messages([count][ cursor]) Returns 过去 30 天内的所有直接消息事件(发送和接收)。按时间倒序排列。"

my_dms = api.list_direct_messages()

获取最新消息对象(发送和接收):

my_dms[0]

如果您特别想要最后 收到 消息:

def get_last_received(my_dms):
    for dm in my_dms:
        if dm.message_create['target']['recipient_id'] == 'my_user_id':
            return dm  # We will return when we encounter the first received message object

get_last_received(my_dms)