如何使用 telethon bot api 主动发送消息?

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

我正在通过向演示频道发送“机器人”来测试机器人:

bot = TelegramClient(
    Path("tgapi.bot.session"),
    config.api_id,
    config.api_hash
)
bot.start(bot_token=config.bot_token)


async def bot_main():
    await bot.send_message(config.demo, "bot")


if __name__ == "__main__":
    asyncio.run(bot_main())

但是当我运行时,它只是输出一堆错误:

Traceback (most recent call last):
  File "/home/trdthg/repo/tgapi/tgapi-py/demo.py", line 20, in <module>
    asyncio.run(bot_main())
  File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/home/trdthg/repo/tgapi/tgapi-py/demo.py", line 16, in bot_main
    await bot.send_message(config.demo, "bot")
  File "/home/trdthg/repo/tgapi/tgapi-py/.venv/lib/python3.10/site-packages/telethon/client/messages.py", line 905, in send_message
    result = await self(request)
  File "/home/trdthg/repo/tgapi/tgapi-py/.venv/lib/python3.10/site-packages/telethon/client/users.py", line 30, in __call__
    return await self._call(self._sender, request, ordered=ordered)
  File "/home/trdthg/repo/tgapi/tgapi-py/.venv/lib/python3.10/site-packages/telethon/client/users.py", line 34, in _call
    raise RuntimeError('The asyncio event loop must not change after connection (see the FAQ for details)')
RuntimeError: The asyncio event loop must not change after connection (see the FAQ for details)
Task was destroyed but it is pending!

...

所以bot无法主动发送消息?

telethon
1个回答
0
投票

问题是

asyncio.run
创建了一个新的异步事件循环。但是,您在此之前已经调用了
.start()
,它使用了 different 事件循环。

正如您所指出的,可以将

.start()
移动到
async def
内部,以便它使用相同的循环,或者使用
client.loop.run_until_complete
而不是
asyncio.run
来使用默认循环。

© www.soinside.com 2019 - 2024. All rights reserved.