I am developing a telegram bot with FSM. It is should've chat-bot for ordering pizza. The conversation should be like this:
What kind of pizza do you want? Big or small?
Great
How will you pay?
In cash
Do you want a big pizza, cash payment?
Yes
Thank you for the order
I've come with this code:
bot.py
import telebot
import config
import FSM
from telebot import types
bot = telebot.TeleBot(config.TOKEN)
fsm = FSM.TelegramBot()
#bot.message_handler(commands=['start'])
def welcome(message):
#keyboard
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Заказать пиццу")
item2 = types.KeyboardButton("Посмотреть меню")
markup.add(item1, item2)
bot.send_message(message.chat.id,
"Добро пожаловать, {0.first_name}!\nЯ - <b>{1.first_name}</b> бот, я помогу вам "
"сделать заказ.".format(
message.from_user, bot.get_me()),
parse_mode='html', reply_markup=markup)
#bot.message_handler(content_types=['text'])
#bot.message_handler(func=lambda message: fsm.state == 'asleep')
def order_pizza(message):
bot.send_message(message.chat.id, 'Какую вы хотите пиццу? Большую или маленькую?')
fsm.asked_for_payment_method(message.text)
#bot.message_handler(content_types=['text'])
#bot.message_handler(func=lambda message: fsm.state == 'size_selected')
def choose_size(message):
bot.send_message(message.chat.id, 'Как вы будете платить?')
fsm.asked_for_payment_method(message.text)
#bot.message_handler(content_types=['text'])
#bot.message_handler(func=lambda message: fsm.state == 'payment_selected')
def choose_size(message):
bot.send_message(message.chat.id, 'Какой вкус вы хотите?')
fsm.asked_for_flavour(message.text)
#bot.message_handler(content_types=['text'])
#bot.message_handler(func=lambda message: fsm.state == 'flavour_selected')
def choose_size(message):
markup = types.InlineKeyboardMarkup(row_width=2)
item1 = types.InlineKeyboardButton("Да", callback_data='yes')
item2 = types.InlineKeyboardButton("Нет ", callback_data='no')
markup.add(item1, item2)
bot.send_message(message.chat.id, f'Вы хотите {fsm.size} пиццу {fsm.flavour}, оплата - {fsm.pay_method} ?', reply_markup=markup)
#bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
try:
if call.message:
if call.data == 'yes':
bot.send_message(call.message.chat.id, 'Спасибо за заказ')
fsm.confirmed()
# show alert
bot.answer_callback_query(callback_query_id=call.id, show_alert=True,
text="Заказ оформлен")
elif call.data == 'no':
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Заказать пиццу")
item2 = types.KeyboardButton("Посмотреть меню")
markup.add(item1, item2)
bot.send_message(call.message.chat.id, 'Бывает 😢', reply_markup=markup)
fsm.confirmed()
# remove inline buttons
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=f'Вы хотите {fsm.size} пицца {fsm.flavour}, оплата - {fsm.pay_method} ?',
reply_markup=None)
except Exception as e:
print(repr(e))
# RUN
bot.polling(none_stop=True)
And this code for Finite State Machine. I've used pytransitions
/
transitions
FSM.py
from transitions import Machine, State
class telegram_bot_state(object):
states = ['asleep',
'size_selected',
'payment_selected',
'flavour_selected']
transitions = [
{'trigger': 'asked_size', 'source': 'asleep', 'dest': 'size_selected', 'after': 'update_size'},
{'trigger': 'asked_for_payment_method', 'source': 'size_selected', 'dest': 'payment_selected', 'after': 'update_payment'},
{'trigger': 'asked_for_flavour', 'source': 'payment_selected', 'dest': 'flavour_selected','after': 'update_flavour'},
{'trigger': 'confirmed', 'source': 'flavour_selected', 'dest': 'asleep'}, ]
def __init__(self):
self.size = ''
self.pay_method = ''
self.flavour = ''
self.machine = Machine(model=self, states=TelegramBot.states, transitions=TelegramBot.transitions, initial='asleep')
def update_size(self, msg):
self.size = msg
print(f'размер задан: {self.size}')
def update_payment(self, msg):
self.pay_method = msg
print(f'способ оплаты задан: {self.pay_method}')
def update_flavour(self, msg):
self.flavour = msg
print(f'Вкус пиццы задан: {self.flavour}')
But the problem is it just runs through everything and doesn't wait for the user's answer. Just send all the questins.
p.s. I'm sorry in advance if wrote something wrong this is my first question.
For sequence use method bot.register_next_step_handler_by_chat_id and create functions with your name of this step. I'm hope this answer is helpful
This question is dated but has been viewed quite often. As of September 2022, I'd say that there is no need for transitions when you write a Telegram bot with pyTelegramBotAPI as it contains means for state-based logic and data storage.
There is a custom state example which illustrates how states can be used. I adapted this example for your use case:
import telebot # telebot
from telebot import custom_filters
from telebot.handler_backends import State, StatesGroup #States
# States storage
from telebot.storage import StateMemoryStorage
# Now, you can pass storage to bot.
state_storage = StateMemoryStorage() # you can init here another storage
bot = telebot.TeleBot("<YOUR TOKEN HERE>", state_storage=state_storage)
# States group.
class MyStates(StatesGroup):
# Just name variables differently
size = State() # creating instances of State class is enough from now
payment = State()
confirmation = State()
#bot.message_handler(commands=['order'])
def order(message):
bot.set_state(message.from_user.id, MyStates.size, message.chat.id)
bot.send_message(message.chat.id, 'What size of pizza do you want? Large or small?')
#bot.message_handler(state="*", commands=['cancel'])
def cancel(message):
bot.send_message(message.chat.id, "Your order was cancelled.")
bot.delete_state(message.from_user.id, message.chat.id)
#bot.message_handler(state=MyStates.size)
def get_size(message):
inp = message.text.lower()
if inp not in ["small", "large"]:
bot.send_message(message.chat.id, 'Please enter "large" or "small".')
return
bot.send_message(message.chat.id, 'How will you pay? Cash or paypal?')
bot.set_state(message.from_user.id, MyStates.payment, message.chat.id)
with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
data['size'] = inp
#bot.message_handler(state=MyStates.payment)
def get_payment(message):
inp = message.text.lower()
if inp not in ["cash", "paypal"]:
bot.send_message(message.chat.id, 'Please enter "cash" or "paypal".')
return
with bot.retrieve_data(message.from_user.id, message.chat.id) as data:
msg = ("Your order details\n---------\n"
f"Size: {data['size']}\n"
f"Payment: {inp}\n---------\n"
f"Is that correct [yes/no]?")
bot.send_message(message.chat.id, msg)
bot.set_state(message.from_user.id, MyStates.confirmation, message.chat.id)
# result
#bot.message_handler(state=MyStates.confirmation)
def confirm_order(message):
inp = message.text.lower()
if inp == "yes":
bot.send_message(message.chat.id, "Great. The order is on its way.")
bot.delete_state(message.from_user.id, message.chat.id)
return
elif inp == "no":
bot.send_message(message.chat.id, "Okay. Let's start again.")
order(message)
return
bot.send_message(message.chat.id, 'Please enter "yes" or "no".')
bot.add_custom_filter(custom_filters.StateFilter(bot))
bot.infinity_polling(skip_pending=True)
Related
I'm trying to get code from user and if it's correct to start sending him options.
But the third function (send_welcome) doesn't start. Could you say what I'm missing?
#bot.message_handler(commands=['start'])
def send_text_request(message):
msg = bot.send_message(message.chat.id, "Write a code")
bot.register_next_step_handler(msg, function)
def function(message):
if message.text=='6':
print('hello')
bot.register_next_step_handler(message, send_welcome)
def send_welcome(message):
markup=types.ReplyKeyboardRemove(selective=False)
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
itembtn1 = types.KeyboardButton("option1")
itembtn2 = types.KeyboardButton("option2")
markup.add(itembtn1, itembtn2)
msg = bot.send_message(message.chat.id, "Hello "+message.from_user.first_name+", I will help you! \n Enter the product", reply_markup=markup)
I'm trying to make /stop command for the bot (the greetings stop to send). It works, but only one time, after pressing the /start command it is unable to stop again and runs forever.
Tried different methods of stopping, manged either to stop and unable to restart or to stop once and unable to stop after repeating /start or "greet".
I would be very grateful for the advice of how to improve the existing code
import random, telebot, schedule, time
from telebot import types
from config import token
bot = telebot.TeleBot(token)
greetings = ["hello", "Have a nice day", "Goodbye", "Wow"]
#bot.message_handler(commands=['start'])
def start_message(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Greet")
markup.add(item1)
bot.send_message(message.chat.id, "Press button", reply_markup=markup)
#bot.message_handler(content_types=["text"])
def run_function(message):
def function_to_run():
random_greet = random.choice(greetings)
bot.send_message(message.chat.id, random_greet)
def scheduling():
schedule.every(4).seconds.do(function_to_run).tag('schedule')
scheduling()
if message.text.lower() == "greet":
bot.send_message(message.chat.id, "here you go")
function_to_run()
def schedule_run():
while True:
schedule.run_pending()
time.sleep(1)
schedule_run()
elif message.text.lower() == "stop":
bot.send_message(message.chat.id, "stopping...")
schedule.clear('schedule')
time.sleep(1)
bot.send_message(message.chat.id, "stopped successfully")
bot.polling()
import random, telebot, schedule, time
from telebot import types
from config import token
bot = telebot.TeleBot(token)
greetings = ["hello", "Have a nice day", "Goodbye", "Wow"]
#bot.message_handler(commands=['start', 'stop'])
def start_message(message):
command = message.text.split()[0]
if command == "/start":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Greet")
markup.add(item1)
bot.send_message(message.chat.id, "Press button", reply_markup=markup)
elif command == "/stop":
bot.send_message(message.chat.id, "stopping...")
schedule.clear('schedule')
time.sleep(1)
bot.send_message(message.chat.id, "stopped successfully")
exit()
#bot.message_handler(content_types=["text"])
def run_function(message):
...
# or
elif message.text.lower() == "stop":
bot.send_message(message.chat.id, "stopping...")
schedule.clear('schedule')
time.sleep(1)
bot.send_message(message.chat.id, "stopped successfully")
exit()
bot.polling()
if you want to on it again try this:
import random, telebot, schedule, time
from telebot import types
from config import token
bot = telebot.TeleBot(token)
greetings = ["hello", "Have a nice day", "Goodbye", "Wow"]
on = True
#bot.message_handler(commands=['start', 'stop'])
def start_message(message):
global on
command = message.text.split()[0]
if command == "/start" and not on:
on = True
# your code
if command == "/stop" and on:
on = False
# your code
#bot.message_handler(content_types=["text"])
def run_function(message):
global on
if on:
# your code
bot.polling()
I'm very new to the Alexa Skills Kit. And I`ve been trying to make a simple music player skill on a web hosted server in https://www.pythonanywhere.com. When I try to make a request a
"SKILL_ENDPOINT_ERROR"
is captured in the device log with the following description:
"Skill execution returned an exception for requestId
amzn1.echo-api.request.e08ec414-0a30-4e95-87bb-28f315c8d4eb".
This is my skill request handler code:
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.utils import is_intent_name, is_request_type
from flask import Flask
from flask_ask_sdk.skill_adapter import SkillAdapter
from ask_sdk_model.ui import SimpleCard
app = Flask(__name__)
sb = SkillBuilder()
#VARIABLES
Current_song = ""
silent_mode = False
"""/////////////////////////
// Request Handlers //
////////////////////////"""
#Launch request
#sb.request_handler(can_handle_func=is_request_type("LaunchRequest"))
def launch_request_handler(handler_input):
speech_text = "What do you wish to play?"
return handler_input.response_builder.speak(speech_text).set_card(
SimpleCard("Hello World", speech_text)).set_should_end_session(
False).response
#Session Ended Request
#sb.request_handler(can_handle_func=is_request_type("SessionEndedRequest"))
def session_ended_request_handler(handler_input):
return handler_input.response_builder.response
"""/////////////////////////
// ASK Intent Handlers //
////////////////////////"""
#Help Intent
#sb.request_handler(can_handle_func=is_intent_name("AMAZON.HelpIntent"))
def help_intent_handler(handler_input):
speech_text = "You can ask me to play something on your server!"
return handler_input.response_builder.speak(speech_text).ask(
speech_text).set_card(SimpleCard(
"Wha can I do", speech_text)).response
#Stop Skill intent
#sb.request_handler(
can_handle_func=lambda handler_input:
is_intent_name("AMAZON.CancelIntent")(handler_input) or
is_intent_name("AMAZON.StopIntent")(handler_input))
def cancel_and_stop_intent_handler(handler_input):
speech_text = "Goodbye!"
return handler_input.response_builder.speak(speech_text).set_card(
SimpleCard("Hello World", speech_text)).response
#FallBack Intent
#sb.request_handler(can_handle_func=is_intent_name("AMAZON.FallbackIntent"))
def fallback_handler(handler_input):
speech = (
"I can't help you with that. "
"You can ask me to play music!")
reprompt = "You can ask me to play music!"
handler_input.response_builder.speak(speech).ask(reprompt)
return handler_input.response_builder.response
"""/////////////////////////
// Bot Intent Handlers //
////////////////////////"""
#Play Intent
#sb.request_handler(can_handle_func=is_intent_name("PlayIntent"))
def Play_intent_handler(handler_input):
song_value = handler_input.request_envelope.request.intent.slots["music"].value
if song_value:
speak_output = "Now playing {} on our server.".format(song_value)
Current_song = song_value
else:
speak_output = "I dont know what you want to play."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).ask(speak_output).set_card(SimpleCard("Playing {}...".format(song_value), speak_output))
return handler_input.response_builder.response
#Pause Intent
#sb.request_handler(can_handle_func=is_intent_name("PauseIntent"))
def Pause_intent_handler(handler_input):
speak_output = "Paused."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Pause", speak_output))
return handler_input.response_builder.response
#Loop Intent
#sb.request_handler(can_handle_func=is_intent_name("LoopIntent"))
def Loop_intent_handler(handler_input):
speak_output = "Song loop enabled."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Loop", speak_output))
return handler_input.response_builder.response
#Restart Intent
#sb.request_handler(can_handle_func=is_intent_name("RestartIntent"))
def Restart_intent_handler(handler_input):
speak_output = "Restarting current song"
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Restart", speak_output))
return handler_input.response_builder.response
#Resume Intent
#sb.request_handler(can_handle_func=is_intent_name("ResumeIntent"))
def Resume_intent_handler(handler_input):
speak_output = "Resumed."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Resume", speak_output))
return handler_input.response_builder.response
#Now Playing Intent
#sb.request_handler(can_handle_func=is_intent_name("NowPlayingIntent"))
def Now_Playing_intent_handler(handler_input):
if Current_song:
speak_output = "Now playing {}.".format(Current_song)
else:
speak_output = "There is nothing playing at the moment"
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Now Playing", speak_output))
return handler_input.response_builder.response
#Print Intent
#sb.request_handler(can_handle_func=is_intent_name("PrintIntent"))
def Print_intent_handler(handler_input):
speak_output = "Printed."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Print", speak_output))
return handler_input.response_builder.response
#Remove Number Intent
#sb.request_handler(can_handle_func=is_intent_name("RemoveNumIntent"))
def Remove_Num_intent_handler(handler_input):
num_value = handler_input.request_envelope.request.intent.slots["MusicNum"].value
if num_value:
speak_output = "Removed song number {} from queue".format(num_value)
else:
speak_output = "There is no song in number {}".format(num_value)
if silent_mode == False:
handler_input.response_builder.speak(speak_output).ask(speak_output).set_card(SimpleCard("Remove", speak_output))
return handler_input.response_builder.response
#Remove Position Intent
#sb.request_handler(can_handle_func=is_intent_name("RemovePosIntent"))
def Remove_Pos_intent_handler(handler_input):
pos_value = handler_input.request_envelope.request.intent.slots["MusicPos"].value
if pos_value:
speak_output = "Removed {} song from queue.".format(pos_value)
else:
speak_output = "There is no {} song in queue.".format(pos_value)
if silent_mode == False:
handler_input.response_builder.speak(speak_output).ask(speak_output).set_card(SimpleCard("Remove", speak_output))
return handler_input.response_builder.response
#Remove All Intent
#sb.request_handler(can_handle_func=is_intent_name("RemoveALLIntent"))
def Remove_All_intent_handler(handler_input):
speak_output = "All songs removed from queue"
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Remove", speak_output))
return handler_input.response_builder.response
#Back Intent
#sb.request_handler(can_handle_func=is_intent_name("BackIntent"))
def Back_intent_handler(handler_input):
speak_output = "Went back a song in queue."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Back", speak_output))
return handler_input.response_builder.response
#Skip Intent
#sb.request_handler(can_handle_func=is_intent_name("SkiptIntent"))
def Skip_intent_handler(handler_input):
speak_output = "Skipped."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Skip", speak_output))
return handler_input.response_builder.response
#Shuffle Intent
#sb.request_handler(can_handle_func=is_intent_name("ShuffleIntent"))
def Shuffle_intent_handler(handler_input):
speak_output = "Shuffled queue."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Shuffle", speak_output))
return handler_input.response_builder.response
#Skip to number Intent
#sb.request_handler(can_handle_func=is_intent_name("SkipToNumIntent"))
def Skip_To_Num_intent_handler(handler_input):
num_value = handler_input.request_envelope.request.intent.slots["MusicNum"].value
if num_value:
speak_output = "Skiped to song number {}.".format(num_value)
else:
speak_output = "There is no {} song in queue.".format(num_value)
if silent_mode == False:
handler_input.response_builder.speak(speak_output).ask(speak_output).set_card(SimpleCard("Skip To", speak_output))
return handler_input.response_builder.response
#Skip to position Intent
#sb.request_handler(can_handle_func=is_intent_name("SkipToPosIntent"))
def Skip_To_Pos_intent_handler(handler_input):
pos_value = handler_input.request_envelope.request.intent.slots["MusicPos"].value
if pos_value:
speak_output = "Skiped to {} song in queue.".format(pos_value)
else:
speak_output = "There is no {} song in queue.".format(pos_value)
if silent_mode == False:
handler_input.response_builder.speak(speak_output).ask(speak_output).set_card(SimpleCard("Skip To", speak_output))
return handler_input.response_builder.response
#Loop queue Intent
#sb.request_handler(can_handle_func=is_intent_name("LoopQueueIntent"))
def Loop_Queue_intent_handler(handler_input):
speak_output = "Looped queue."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Loop Queue", speak_output))
return handler_input.response_builder.response
#Silent Mode Intent
#sb.request_handler(can_handle_func=is_intent_name("SilentModeIntent"))
def Silent_Mode_intent_handler(handler_input):
silent_mode = True
return handler_input.response_builder.response
#Disconnect Intent
#sb.request_handler(can_handle_func=is_intent_name("DisconnectIntent"))
def Disconnect_intent_handler(handler_input):
speak_output = "Disconnected."
if silent_mode == False:
handler_input.response_builder.speak(speak_output).set_card(SimpleCard("Disconnect", speak_output))
return handler_input.response_builder.response
sa = SkillAdapter(skill=sb.create(), skill_id="amzn1.ask.skill.e5e95d9a-6047-41aa-96f1-879b88421432", app=app)
"""/////////////////////////
// Exception Handlers //
////////////////////////"""
#Exception Handler
#sb.exception_handler(can_handle_func=lambda i, e: True)
def all_exception_handler(handler_input, exception):
speech = "Sorry, there was some problem. Please try again!!"
handler_input.response_builder.speak(speech).ask(speech)
return handler_input.response_builder.response
#app.route("/")
def invoke_skill():
return sa.dispatch_request()
I first assumed the problem was that I didn't have an Exeption Handler, but there was no change in the result since I implemented one.
Has anyone solved this issue or has any idea what my code is missing?
I'm new in development and python too. I tried to write a simple telegram bot using Telebot. The scenario is to show inline keyboard to user when user click on button do some logic. In Example below I cut the code but it showing the problem. And the problem is:
When first user start working he gets correct and all notifications. But when second user starts to work with bot he gets correct keyboard but notification will send to First user.
Here is a code example:
import telebot
import datetime
bot = telebot.TeleBot(insert_token_here)
keyboard1 = telebot.types.ReplyKeyboardMarkup(True)
keyboard1.row('Choose date', 'dont push it')
#bot.message_handler(commands=['start'])
def start_message(message):
bot.send_message(message.chat.id, 'Welcome', reply_markup=keyboard1)
def dates_inline():
current_date = datetime.datetime.today()
# Inline keyboard
keyboard_dates = telebot.types.InlineKeyboardMarkup()
key_now = telebot.types.InlineKeyboardButton(text=current_date.strftime('%d.%m.%Y') + ' (Today)',
callback_data=current_date.strftime('%Y-%m-%d'))
keyboard_dates.add(key_now)
return keyboard_dates
#bot.message_handler(content_types=['text'])
def choose_message(message):
if message.text == "Choose date":
bot.send_message(message.chat.id, 'Choose date:', reply_markup=dates_inline())
#bot.callback_query_handler(func=lambda call: True)
def choose_date(call):
dt = call.data
print('chose_date dt: %s' % dt)
bot.send_message(message.chat.id, 'All done')
print('end')
else:
print('smth else')
def main():
bot.polling(none_stop=True)
if __name__ == '__main__':
main()
I also faced a similar problem.
Do not create a handler/decorator inside another one. It doesn't work like that. I'm also relatively new to python, so I don't know the exact reason. I also learned it from my mistake.
Do not send messages back to message.chat.id . send it to call.from_user.id so that it'll always send the reply back to the user from whom the call came.
#bot.message_handler(content_types=['text'])
def choose_message(message):
if message.text == "Choose date":
bot.send_message(message.chat.id, 'Choose date:', reply_markup=dates_inline())
else:
print('smth else')
#bot.callback_query_handler(func=lambda call: True)
def choose_date(call):
dt = call.data
print('chose_date dt: %s' % dt)
bot.send_message(call.from_user.id, 'All done')
print('end')
I am also in the development of a bot right now and this is working fine for me.
You need to move following code to top-level indentation. Otherwise it works not as you intended.
#bot.callback_query_handler(func=lambda call: True)
def choose_date(call):
dt = call.data
print('chose_date dt: %s' % dt)
bot.send_message(message.chat.id, 'All done')
#wowkin2 Here is a sample code:
#bot.message_handler(content_types=['text'])
def choose_message(message):
if message.text == "Choose date":
bot.send_message(message.chat.id, 'Choose date:', reply_markup=dates_inline())
print('end')
else:
print('smth else')
#bot.callback_query_handler(func=lambda call: True)
def choose_date(call):
dt = call.data
bot.send_message(message.chat.id, 'All done')
I wrote the first bot in my life using python, which get a username, password and some other data from user input, enter into a site and do some clicking there. It seems to be nothing complicated even for me whose experience in programming is only 2 months))) If the bot is used by one user from beginning to end, everything works well as it should, But if while the bot still has not finished working for one user and some other users are already beginning to use it, I have problems, global variables are confused and mixed.
Please help me to handle my bug (((
import telebot
from telebot.types import Message
from telebot import types
import requests
bot = telebot.TeleBot('xxx')
start_text = """
Hello
"""
payment_text = """
Chose the payment type:
"""
help_text = """
Commands:
/pushup - starting
"""
def check_reg(login, password):
r = requests.post('xxx', data={'login': str(login), 'password':
str(password)})
response = r.text
return response
#bot.message_handler(commands=['start'])
def start_handler(message: Message):
bot.send_message(message.from_user.id, start_text)
#bot.message_handler(commands=['help'])
def help_handler(message: Message):
bot.send_message(message.from_user.id, help_text)
#bot.message_handler(commands=['up'])
def login_handler(message: Message):
bot.send_message(message.from_user.id, a)
bot.register_next_step_handler(message, get_login)
#bot.message_handler(content_types=['text'])
def text_handler(message: Message):
bot.send_message(message.from_user.id, b)
def get_login(message: Message):
if '#' in message.text or '+' in message.text:
global login
login = message.text
bot.send_message(message.from_user.id, c)
bot.register_next_step_handler(message, get_psw)
else:
bot.send_message(message.from_user.id, d)
bot.register_next_step_handler(message, get_login)
def get_psw(message):
global password
password = message.text
if check_reg(login, password) == '1':
bot.send_message(message.from_user.id, e)
bot.register_next_step_handler(message, get_up)
else:
bot.send_message(message.from_user.id, f)
def get_up(message):
global up
up = message.text
if up.isdigit():
if int(up) <= 0:
bot.send_message(message.from_user.id, g)
bot.register_next_step_handler(message, get_up)
else:
get_url(message)
else:
bot.send_message(message.from_user.id, h)
bot.register_next_step_handler(message, get_up)
def get_url(message):
keyboard = types.InlineKeyboardMarkup()
key_xx = types.InlineKeyboardButton("xx", callback_data='xx')
keyboard.add(key_xx)
key_yy = types.InlineKeyboardButton("yy", callback_data='yy')
keyboard.add(key_yy)
bot.send_message(message.from_user.id, text=i, reply_markup=keyboard)
#bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
global url
if call.data == "xx":
url = "xx"
test(call)
elif call.data == "yy":
url = "yy"
test(call)
def test(message):
test= test()
if test.login(url, login, password):
bot.send_message(message.from_user.id, j)
if test.auto_click(up):
bot.send_message(message.from_user.id, k)
bot.send_message(message.from_user.id, n)
test.kill_task()
else:
bot.send_message(message.from_user.id, l)
test.kill_task()
else:
bot.send_message(message.from_user.id, m)
bot.register_next_step_handler(message, get_login)
test.kill_task()
bot.polling(timeout=90)
I did it by myself
user = {}
class user_cred():
login = ''
password = ''
up = ''
def __init__(self, login, password, up):
self.login = login
self.password = password
self.up = up
def set_login(self, login):
self.login = login
def set_password(self, password):
self.password = password
def set_up(self, up):
self.up = up