我正在用python3和python-telegram-bot编写一个python机器人,我希望它在发送消息之前显示“正在输入...”

问题描述

我希望该机器人显示“ typing ...”动作,我发现了有关该主题的其他讨论,但没有关于此库的讨论,因此,如果有可能,它将很有帮助,在此先感谢。

我找到了这段代码

import logging
from telegram import *
from telegram.ext import *

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
logger = logging.getLogger(__name__)


def message(update,context):
    bot.sendChatAction(chat_id=update.message.chat_id,action = telegram.ChatAction.TYPING)

    sleep(random() * 2 + 3.)

    bot.sendMessage(chat_id=update.message.chat_id,text="Hi")


def error(update,context):
    logger.warning('Update "%s" caused error "%s"',update,context.error)


def main():
    updater = Updater("token",use_context=True)
    dp = updater.dispatcher
    dp.add_handler(MessageHandler(Filters.text,message))
    dp.add_error_handler(error)
    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()

错误显然是“错误名称“ bot”未定义”,但问题是,如何创建与更新程序不冲突的bot对象?帮助

解决方法

您应该在回调函数中使用context.bot而不是bot。从python-telegram-bot版本12开始,他们添加了基于上下文的回调。 bot对象现在位于context下。要查看context还拥有哪些其他对象,请检查their documentation for callback context.

这是您代码的固定版本:

import logging
from telegram import *
from telegram.ext import *

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
logger = logging.getLogger(__name__)

from time import sleep  #You need to import sleep to be able to use that.
from random import random  #You must also import random since you are using that.

def message(update,context):
    context.bot.sendChatAction(chat_id=update.message.chat_id,action = telegram.ChatAction.TYPING)

    sleep(random() * 2 + 3.)

    context.bot.sendMessage(chat_id=update.message.chat_id,text="Hi")


def error(update,context):
    logger.warning('Update "%s" caused error "%s"',update,context.error)


def main():
    updater = Updater("token",use_context=True)
    dp = updater.dispatcher
    dp.add_handler(MessageHandler(Filters.text,message))
    dp.add_error_handler(error)
    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()