Skip to main content
 首页 » 编程设计

python之电报机器人 : Custom Keyboard [Python]

2025年05月04日14开发

我已经下载了这个 open-source code来自用 Python 编写的 GitHub(我对它很陌生),我想让我的机器人有一个自定义键盘,而不是让用户说出他们想要的任何东西。例如,如果用户开始与我的机器人聊天,他们将自动发送 /start 并且当发生这种情况时,我希望我的机器人给他们两到三个选项 ['Option One'], [选项二], 在键盘上,当他们选择其中一个选项时,我希望有完全不同的选项(例如 ['Plan A'], ['Plan B'], ).当他们再次选择其中之一时,他们的键盘上会出现不同的选项,依此类推。

class WebhookHandler(webapp2.RequestHandler): 
def post(self): 
    urlfetch.set_default_fetch_deadline(60) 
    body = json.loads(self.request.body) 
    logging.info('request body:') 
    logging.info(body) 
    self.response.write(json.dumps(body)) 
 
    update_id = body['update_id'] 
    try: 
        message = body['message'] 
    except: 
        message = body['edited_message'] 
    message_id = message.get('message_id') 
    date = message.get('date') 
    text = message.get('text') 
    fr = message.get('from') 
    chat = message['chat'] 
    chat_id = chat['id'] 
 
    if not text: 
        logging.info('no text') 
        return 
 
    def reply(msg=None, img=None): 
        if msg: 
            resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({ 
                'chat_id': str(chat_id), 
                'text': msg.encode('utf-8'), 
                'disable_web_page_preview': 'true', 
            })).read() 
 
        else: 
            logging.error('no msg or img specified') 
            resp = None 
 
        logging.info('send response:') 
        logging.info(resp) 
 
    if text.startswith('/'): 
        if text == '/start': 
            reply('Bot enabled') 
            setEnabled(chat_id, True) 
        elif text == '/stop': 
            reply('Bot disabled') 
            setEnabled(chat_id, False) 
 
        else: 
            reply('That ain\'t been coded yet.') 

正如我所说的,我是 Pyhton 的处女,如果你将你的代码应用于本文上方的代码,而不是给我想法(我不知道如何使用它们,我将非常感激,并完成工作!)。

请您参考如下方法:

首先,我建议您使用一些模块来处理它。由于您是新手,python-telegram-bot可以帮助你。

好吧,假设你会使用它,你有两个选择:

  1. 您可以创建一个键盘,其中的选项是命令。

    def start(bot, update): 
        kb = [[telegram.KeyboardButton('/command1')], 
              [telegram.KeyboardButton('/command2')]] 
        kb_markup = telegram.ReplyKeyboardMarkup(kb) 
        bot.send_message(chat_id=update.message.chat_id, 
                         text="your message", 
                         reply_markup=kb_markup) 
     
    start_handler = CommandHandler('start', start) 
    dispatcher.add_handler(start_handler) 
    
  2. 创建文本选项并使用正则表达式过滤它们。

    def start(bot, update): 
        kb = [[telegram.KeyboardButton("Option 1")], 
              [telegram.KeyboardButton("Option 2")]] 
        kb_markup = telegram(chat_id=update.message.chat_id, 
                             text="your message", 
                             reply_markup=kb_markup) 
     
    start_handler = RegexHandler('some-regex-here', start) 
    dispatcher.add_handler(start_handler) 
    

但是,您不能阻止用户发送他想要的任何其他消息。您只能忽略消息并仅回复命令或键盘响应。