使用 Telebot 停止 Telegram 机器人回调时出错

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

我正在使用 Python 中的 Telebot 库开发 Telegram 机器人。该机器人有一个主菜单,其中包含两个命令:/cep 和 /person。使用/cep命令时,用户必须输入邮政编码才能获取相关信息。处理邮政编码后,机器人会显示详细信息并提供“主菜单”按钮以返回主屏幕,这相当于 /start 命令。

当我在查询邮政编码后尝试使用“主菜单”按钮时,就会出现问题。与按钮关联的回调不会中断流程并返回欢迎消息。它卡在 process_cep_input 函数中,导致出现不需要的行为。

import telebot
import requests, json
from telebot import types

TELEGRAM_BOT_TOKEN = 'SECRET_TOKEN'
bot = telebot.TeleBot(token=TELEGRAM_BOT_TOKEN, parse_mode='HTML')

@bot.message_handler(commands=['start'])
def handler_start(message):
  welcome_message = (
    f'Olá {message.from_user.first_name}. Tudo bem?\n\n'
    'Veja o que posso fazer por você:\n'
    '1. /cep - Consultar informações de um CEP\n'
    '2. /pessoa - Gerar uma pessoa fictícia com IA\n\n'
    'Escreva abaixo o comando que deseja utilizar ou clique diretamente acima.'
  )
  bot.send_message(chat_id=message.from_user.id, text=welcome_message)

@bot.message_handler(commands=['cep'])
def handler_cep(message):
    bot.send_message(chat_id=message.from_user.id, text='Legal, vamos consultar um CEP.\n\nPor favor, digite o CEP que você deseja consultar informando <u><b>apenas números</b></u>, conforme o exemplo: <i>XXXXXXXX</i>')

@bot.message_handler(commands=['cep'])
def process_cep_input(message):
  try:
    cep_solicitado = int(message.text)
    url_api = f'https://viacep.com.br/ws/{cep_solicitado}/json/'
    request = requests.get(url_api)

    if request.status_code == 200:
      dicionario = json.loads(request.content.decode('utf-8'))
      mensagem = 'Essas são as informações do CEP solicitado! \n\nCEP: {}\nLogradouro: {}\nBairro: {}\nCidade: {}\nEstado: {}\nDDD da Região: {}\n\nInforme outro CEP para uma nova busca ou volte ao menu anterior.'
      markup = types.InlineKeyboardMarkup()
      markup.add(
        types.InlineKeyboardButton('Menu Principal', callback_data='/chatbot main menu')
      )
      bot.send_chat_action(chat_id=message.from_user.id, action='typing')
      bot.send_message(chat_id=message.from_user.id, text=mensagem.format(dicionario['cep'], dicionario['logradouro'], dicionario['bairro'], dicionario['localidade'], dicionario['uf'], dicionario['ddd']), reply_to_message_id=message.message_id, reply_markup=markup)
      bot.register_next_step_handler(message, process_cep_input)

    else:
      bot.send_message(chat_id=message.from_user.id, text='🚫 Dados incorretos. Por favor, informe um CEP válido.', reply_to_message_id=message.message_id)
      bot.register_next_step_handler(message, process_cep_input)

  except:
    bot.send_message(chat_id=message.from_user.id, text='🚫 Dados incorretos. Por favor, informe um CEP válido.', reply_to_message_id=message.message_id)
    bot.register_next_step_handler(message, process_cep_input)

@bot.callback_query_handler(func=lambda call: True)
def callback_handler(call):
  if call.data == '/chatbot main menu':
     handler_start(call)

试图中断

/chatbot main_menu
回调并返回主菜单。我使用
callback_handler
函数来处理回调,并尝试调用其中的
handler_start
函数来发送欢迎消息并重新启动用户交互。然而,这并没有按预期工作。我期望收到的是成功的回调中断以及机器人主菜单中与
/start
命令相关的欢迎消息的转换。我正在寻求有关如何解决此问题并有效停止 Telebot 中的回调的指导。

python callback telegram telegram-bot python-telegram-bot
1个回答
0
投票

您说 Button 有问题,但我测试了所有代码,有很多错误(因此代码无法运行),只有 Button 工作正常。所以我不明白你的问题。

但是我放了我用来测试问题的完整工作代码。

import telebot
import requests, json
from telebot import types
import os

import logging
telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console.

