首页 > 解决方案 > Discord py 获取消息

问题描述

我正在尝试从公会的特定频道中的用户那里获取所有消息。但是,即使用户在频道/公会中发送了超过 30 条消息,它也只能从用户那里收到一条消息。

async def check(channel):
    fetchMessages = await channel.history().find(lambda m: m.author.id == 627862713242222632)
    print(fetchMessages.content)

标签: pythonpython-3.xdiscord.py

解决方案


问题是.find()并且.get()只返回与您的条件匹配的第一个条目。您可以改为flatten()来自该频道的消息,这将为您提供消息列表,然后过滤掉属于您指定的 ID 的消息。确保检查文档的链接。

@client.command()
async def check(ctx, channel:discord.TextChannel): # Now you can tag the channel
    messages = await channel.history().flatten()
    # messages is now list of message objects.

    for m in messages:
        if m.author.id == 627862713242222632: # ID you provided
            print(m.content) # one message at the tim

或者另一种方法是使用filter().

@client.command()
async def check(ctx, channel:discord.TextChannel):
    def user_filter(message):
        return message.author.id == 627862713242222632

    messages = [m.content async for m in channel.history().filter(user_filter)]
    print(messages) # prints the list we get from the line above

推荐阅读