RuntimeWarning:启用tracemalloc以获取对象分配回溯 - 不使用异步

And*_*y B 3 python telegram

我有一段代码来测试我的电报机器人的实现是否在 python 中工作。它在我的 Windows 11 笔记本电脑上运行完全正常,但当我在 Windows 2019 服务器上运行它时,我得到以下输出:

c:\Python\Scripts\telegram_test.py:11: RuntimeWarning: 协程 'Bot.send_message' 从未等待 bot.sendMessage(chat_id=chat_id, text=msg) RuntimeWarning: 启用tracemalloc 以获取对象分配回溯消息已发送!

两个安装都使用 python 3.9.0,并且我已确认它们都使用 telegram 0.0.1,因此错误有点令人困惑。我也不在代码中使用异步,如下所示:

import telegram

my_token = 'blahblahblah'

def send(msg, chat_id, token=my_token):
    """
    Send a message to a telegram user or group specified on chatId
    chat_id must be a number!
    """
    bot = telegram.Bot(token=token)
    bot.sendMessage(chat_id=chat_id, text=msg)
    print('Message Sent!')


MessageString = 'Testing from virtual server'
print(MessageString)
send(MessageString, '-blahblah', my_token ) 
Run Code Online (Sandbox Code Playgroud)

代码实际上没有任何内容,每次在我的笔记本电脑上它都 100% 有效,所以我不知道有什么区别。有什么想法吗?

And*_*y B 6

好的,多亏了这篇文章,我才可以使用它:

Telethon 导致“RuntimeWarning:协程‘MessageMethods.send_message’从未等待过”

我不知道为什么它之前不起作用,但修改代码如下后,它起作用了:

import telegram
import asyncio

my_token = 'blahblahblah'
my_chat_id = -123456789

async def send(msg, chat_id, token=my_token):
    """
    Send a message "msg" to a telegram user or group specified by "chat_id"
    msg         [str]: Text of the message to be sent. Max 4096 characters after entities parsing.
    chat_id [int/str]: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
    token       [str]: Bot's unique authentication token.
    """
    bot = telegram.Bot(token=token)
    await bot.sendMessage(chat_id=chat_id, text=msg)
    print('Message Sent!')


MessageString = 'Testing from virtual server'
print(MessageString)
asyncio.run(send(msg=MessageString, chat_id=my_chat_id, token=my_token))
Run Code Online (Sandbox Code Playgroud)

  • @RobertAlexander **1:** `token` [预计是一个字符串](https://docs.python-telegram-bot.org/en/stable/telegram.bot.html#telegram.Bot),而`chat_id` 可以是[整数或字符串](https://docs.python-telegram-bot.org/en/stable/telegram.bot.html#telegram.Bot.send_message)。**2:** 第一个字符串“-blahblahblah”是(无效的)“chat_id”。在这个例子中,“chat_id”和“my_token”恰好重合。我将在上面的答案中提出解决方案。 (2认同)