如何增加pyTelegramBotApi中send_action的运行时间?

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

我想怎么做:调度操作,如何结束文件发送。但事实证明,该动作持续了 5 秒,然后又花了 5 秒来发送文件,而这次用户不明白是机器人被冻结还是文件仍在发送。在直接发送文件之前如何增加操作持续时间?

import telebot
...
def send_file(m: Message, file):
    bot.send_chat_action(m.chat.id, action='upload_document')
    bot.send_document(m.chat.id, file)
python telegram telegram-bot py-telegram-bot-api
2个回答
1
投票

作为Tibebes。 M 表示这是不可能的,因为所有操作都是通过 API 发送的。但线程帮助我解决了这个问题。解决方案如下所示:

from threading import Thread
def send_action(id, ac):
    bot.send_chat_action(id, action=ac)

def send_doc(id, f):
    bot.send_document(id, f)

def send_file(m: Message):
    file = open(...)
    Thread(target=send_action, args=(m.chat.id, 'upload_document')).start()
    Thread(target=send_doc, args=(m.chat.id, file)).start()
...
send_file(m)

因此,可以做到操作一结束,就立即发送文件,没有时间间隔


0
投票

如果使用这些函数的异步版本,我们应该这样做:

async def keep_typing_while(chat_id, func):
    cancel = { 'cancel': False }

    async def keep_typing():
        while not cancel['cancel']:
            await bot.send_chat_action(chat_id, 'typing')
            await asyncio.sleep(5)

    async def executor():
        await func()
        cancel['cancel'] = True

    await asyncio.gather(
        keep_typing(),
        executor(),
    )

并这样称呼它:

answer = {}

async def openai_caller():
    local_answer = await get_openai_completion(user_context.get_messages())
    answer['role'] = local_answer['role']
    answer['content'] = local_answer['content']

await keep_typing_while(message.chat.id, openai_caller)
© www.soinside.com 2019 - 2024. All rights reserved.