def final_or_make_changes_to_bill(bot, update):
user_choice_make_changes = update.message.text
if user_choice_make_changes == "Yes":
reply_keyboard = [["Add","Delete"]]
message = "Do you want to add or delete?"
bot.send_message(chat_id=update.message.chat_id, text=message, reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
return ADD_OR_DELETE
return STOP
По некоторым причинам состояние STOP
в моем коде никогда не достигается.Я пробовал другие состояния, и ни одно из них не достигнуто.Я попытался заменить оператор возврата в условии if
на STOP
, чтобы проверить, не возникла ли проблема с состоянием.Но, похоже, он работает нормально, и состояние достигается через блок операторов if.
Это функция для состояния STOP
.
def stop(bot, update):
print("ht")
bot.send_message(chat_id=update.message.chat_id,text="dsfdsfsadf")
return ConversationHandler.END
Вот весь код.
<code>import os
import logging
from DBHelper import DBHelper
from telegram.ext import Updater,CommandHandler,MessageHandler,ConversationHandler,Filters
from telegram import ReplyKeyboardMarkup
from random import randint
TOKEN = ""
db = DBHelper()
ADD_ITEMS, FINAL_OR_MAKE_CHANGES, ADD_OR_DELETE, DELETE, STOP = range(5)
bill_items = []
ID = None
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def start(bot, update):
message = "Welcome to the Bill Splitter Bot. An easy way to split bills among friends. The following are a list of"
+ "commands you can use."
bot.send_message(chat_id=update.message.chat_id, text=message)
message = ""
message += "/help - To get a list of commands\n"
message += "/create - To create a new bill\n"
message += "/add - To add items spent on for a particular bill"
message += "/get - To get the amount owed"
def create(bot, update):
global ID
message = "Hey! Looks like you're trying to create a new bill! One moment, while I create a new ID for you!"
bot.send_message(chat_id=update.message.chat_id, text=message)
id_for_bill = randint(1000,9999)
# Check if bill id does not exist in database
message = "Here's the ID for your bill: " + str(id_for_bill)
ID = id_for_bill
print(ID)
bot.send_message(chat_id=update.message.chat_id, text=message)
message = "Can you enter the items followed by the price for the bill? A simple format would look as follows. Type "
message += "Done when you're done adding items to the bill\n"
bot.send_message(chat_id=update.message.chat_id, text=message)
message = " <pre>Pizza - 150\n"
message += "Pasta - 150\n"
message += "Garlic Bread - 230
"reply_keyboard = [[" Done "]] bot.send_message(chat_id = update.message.chat_id, text = message, parse_mode = "html") вернуть ADD_ITEMS def add_items_to_bill (бот, обновление): user_input_bill_items = update.message.text # Использовать регулярное выражение, если user_input_bill_items == "Done": message =Похоже, вы сделали!Вот ваш счет для повторного подтверждения: "item_count = 0 для элемента в bill_items: item_count + = 1 message + ="
" + str(item_count) + ". " + str(item) + "\n
"bot.send_message (chat_id = update.message.chat_id, text = message, parse_mode =" html ") message = "Хотите ли вы внести какие-либо изменения в счет?" reply_keyboard = [["Yes", "No"]] bot.send_message (chat_id = update.message.chat_id, text = message, reply_markup = ReplyKeyboardMarkup (reply_keyboard, one_time_keyboard = True)) возвращать FINAL_OR_MAKE_CHANGES bill_items.append (user_input_bill_items) возвращать ADD_ITEMS def final_or_make_changes_to_bill (бот, обновлять): user_choice_make_changes = update.message.text if user_choice__set_key_keke_keke_keke_keys_key_make_make =]] message = «Хотите добавить или удалить?» bot.send_message (chat_id = update.message.chat_id, text = message, reply_markup = ReplyKeyboardMarkup (reply_keyboard, one_time_keyboard = True)) return ADD_OR_DELETE вернуть STOP def add_or_delete (бот,обновление): user_choice_add_or_delete = update.message.text если user_choice_add_or_delete ==«Добавить»: message = «Введите элементы, которые вы хотите добавить.» Bot.send_message (chat_id = update.message.chat_id, text = message) return ADD_ITEMS message = "Введите номер списка элемента, который вы хотите удалить.Когда вы закончите, введите Готово. "Bot.send_message (chat_id = update.message.chat_id, text = message) вернуть DELETE def delete_item_from_bill (бот, обновление): number_to_delete = update.message.text print (number_to_delete) # SQL-команда дляудалить из таблицы print ("быть заполненным") return STOP def stop (бот, обновление): print ("ht") bot.send_message (chat_id = update.message.chat_id, text = "dsfdsfsadf") return ConversationHandler.END #def done (bot, update): # global ID # bot.send_message (chat_id = update.message.chat_id, text = "done") # print ("done") # message = "Отлично!Поделитесь этим идентификатором с другими участниками счета: "# bot.send_message (chat_id = update.message.chat_id, text = message) # return ConversationHandler.END def cancel (бот, обновление): print (" cancel ") return ConversationHandler.END def add_bought_items (bot, update): message = "Добавить список элементов, соответствующих этому примеру.За биллом следует идентификатор \ nEg: 4632 1,2,3 "bot.send_message (chat_id = update.message.chat_id, text = message) def error (bot, update, error):" "" Журнал ошибок, вызванных обновлениями. """ logger.warning ('Обновление "% s" вызвало ошибку "% s"', update, update.error) def main (): Updater = Updater (TOKEN) db.setup () PORT = int (os.environ.get ('PORT', '8443')) dp = updater.dispatcher dp.add_handler (CommandHandler ("help", start)) create_conversation_handler = ConversationHandler (entry_points = [CommandHandler ('create', create)], состояния = {#GET_BILL_DETAILS: [MessageHandler (Filters.text, get_bill_details)], ADD_ITEMS: [MessageHandler (Filters.text, add_items_to_bill)], FINAL_OR_MAKE_CHANGES: [MessageHandler (Filters.text, final_or_to_ill_make_)ADD_OR_DELETE: [MessageHandler (Filters.text, add_or_delete)], DELETE: [MessageHandler (Filters.text, delete_item_from_bill)], STOP: [MessageHandler (Filters.text, stop)]}, отступления = [CommandHandler ('отменить', отменить))]) dp.add_handler (create_conversation_handler) dp.add_error_handler (ошибка) dp.add_handler (CommandHandler («add», add_bought_items)) # dp.add_handler (CommandHandler («add», add))) updater.start_polling () if= "__main__": main ()