python - 如何在 discord.py 中获取频道的最新消息?
问题描述
有没有办法使用 discord.py 获取特定频道的最新消息?我查看了官方文档并没有找到方法。
解决方案
(答案使用discord.ext.commands.Bot
而不是discord.Client
;我没有使用 API 的较低级别部分,所以这可能不适用于discord.Client
)
在这种情况下,您可以使用Bot.get_channel(ID)
获取要检查的通道。
channel = self.bot.get_channel(int(ID))
然后,您可以使用channel.last_message_id
获取最后一条消息的 ID,并使用 获取消息channel.fetch_message(ID)
。
message = await channel.fetch_message(
channel.last_message_id)
组合起来,获取频道最后一条消息的命令可能如下所示:
@commands.command(
name='getlastmessage')
async def client_getlastmessage(self, ctx, ID):
"""Get the last message of a text channel."""
channel = self.bot.get_channel(int(ID))
if channel is None:
await ctx.send('Could not find that channel.')
return
# NOTE: get_channel can return a TextChannel, VoiceChannel,
# or CategoryChannel. You may want to add a check to make sure
# the ID is for text channels only
message = await channel.fetch_message(
channel.last_message_id)
# NOTE: channel.last_message_id could return None; needs a check
await ctx.send(
f'Last message in {channel.name} sent by {message.author.name}:\n'
+ message.content
)
# NOTE: message may need to be trimmed to fit within 2000 chars
推荐阅读
- git - 在 bitbucket 管道上定义同步目录
- pandas - 重新采样和插值 pandas df
- makefile - 安装时说未设置 CUDADIR 环境变量
- python - Python:将初始numpy数组分配给另一个变量,更改新变量的几个元素会更改初始numpy数组
- algorithm - 分配最佳卫生间的算法
- python - 如何在python中附加到列表时格式化字符串和小数
- javascript - react-loadable 已加载块但未执行代码
- matlab - 如何在 MATLAB 中求解 ODE?
- android - 保存和加载 RadioGroup 的正确方法
- npm - 无法从 webpack 3 升级到 3.12.0