1

I want the bot to display the "typing..." action, i found other discussions about this topic, but not about this library, so if it's possible it would be so much helpful, thanks in advance.

i found this code

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()

and the error is "error "name 'bot' is not defined" obviously, but the question is, how can i create bot object without conflict with the updater? help

raxp122
  • 13
  • 5

1 Answers1

2

You should use context.bot instead of just bot in your callback functions. Since version 12 of python-telegram-bot, they have added context-based callback. The bot object is now under context. To see what other objects context holds, check their documentation for callback context.

Here is a fixed version for your code:

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()
  • Nice answer. It's also possible to [create a decorator](https://stackoverflow.com/a/61520787/2052575) to assign the typing action to any handler. – v25 Sep 22 '20 at 14:30
  • Yes. Decorator is a really nice approach for sending chat action. The wiki of python telegram bot has a really nice code snippet for that, [send-a-chat-action](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Code-snippets#send-a-chat-action) – Shivam Saini Sep 22 '20 at 14:35