python-telegram-bot/examples/state_machine_bot.py

101 lines
3.7 KiB
Python
Raw Normal View History

2016-03-21 20:08:32 +01:00
#!/usr/bin/env python
2016-03-22 02:33:43 +01:00
# -*- coding: utf-8 -*-
#
2016-03-21 20:08:32 +01:00
# Basic example for a bot that awaits an answer from the user
# This program is dedicated to the public domain under the CC0 license.
import logging
2016-04-16 19:25:08 +02:00
from telegram import Emoji, ForceReply, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
2016-03-21 20:08:32 +01:00
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
2016-03-21 20:08:32 +01:00
level=logging.INFO)
# Define the different states a chat can be in
MENU, AWAIT_CONFIRMATION, AWAIT_INPUT = range(3)
# Python 2 and 3 unicode differences
try:
YES, NO = (Emoji.THUMBS_UP_SIGN.decode('utf-8'), Emoji.THUMBS_DOWN_SIGN.decode('utf-8'))
2016-03-21 20:08:32 +01:00
except AttributeError:
YES, NO = (Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN)
# States are saved in a dict that maps chat_id -> state
state = dict()
# Sometimes you need to save data temporarily
context = dict()
# This dict is used to store the settings value for the chat.
# Usually, you'd use persistence for this (e.g. sqlite).
values = dict()
# Example handler. Will be called on the /set command and on regular messages
def set_value(bot, update):
chat_id = update.message.chat_id
user_id = update.message.from_user.id
text = update.message.text
chat_state = state.get(chat_id, MENU)
chat_context = context.get(chat_id, None)
# Since the handler will also be called on messages, we need to check if
# the message is actually a command
if chat_state == MENU and text[0] == '/':
state[chat_id] = AWAIT_INPUT # set the state
context[chat_id] = user_id # save the user id to context
bot.sendMessage(chat_id,
text="Please enter your settings value or send "
"/cancel to abort",
2016-03-21 20:08:32 +01:00
reply_markup=ForceReply())
# If we are waiting for input and the right user answered
elif chat_state == AWAIT_INPUT and chat_context == user_id:
state[chat_id] = AWAIT_CONFIRMATION
# Save the user id and the answer to context
context[chat_id] = (user_id, update.message.text)
2016-04-16 19:25:08 +02:00
reply_markup = ReplyKeyboardMarkup(
[[KeyboardButton(YES), KeyboardButton(NO)]],
one_time_keyboard=True)
bot.sendMessage(chat_id, text="Are you sure?", reply_markup=reply_markup)
2016-03-21 20:08:32 +01:00
# If we are waiting for confirmation and the right user answered
elif chat_state == AWAIT_CONFIRMATION and chat_context[0] == user_id:
2016-04-16 19:25:08 +02:00
del state[chat_id]
del context[chat_id]
2016-03-21 20:08:32 +01:00
if text == YES:
values[chat_id] = chat_context[1]
bot.sendMessage(chat_id, text="Changed value to %s." % values[chat_id])
2016-03-21 20:08:32 +01:00
else:
bot.sendMessage(chat_id,
text="Value not changed: %s." % values.get(chat_id, '<not set>'))
2016-03-21 20:08:32 +01:00
# Handler for the /cancel command.
# Sets the state back to MENU and clears the context
def cancel(bot, update):
chat_id = update.message.chat_id
2016-04-16 19:25:08 +02:00
del state[chat_id]
del context[chat_id]
2016-03-21 20:08:32 +01:00
def help(bot, update):
bot.sendMessage(update.message.chat_id, text="Use /set to test this bot.")
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
# The command
updater.dispatcher.add_handler(CommandHandler('set', set_value))
2016-03-21 20:08:32 +01:00
# The answer and confirmation
updater.dispatcher.add_handler(MessageHandler([Filters.text], set_value))
updater.dispatcher.add_handler(CommandHandler('cancel', cancel))
updater.dispatcher.add_handler(CommandHandler('start', help))
updater.dispatcher.add_handler(CommandHandler('help', help))
2016-03-21 20:08:32 +01:00
# Start the Bot
updater.start_polling()
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT
updater.idle()