Как вызвать ряд функций из модуля в основной файл проекта с использованием bot.register_next_step_handler
У меня есть 2 файла. main.py - основа проекта и reg.py - регистрация пользователя. reg.py
from telebot import types
import telebot, requests
bot = telebot.TeleBot('TOKEN')
user_data = {}
class User_register:
def __init__(self, login):
self.login = login
self.password = " "
self.email = " "
self.category = " "
@bot.message_handler(commands=['start'])
def send_login(message):
markup = types.ReplyKeyboardRemove(selective=False)
msg = bot.send_message(message.chat.id, "Введите логин: ", reply_markup=markup)
bot.register_next_step_handler(msg, send_password)
def send_password(message):
user_id = message.from_user.id
user_data[user_id] = User_register(message.text)
msg = bot.send_message(message.chat.id, "Введите пароль: ")
bot.register_next_step_handler(msg, send_email)
def send_email(message):
user_id = message.from_user.id
user = user_data[user_id]
user.password = message.text
msg = bot.send_message(message.chat.id, "Введите email: ")
bot.register_next_step_handler(msg, send_category)
def send_category(message):
user_id = message.from_user.id
user = user_data[user_id]
user.email = message.text
markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True, row_width=2)
itembtn1 = types.KeyboardButton('ИС-16')
itembtn2 = types.KeyboardButton('ИС-17')
itembtn3 = types.KeyboardButton('ИС-18')
itembtn4 = types.KeyboardButton('ИС-19')
markup.add(itembtn1, itembtn2, itembtn3, itembtn4)
msg = bot.send_message(message.from_user.id, "Введите Вашу группу: ", reply_markup=markup)
bot.register_next_step_handler(msg, last_process)
def last_process(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.category = message.text
bot.send_message(message.chat.id, "Вы успешно зарегистрированы.")
except Exception as e:
bot.reply_to(message, "Вы уже зарегистрированы.")
bot.polling(none_stop=True)
файл main.py
import telebot, logging, requests, json, time
from telebot import types
import reg
bot = telebot.TeleBot('TOKEN')
def main_menu():
keyboard = types.InlineKeyboardMarkup(True)
row = [types.InlineKeyboardButton(text="Регистрация", callback_data="registration")]
keyboard.row(*row)
return keyboard
@bot.message_handler(commands=["start"])
def send_welcome(message):
img = open("xxx", "rb")
bot.send_photo(message.chat.id, img, caption="Добро пожаловать на платформу по обучению бездарей",
reply_markup=main_menu())
@bot.callback_query_handler(func=lambda call: True)
def callback_btn(call):
data = call.data
if data == "registration":
reg.send_login(call.message)#первая функция в файле reg.py
bot.polling(none_stop=True)
В файле main.py я импортирую файл reg.py и мне нужно вызвать регистрацию пользователя по нажатию кнопки. Но если я указываю reg.send_login(message) и запускаю файл main.py то выполняться только 1 функция всей регистрации и не переходит на следующий шаг. Как мне сделать что бы при вызове функции он проходил по всем шагам??
Ответы (3 шт):
@bot.message_handler(commands=['uiscreate'])
def uis_request_domain(message):
if message.chat.id not in users_uis:
bot.send_message(message.chat.id, 'Не дозволено')
else:
send = bot.send_message(message.chat.id, 'Создать сослуживца\nПочтовый ящикъ:\n'
'example.ru')
bot.register_next_step_handler(send, uis_request_data)
def uis_request_data(message):
if message.text.lower() == 'отмена':
bot.send_message(message.from_user.id, 'На нетъ и суда нетъ')
return
global domain_uis
domain_uis = message.text.lower()
send = bot.send_message(message.chat.id, 'Введите: ФИО должность нумер')
bot.register_next_step_handler(send, create_uis)
def create_uis(message):
first = message.text.split()[1]
last = message.text.split()[0]
middle = message.text.split()[2]
phone = message.text.split()[4]
position = message.text.split()[3]
uis_login = create_nickname(first, last, middle, 'create_uis')
bot.send_message(message.chat.id, '✅ логинъ')
uis_password = create_password()
bot.send_message(message.chat.id, '✅ шифръ')
вместо global можете воспользоваться классом
@bot.message_handler(commands=["start"])
def send_welcome(message):
start_keyboard = types.InlineKeyboardMarkup()
start_registration = types.InlineKeyboardButton(text='Регистрация', callback_data='registration')
start_keyboard.add(start_registration)
bot.send_message(message.chat.id, 'привет', reply_markup=start_keyboard)
@bot.callback_query_handler(func=lambda call: True)
def callback_btn(call):
if call.data == "registration":
send_login(call.message)
user_data = {}
class User_register:
def __init__(self, login):
self.login = login
self.password = " "
self.email = " "
self.category = " "
def send_login(message):
markup = types.ReplyKeyboardRemove(selective=False)
msg = bot.send_message(message.chat.id, "Введите логин: ", reply_markup=markup)
bot.register_next_step_handler(msg, send_password)
def send_password(message):
user_id = message.from_user.id
user_data[user_id] = User_register(message.text)
msg = bot.send_message(message.chat.id, "Введите пароль: ")
bot.register_next_step_handler(msg, send_email)
def send_email(message):
user_id = message.from_user.id
user = user_data[user_id]
user.password = message.text
msg = bot.send_message(message.chat.id, "Введите email: ")
bot.register_next_step_handler(msg, send_category)
def send_category(message):
user_id = message.from_user.id
user = user_data[user_id]
user.email = message.text
markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True, row_width=2)
itembtn1 = types.KeyboardButton('ИС-16')
itembtn2 = types.KeyboardButton('ИС-17')
itembtn3 = types.KeyboardButton('ИС-18')
itembtn4 = types.KeyboardButton('ИС-19')
markup.add(itembtn1, itembtn2, itembtn3, itembtn4)
msg = bot.send_message(message.from_user.id, "Введите Вашу группу: ", reply_markup=markup)
bot.register_next_step_handler(msg, last_process)
def last_process(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.category = message.text
bot.send_message(message.chat.id, "Вы успешно зарегистрированы.")
except Exception as e:
bot.reply_to(message, "Вы уже зарегистрированы.")
# Запуск бота
bot.polling(none_stop=True, interval=0)
Андрей, у меня возник подобный вопрос. Из всех вариантов решения, я предполагаю, что надо как-то правильно применять
if __name__=='__main__':
Так как вопрос был задан полтора года назад и если у вас получилось решить данную проблему, прошу дополнить вопрос.
Или можете ответить на странице моего вопроса. Заранее спасибо.
