2017-05-18 133 views
3

我正在python上建立一些电报机器人(使用此框架pyTelegramBotAPI)。我遇到了用户输入的问题。我需要在某些机器人消息后保存用户输入(可以是任何文本)。例如:保存用户输入后,某些消息电报机器人

机器人: - 请描述您的问题。

用户: - 我们的电脑无法使用。

然后,我需要将此文字“我们的计算机不工作”保存到某个变量,然后转到下一步。 这里是我的代码:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import telebot 
import constants 
from telebot import types 

bot = telebot.TeleBot(constants.token) 

@bot.message_handler(commands=['start']) 
def handle_start(message): 
    keyboard = types.InlineKeyboardMarkup() 
    callback_button = types.InlineKeyboardButton(text="Help me!", callback_data="start") 
    keyboard.add(callback_button) 
    bot.send_message(message.chat.id, "Welcome I am helper bot!", reply_markup=keyboard) 



@bot.inline_handler(lambda query: len(query.query) > 0) 
def query_text(query): 
    kb = types.InlineKeyboardMarkup() 
    kb.add(types.InlineKeyboardButton(text="Help me!", callback_data="start")) 
    results = [] 
    single_msg = types.InlineQueryResultArticle(
     id="1", title="Press me", 
     input_message_content=types.InputTextMessageContent(message_text="Welcome I am helper bot!"), 
     reply_markup=kb 
    ) 
    results.append(single_msg) 
    bot.answer_inline_query(query.id, results) 

@bot.callback_query_handler(func=lambda call: True) 
def callback_inline(call): 
    if call.message: 
     if call.data == "start": 
      bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Please describe your problem.") 
      #here I need wait for user text response, save it and go to the next step 

我有在语句中使用MESSAGE_ID的想法,但仍然无法实现它。我如何解决这个问题?有任何想法吗?谢谢。

回答

2

它不是一个python甚至程序设计相关的问题。它更像是设计问题。但不管怎么说。 解决方案为用户保留会话。例如用户发送给您:

我们的电脑无法正常工作。

首先你为这个用户创建一个会话(身份应该是一个用户ID),然后给他/她发送一个适当的消息。当用户首先发送下一条消息时,请查看用户状态并查看他/她是否有会话。如果他/她有会话,则继续第二步。我开发这样一个机器人,并使用字典为了存储用户会话。但它使一切都变得复杂。

0

您应该将数据保存在缓存或数据库中。

0

您可以使用Forcereply。 一旦收到带有这个对象的消息,电报客户端就会向用户显示一个回复界面(就好像用户已经选择了机器人的消息并点击'回复'一样)。如果您想创建用户友好的逐步界面而不必牺牲隐私模式,这可能非常有用。 https://core.telegram.org/bots/api#forcereply

0

这将帮助你 https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/step_example.py

import telebot 
import constants 
from telebot import types 

bot = telebot.TeleBot(constants.token) 

@bot.message_handler(commands=['start']) 
def start(message): 
    sent = bot.send_message(message.chat.id, 'Please describe your problem.') 
    bot.register_next_step_handler(sent, hello) 

def hello(message): 
    open('problem.txt', 'w').write(message.chat.id + ' | ' + message.text + '||') 
    bot.send_message(message.chat.id, 'Thank you!') 
    bot.send_message(ADMIN_ID, message.chat.id + ' | ' + message.text) 

bot.polling() 
相关问题