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

如何修复删除Telegram频道最后一条动态的Python代码

删除Telegram频道最后一条消息的代码错误修复

错误原因分析

你遇到的核心问题有两个:

  1. 协程未正确等待:bot.get_chat(chat_id)是异步协程函数,必须通过await关键字等待其执行完成,才能返回有效的Chat对象。你直接在它后面调用fetch_all(),导致操作的是未执行的协程对象,而非Chat实例。
  2. 不存在的方法调用:Telegram Bot的Chat对象根本没有fetch_all()方法,这是你误用了不存在的API。要获取频道消息,需使用官方提供的聊天历史获取方法。

错误信息翻译

D:\pyMap\venv\Scripts\python.exe "D:\pyMap\main 5.py"
回溯(最近的调用最后):
文件 "D:\pyMap\main 5.py",第29行,在 <module> 中
    asyncio.run(main())
文件 "C:\Users\777\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py",第194行,在 run 中
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
文件 "C:\Users\777\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py",第118行,在 run 中
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
文件 "C:\Users\777\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py",第664行,在 run_until_complete 中
    return future.result()
           ^^^^^^^^^^^^^^^
文件 "D:\pyMap\main 5.py",第15行,在 main 中
    messages = await bot.get_chat(chat_id).fetch_all()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'coroutine' 对象没有属性 'fetch_all'
sys:1: RuntimeWarning: 协程 'Bot.get_chat' 从未被等待
进程结束,退出代码 1

修正后的代码

以下是针对python-telegram-bot v20+版本的修复代码(如果使用旧版本,可将get_chat_history替换为get_history):

import asyncio
from telegram import Bot
from telegram.error import TelegramError

bot_token = '你的BotToken'
chat_id = '@你的频道用户名'  # 或直接使用频道数字ID


async def main():
    bot = Bot(token=bot_token)

    try:
        # 可选:先验证频道可访问
        await bot.get_chat(chat_id)
        
        # 获取频道最后1条消息
        async for message in bot.get_chat_history(chat_id, limit=1):
            await message.delete()
            print(f"已删除最后一条消息:{message.text}")
            return
        
        print("频道中没有消息可删除")
    except TelegramError as e:
        print(f"操作出错:{e}")


if __name__ == '__main__':
    asyncio.run(main())

关键改动说明

  • 用await bot.get_chat(chat_id)正确等待协程执行,验证频道的可访问性
  • 使用bot.get_chat_history()异步迭代获取聊天历史,通过limit=1只获取最新一条消息
  • 直接遍历获取到的消息,执行删除操作
  • 完善了无消息时的提示逻辑

注意:你的Bot必须被添加为频道管理员,且拥有删除消息的权限,否则会触发权限错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:32:51