Save user input after certain message telegram bot

user3151148 picture user3151148 · May 18, 2017 · Viewed 15k times · Source

I am building some telegram bot on python (using this framework pyTelegramBotAPI). And I ran into the problem with user input. I need save user input(it can be any text) after certain bot's message. For example:

Bot: - Please describe your problem.

User: - Our computer doesn't work.

Then I need to save this text "Our computer doesn't work" to some variable and go to the next step. Here's my code:

#!/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

I have the idea with using message_id in statement, but still can't implement it. How I can solve this? Any ideas? Thank you.

Answer

Nematillo Ochilov picture Nematillo Ochilov · Aug 25, 2017

This will help you 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()