Telegram Bot 不再发送消息 - 从未等待过协程“Bot.send_message”

问题描述 投票:0回答:1

我对此感到很无助...... 突然之间,我之前的代码自 2023 年 5 月 3 日起就不再工作了。我并没有故意更改任何内容。但我的电报机器人现在不再发送消息。 我想由于我错过了 anaconda-navigator 的更新,或者我监督的任何其他更改,导致存在一些不兼容性。 也许你可以通过代码或其他方式帮助我解决这个问题。

我的设置: Synology NAS,运行 Virtual Machine Manager,运行安装了 Anaconda-Navigator 的 Ubuntu VM,通过 Spyder 运行代码。以前所有的都是在“基础(根)”环境中运行的,但我也尝试过创建一个新的环境。一切都没有改变。

代码如下:

import telegram

TOKEN = "123"
chat_id = "345"

def send(message, chat_id, token=TOKEN):
    bot = telegram.Bot(token=token)
    bot.sendMessage(chat_id=chat_id, text=message)

message = "Hello world!"
send(message, chat_id)

输出: RuntimeWarning:从未等待协程“Bot.send_message” bot.sendMessage(chat_id=chat_id, text=消息) RuntimeWarning:启用tracemalloc以获取对象分配回溯

您知道可能出了什么问题吗? 我已经完全卸载了 anaconda,重新安装了它,创建了一个具有不同 python 版本的新环境,并从那里运行spyder。没有任何帮助。 作为一种解决方法并检查其他一切是否正常,我通过“requests.get”运行了机器人并且它起作用了,但是我的消息格式被破坏了,这就是为什么我想坚持以前的风格。

我也尝试询问 ChatGPT,但那里的建议总是以相同的错误结束,或者例如这也不起作用:

async def send():
    # Send message to chat
    await bot.send_message(chat_id=chat_id, text="Hello, world!")

# Run the coroutine
asyncio.run(send_message())

输出: RuntimeError:无法从正在运行的事件循环调用 asyncio.run()

有什么想法吗? 谢谢!

亲切的问候, 大卫

bots spyder coroutine python-telegram-bot
1个回答
0
投票

我使用

telegram.Bot
也遇到了同样的问题。我按照本页中描述的步骤运行协程解决了这个问题:https://superfastpython.com/asyncio-coroutine-was-never-awaited/.

所以我只需要将

send_message()
方法的调用移至
asyncio.run()
调用即可。

import asyncio
from telegram import Bot

botToken = 'yourBotToken'
bot = Bot(token = botToken)

chatId = 'yourChatId'
message = 'Hello World!'
asyncio.run(bot.send_message(chatId=chat_id, text=message))
© www.soinside.com 2019 - 2024. All rights reserved.