#TELEGRAM_BOT_TOKEN = 'SECRET_TOKEN'
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_TOKEN')

bot = telebot.TeleBot(token=TELEGRAM_BOT_TOKEN, parse_mode='HTML')

@bot.message_handler(commands=['start'])
def handler_start(message):
    welcome_message = (
        f'Olá {message.from_user.first_name}. Tudo bem?\n\n'
        'Veja o que posso fazer por você:\n'
        '1. /cep - Consultar informações de um CEP\n'
        '2. /pessoa - Gerar uma pessoa fictícia com IA\n\n'
        'Escreva abaixo o comando que deseja utilizar ou clique diretamente acima.'
    )
    bot.send_message(chat_id=message.from_user.id, text=welcome_message)

@bot.message_handler(commands=['cep'])
def process_cep_input(message):
    print('[DEBUG]: process_cep_input()')

    try:
        print('[DEBUG] message.text:', message.text)
        
        # `message.text` is `/cep 0100100` and it needs to remove `/cep` 
        items = message.text.split()
        
        if len(items) < 2 and items[0] == '/cep':
            bot.send_message(chat_id=message.from_user.id, text="it needs code - ie. 0100100")
            bot.register_next_step_handler(message, process_cep_input)
            return
            
        cep_solicitado = items[-1]  # get last element without converting to `int`

        url_api = f'https://viacep.com.br/ws/{cep_solicitado}/json/'
        print('[DEBUG] url_api:', url_api)

        #headers = {
        #    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:98.0) Gecko/20100101 Firefox/98.0',
        #}
        response = requests.get(url_api) #, headers=headers)
        print('[DEBUG] response.status_code:', response.status_code)
        print('[DEBUG] response.text:', response.text)

        if response.status_code == 200:
            print('[DEBUG]: STATUS OK')
            #dicionario = json.loads(request.content.decode('utf-8'))
            dicionario = response.json()
            
            mensagem = 'Essas são as informações do CEP solicitado! \n\nCEP: {}\nLogradouro: {}\nBairro: {}\nCidade: {}\nEstado: {}\nDDD da Região: {}\n\nInforme outro CEP para uma nova busca ou volte ao menu anterior.'
            markup = types.InlineKeyboardMarkup()
            markup.add(
                types.InlineKeyboardButton('Menu Principal', callback_data='/chatbot main menu')
            )
            bot.send_chat_action(chat_id=message.from_user.id, action='typing')
            bot.send_message(chat_id=message.from_user.id, text=mensagem.format(dicionario['cep'], dicionario['logradouro'], dicionario['bairro'], dicionario['localidade'], dicionario['uf'], dicionario['ddd']), reply_to_message_id=message.message_id, reply_markup=markup)
            #bot.register_next_step_handler(message, process_cep_input)       # it seems it doesn't use it 
            #bot.register_next_step_handler(message, callback_handler)        # it seems it doesn't use it 
            #bot.register_next_step_handler(message, other_callback_handler)  # it seems it doesn't use it 
            
        else:
            bot.send_message(chat_id=message.from_user.id, text='🚫 Dados incorretos. Por favor, informe um CEP válido.', reply_to_message_id=message.message_id)
            bot.register_next_step_handler(message, process_cep_input)

    except Exception as ex:
        print('[DEBUG] Exception:', ex)
        bot.send_message(chat_id=message.from_user.id, text='🚫 Dados incorretos. Por favor, informe um CEP válido.', reply_to_message_id=message.message_id)
        bot.register_next_step_handler(message, process_cep_input)

def other(message):
    print('[DEBUG] other message:', message)
    
@bot.callback_query_handler(func=lambda call: call.data == '/chatbot main menu')
def other_callback_handler(call):
    #print('[DEBUG] other_callback_handler:', dir(call))
    print('[DEBUG] other_callback_handler:', call.data)
    #print('[DEBUG] other_callback_handler:', call.message)
    
    handler_start(call)     
         
@bot.callback_query_handler(func=lambda call: True)
def callback_handler(call):
    #print('[DEBUG] callback_handler:', dir(call))
    print('[DEBUG] callback_handler:', call.data)
    #print('[DEBUG] callback_handler:', call.message)
    
    if call.data == '/chatbot main menu':
        handler_start(call)     

if __name__ == '__main__':        
    bot.infinity_polling()
© www.soinside.com 2019 - 2024. All rights reserved.