Telegram转Twitter机器人报错求助:协程对象无get_last_message方法
解决Telegram转Twitter机器人的AttributeError问题
错误原因
- 异步API使用错误:python-telegram-bot v13+版本采用异步架构,
bot.get_chat()返回的是协程对象,必须通过await关键字获取实际的Chat实例,不能直接链式调用方法。 - 方法不存在:Telegram Bot API中没有
get_last_message()方法,获取频道历史消息应使用get_chat_history()。
修正后的完整代码
import asyncio import telegram import tweepy # Twitter API keys consumer_key = "x" consumer_secret = "x" access_token = "x" access_token_secret = "x" # Telegram Bot API token telegram_token = "x" # Telegram chat ID to get messages from channel_id = -1001679200115 # Authenticate with Twitter API auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) async def main(): # 初始化Telegram Bot客户端 bot = telegram.Bot(token=telegram_token) # 获取频道信息(需await异步调用) await bot.get_chat(chat_id=channel_id) # 异步获取最近10条频道消息 messages = [] async for message in bot.get_chat_history(chat_id=channel_id, limit=10): messages.append(message) # 反转消息顺序(从旧到新发送,可选) messages.reverse() # 逐条发送至Twitter for message in messages: if not message.text: continue tweet_content = message.text # 附加消息链接(根据实际消息结构调整) if hasattr(message, 'link') and message.link: tweet_content += f"\n\n{message.link}" try: api.update_status(tweet_content) print(f"已发送推文: {tweet_content}") except tweepy.TweepyException as e: print(f"推文发送失败: {str(e)}") if __name__ == "__main__": asyncio.run(main())
关键修改说明
- 使用
async/await语法适配Telegram的异步API,通过asyncio.run()启动异步主函数。 - 用
get_chat_history()异步生成器获取历史消息,替代不存在的get_last_message()。 - 增加消息文本检查和Twitter API异常处理,提升程序稳定性。
- 可选反转消息顺序,确保推文按频道消息发布顺序发送。
内容的提问来源于stack exchange,提问作者RenanBsz
相关产品推荐
相关产品推荐

