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

如何为Telegram Bot设置时间范围以收集近一个月消息

动态设置Telethon消息收集的时间范围(过去一个月)

要实现自动收集过去一个月内的消息,无需手动写死起始日期,可通过动态计算时间范围修改代码:

修改后的完整代码

from telethon import TelegramClient
from datetime import date, timedelta
# 如需精准按月份计算(例如从5月10日回溯到4月10日),需先安装依赖:pip install python-dateutil
# from dateutil.relativedelta import relativedelta

api_id = my_id
api_hash = ''
phone = ''

client = TelegramClient(phone, api_id, api_hash)
# 方式1:简单回溯30天
date_start = date.today() - timedelta(days=30)
# 方式2:精准回溯1个月(适配不同月份的天数差异)
# date_start = date.today() - relativedelta(months=1)


async def main():
    async for message in client.iter_messages(
        -1001369370434, 
        reverse=True, 
        offset_date=date_start, 
        search='eth'
    ):
        print(message.chat.title, ':', message.date, ':', message.text)

with client:
    client.loop.run_until_complete(main())

关键改动说明

  • 动态计算起始日期:用date.today()结合timedelta自动生成过去30天的起始点,无需手动更新日期;如果需要严格匹配“一个月”(而非固定30天),可以使用relativedelta处理不同月份的天数差异。
  • 时间范围控制:offset_date=date_start指定消息收集的起始时间,配合reverse=True会从该起始时间开始,按从旧到新的顺序遍历到最新消息,恰好覆盖过去一个月的范围。
  • 过滤逻辑:保留search='eth'会只收集包含“eth”关键词的消息,无需过滤可直接移除该参数。

内容的提问来源于stack exchange,提问作者Александр Валиев

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:56:06