You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py中调用channel.history从有效频道返回空列表[]的问题排查

解决Discord频道历史记录返回空列表的问题

我看你在尝试扫描指定频道的所有消息时,遇到了调用channel.history()始终返回空列表[]的问题,咱们来捋清楚问题出在哪以及怎么解决。

你的原代码

# 示例时间为2021-01-01 00:00:00
start_of_month = datetime.datetime(year, month, 1)
# 示例时间为2021-01-31 23:59:59
end_of_month = self.last_second_of_month(start_of_month)
channel = self.bot.get_channel(channelIdgoeshere)
messages = await channel.history(before=start_of_month, after=end_of_month).flatten()

问题原因

你把history()方法的before和after参数搞颠倒了!

  • after参数指定的是时间范围的起始点(仅获取该时间之后的消息)
  • before参数指定的是时间范围的结束点(仅获取该时间之前的消息)

你现在的设置是before=start_of_month(2021-01-01)、after=end_of_month(2021-01-31),这相当于要求获取“在1月1日之前,同时又在1月31日之后”的消息——这显然没有符合条件的内容,所以返回空列表是必然结果。

修正后的代码

只需要调换两个参数的取值即可:

# 示例时间为2021-01-01 00:00:00
start_of_month = datetime.datetime(year, month, 1)
# 示例时间为2021-01-31 23:59:59
end_of_month = self.last_second_of_month(start_of_month)
channel = self.bot.get_channel(channelIdgoeshere)
# 修正:before设为结束时间,after设为开始时间
messages = await channel.history(before=end_of_month, after=start_of_month).flatten()

这样设置后,就能正确获取start_of_month到end_of_month这个时间区间内的所有消息了,只要频道在这段时间内有消息,就不会再返回空列表啦。

内容的提问来源于stack exchange,提问作者JupeOwl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 06:12:34