我正在寻找一种让机器人在命令后等待用户回复的方法。例如,您首先输入“/ask”,然后机器人等待来自用户的普通消息(不是命令),并在用户回复后将他/她的回复存储在一个变量中
我相信这很简单,但是我看到的所有教程都是俄语的,python-telegram-api 的文档非常混乱,我不是最先进的 如果我笨,对不起,请帮助初学者
答案 0 :(得分:0)
这是接受用户输入并将其存储在“store_user_input”变量中的代码。
import logging
from telegram.ext import Updater,
CommandHandler, MessageHandler, Filters,
CallbackContext
from telegram import Update
logging.basicConfig(
format='%(asctime)s - %(name)s - %
(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# function to handle the /start command
def startcommand(update:Update, context:
CallbackContext) -> None:
first_name = update.message.chat.first_name
update.message.reply_text\
(
f'Welcome to the bot, {first_name},
what are you interested in?'
)
# function to handle and store user input
def text(update:Update, context:
CallbackContext) -> None:
text_received = update.message.text
store_user_input = text_received
# function to handle the /help command
def helpcommand(update:Update, context:
CallbackContext) -> None:
update.message.reply_text('Here is a list of
all available commands:\n '
'/start - start the
bot\n'
'/help - get all
available commands\n')
# function to handle errors occured in the
dispatcher
def errormsg(update:Update, context:
CallbackContext) -> None:
update.message.reply_text('An error
occured.')
# main function
def main():
# "bot_data is your .txt file with bot API token"
fo = open("bot_data")
fr = fo.read()
updater = Updater(fr)
dispatcher = updater.dispatcher
# add handlers for start and help commands
dispatcher.add_handler(CommandHandler("start", startcommand))
dispatcher.add_handler(CommandHandler("help", helpcommand))
# add an handler for normal text (not commands)
dispatcher.add_handler(MessageHandler(Filters.text, text))
# add an handler for errors
dispatcher.add_error_handler(errormsg)
# start bot
updater.start_polling()
# run the bot
updater.idle()
if __name__ == '__main__':
main()
您可以通过添加来检查该值:
print("store_user_input")
在 store_user_input 行之后。
答案 1 :(得分:0)
好吧,这毫无意义。我以为你不能使用参数,但我读的帖子是 5 岁所以......我很愚蠢。我只是用参数代替,谢谢你的帮助,真的很感激