【发布时间】:2018-01-15 18:52:38
【问题描述】:
我想知道机器人是否有办法使用 Python 中的 discord.py 获取用户在服务器聊天中发送的最后一条消息?非常感谢
【问题讨论】:
标签: python discord.py
我想知道机器人是否有办法使用 Python 中的 discord.py 获取用户在服务器聊天中发送的最后一条消息?非常感谢
【问题讨论】:
标签: python discord.py
旧答案 discord.py 异步(预重写)
使用log_froms 从频道获取消息。
并使用get_all_channels 浏览所有渠道。
然后在结果中搜索作者的最新版本。您必须以合理的数量通过每个渠道,直到找到该人的消息然后停止。比较每个频道的第一个以获得最新的时间。
为了将来获得更好的帮助考虑加入the "discord api" discord server
编辑:与 discord.py rewrite (+1.0) 兼容的方法
您可以使用channel.history() 获取频道的历史记录。默认情况下,它仅从频道中获取最新的 100 条消息。您可以使用 limit 关键字增加此限制。 (例如channel.history(limit = 200)
您可以将它与 find 异步迭代器结合使用,以仅从具有您正在寻找的 id await channel.history().find(lambda m: m.author.id == users_id) 的用户那里获取消息。
然后,您需要遍历服务器中的每个文本通道,并通过将它们与先前获取的消息进行比较并保持创建的更新消息来找到通道中的最新消息。
查找用户最新消息的示例命令。
@commands.command()
async def lastMessage(self, ctx, users_id: int):
oldestMessage = None
for channel in ctx.guild.text_channels:
fetchMessage = await channel.history().find(lambda m: m.author.id == users_id)
if fetchMessage is None:
continue
if oldestMessage is None:
oldestMessage = fetchMessage
else:
if fetchMessage.created_at > oldestMessage.created_at:
oldestMessage = fetchMessage
if (oldestMessage is not None):
await ctx.send(f"Oldest message is {oldestMessage.content}")
else:
await ctx.send("No message found.")
在我的测试中,这是一个相当缓慢的操作,因为必须提出许多不和谐的请求,但应该可以工作。
【讨论】:
channel.history 是执行此操作的新方法。您可以遍历所有消息并记录作者。
await channel.history(limit = 1000).find(lambda m: m.author.id == users_id) 一样增加await channel.history().find(lambda m: m.author.id == users_id) 中的获取限制