Возникла проблема, сам увы не могу справиться с ней. У меня есть 2 файла, main где находить основной код бота и кнопки и registration где происходит проверка и регистрация пользователя. Как сделать что бы при нажатии на кнопку "Работодатель"(128 строка) в файле main, запускалась функция с названием send_welcome_employer (47 строка) в файле registration. main
from telegram import Update, ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, ConversationHandler
import mysql.connector
from telegram.ext import Updater, CommandHandler
from config import TOKEN
import requests, telebot, logging, sys
from telebot import types, apihelper
from mysql.connector import errorcode
import mysql.connector
try:
mydb = mysql.connector.connect(
host="host",
user="user",
passwd="passwd",
port="port",
database="database"
)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Что-то не так с вашим именем пользователя или паролем")
sys.exit()
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("База данных не существует")
sys.exit()
else:
print(err)
sys.exit()
mycursor = mydb.cursor()
sql = "SELECT COUNT(*) FROM users_employer"
mycursor.execute(sql)
rows = mycursor.fetchall()
number_registered_employers = rows[0][0] # сколько человек зарегистрировано(Работодатели)
sql = "SELECT COUNT(*) FROM users_workers"
mycursor.execute(sql)
rows = mycursor.fetchall()
number_registered_workers = rows[0][0] # сколько человек зарегистрировано(Работодатели)
sql = "SELECT COUNT(*) FROM applications"
mycursor.execute(sql)
rows = mycursor.fetchall()
number_applications = rows[0][0] # сколько человек зарегистрировано(Работодатели)
logging.basicConfig(format='[LINE:%(lineno)d]# - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
bot = telebot.TeleBot(TOKEN)
id_group = -1001159001919 # 756515243#
user_data = {}
class User:
def __init__(self, city):
self.city = city
keys = ['phone', 'date_work_start',
'date_work_finish', 'time_work', 'place_work',
'quantity_people', 'type_payment', "much_pay"]
for key in keys:
self.key = None
FIRST, registration_button, setting_button, main_menu_button, \
post_requests_button, feedback_button= range(6)
def start(update, context):
user = update.message.from_user
logger.info("Пользователь %s запустил команду start.", user.last_name + user.first_name)
img = open('D:\Photo\wallapper\\17706.jpg', 'rb')
bot.send_photo(update.message.chat.id, img)
keyboard = [
[InlineKeyboardButton('Зарегистрироваться', callback_data=str(registration_button)),
InlineKeyboardButton('Настройка', callback_data=str(setting_button))],
[InlineKeyboardButton('Заявка', callback_data=str(post_requests_button))],
[InlineKeyboardButton('Обратная связь', callback_data=str(feedback_button))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text("Ура! Вы - в главном меню!\n Добро пожаловать в бота для поиска работы, "
"для работодателей представляеться прекрасная возможность в короткий срок "
"найти ответсвенных работников для проведения скорых работ. В свою очередь для "
"работников представляеться возможность в короткий срок заработать\n---\n🔘Работодателей: "
+ str(number_registered_employers) + "\n🔘Работников: " + str(number_registered_workers) +
"\n🔘Количество размещенных заказов: " + str(number_applications) +
"\n---\nДля начала работы нажмите одну из кнопок ниже:", reply_markup=reply_markup)
return FIRST
def start_over(update, context): # Запрашивать тот же текст и клавиатуру, что и` start`, но не как новое сообщение
bot = context.bot
img = open('D:\\Photo\\wallapper\\17706.jpg', 'rb')
bot.send_photo(update.message.chat.id, img)
keyboard = [
[InlineKeyboardButton('Зарегистрироваться', callback_data=str(registration_button)),
InlineKeyboardButton('Настройка', callback_data=str(setting_button))],
[InlineKeyboardButton('Заявка', callback_data=str(post_requests_button))],
[InlineKeyboardButton('Обратная связь', callback_data=str(feedback_button))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text("Ура! Вы - в главном меню!\n Добро пожаловать в бота для поиска работы, "
"для работодателей представляеться прекрасная возможность в короткий срок "
"найти ответсвенных работников для проведения скорых работ. В свою очередь для "
"работников представляеться возможность в короткий срок заработать\n---\n🔘Работодателей: "
+ str(number_registered_employers) + "\n🔘Работников: " + str(number_registered_workers) +
"\n🔘Количество размещенных заказов: " + str(number_applications) +
"\n---\nДля начала работы нажмите одну из кнопок ниже:", reply_markup=reply_markup)
return FIRST
def registration_menu(update, context): # при нажатии на первую кнопку (Зарегистрироваться)
query = update.callback_query
bot = context.bot
keyboard = [
[InlineKeyboardButton("Работодатель", callback_data=str(" ")), # СТРОКА 128
InlineKeyboardButton("Работник", callback_data=str(" "))],
[InlineKeyboardButton("Вернуться в главное меню", callback_data=str(main_menu_button))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
bot.edit_message_text(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
text="Выбирете кто вы, для регистрации в бд ",
reply_markup=reply_markup
)
return FIRST
def setting_menu(update, context): # при нажатии на вторую кнопку (Настройка)
query = update.callback_query
bot = context.bot
keyboard = [
[InlineKeyboardButton("Данные о себе", callback_data=str(" ")),
InlineKeyboardButton("Данные вашей заявки", callback_data=str(" "))],
[InlineKeyboardButton("Вернуться в главное меню", callback_data=str(main_menu_button))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
bot.edit_message_text(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
text="Что вы хотите изменить??",
reply_markup=reply_markup
)
return FIRST
def post_requests_menu(update, context): # при нажатии на третью кнопку (Разместить объявление)
query = update.callback_query
bot = context.bot
keyboard = [
[InlineKeyboardButton("Вернуться в главное меню", callback_data=str(main_menu_button))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
bot.edit_message_text(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
text="ТУТ ДОЛЖНА БЫТЬ ФОРМА ДЛЯ РАЗМЕЩЕНИЯ ОБЪЯВЛЕНИЯ",
reply_markup=reply_markup
)
return FIRST
def feedback_menu(update, context): # при нажатии на третью кнопку (Разместить объявление)
query = update.callback_query
bot = context.bot
keyboard = [
[InlineKeyboardButton("Вернуться в главное меню", callback_data=str(main_menu_button))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
bot.edit_message_text(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
text="Напишите нам, чего не хватает в боте 🙌 \
Мы всегда рады обратной связи от неравнодушных пользователей!\
Здесь вы можете поделиться позитивным, негативным опытом, предложить сферы деятельности, категории, параметры фильтрации и т.д.",
reply_markup=reply_markup
)
return FIRST
def error(update, context):
logger.warning('Обновление "%s" вызвало ошибку "%s"', update, context.error)
def main():
updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher
# ^ означает "начало строки"
# $ означает "конец строки"
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
FIRST: [CallbackQueryHandler(registration_menu, pattern='^' + str(registration_button) + '$'),
CallbackQueryHandler(setting_menu, pattern='^' + str(setting_button) + '$'),
CallbackQueryHandler(post_requests_menu, pattern='^' + str(post_requests_button) + '$'),
CallbackQueryHandler(feedback_menu, pattern='^' + str(feedback_button) + '$'),
CallbackQueryHandler(start_over, pattern='^' + str(main_menu_button) + '$')]
},
fallbacks=[CommandHandler('start', start)]
)
dp.add_handler(conv_handler)
dp.add_error_handler(error)
updater.start_polling()
if __name__ == '__main__':
main()
registration
import requests, telebot, logging, sys
from telebot import types, apihelper
from mysql.connector import errorcode
import mysql.connector
try:
mydb = mysql.connector.connect( # даныне бд
host="host",
user="user",
passwd="passwd",
port="port",
database="database"
)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Что-то не так с вашим именем пользователя или паролем")
sys.exit()
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("База данных не существует")
sys.exit()
else:
print(err)
sys.exit()
mycursor = mydb.cursor()
bot = telebot.TeleBot('909567963:AAEiKOOZkQ8dCeyGLPYd1EV6Uy-m1AAmEsQ')
user_data = {}
@bot.message_handler(commands=['help'])
def help_list(message):
a = ['/help ' + 'Информация\n', '/reg_employer ' + 'Регистрация работодателя\n', '/reg_workers '+'Регистрация работника']
for i in a:
bot.send_message(message.chat.id, i)
class User:
def __init__(self, first_name):
self.first_name = first_name
self.last_name = ''
self.middle_name = ''
self.phone_number = ''
self.subjects_civil_law = ''
self.region = ''
self.services_provided = ''
self.age = ''
@bot.message_handler(commands=['reg_employer']) # Работодатель
def send_welcome_employer(message):# СТРОКА 47
user_id = message.from_user.id
list = []
sql = "SELECT user_id FROM users_employer "
mycursor.execute(sql)
rows = mycursor.fetchall()
for row in rows:
list.append(row[0])
if user_id not in list:
markup = types.ReplyKeyboardRemove(selective=False)
msg = bot.send_message(message.chat.id, "Введите Ваше имя: ", reply_markup=markup)
bot.register_next_step_handler(msg, process_lastname_step_employer)
else:
sql = "SELECT first_name, last_name FROM users_employer WHERE user_id LIKE %s"
val = (user_id,)
mycursor.execute(sql, val)
rows = mycursor.fetchall()
for row in rows:
first_name = row[0]
last_name = row[1]
bot.send_message(message.chat.id, "Вы уже зарегистрированы, " + first_name + " " + last_name)
def process_lastname_step_employer(message):
try:
user_id = message.from_user.id
user_data[user_id] = User(message.text)
user = user_data[user_id]
msg = bot.send_message(message.chat.id, "Введите Вашу фамилию: ")
bot.register_next_step_handler(msg, process_middlename_step_employer)
except Exception as e:
bot.reply_to(message, "ooooooooooooops ")
def process_middlename_step_employer(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.last_name = message.text
msg = bot.send_message(message.chat.id, "Введите Ваше отчество: ")
bot.register_next_step_handler(msg, process_phonenumber_step_employer)
except Exception as e:
bot.reply_to(message, 'ooooooooooooops')
def process_phonenumber_step_employer(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.middle_name = message.text
msg = bot.send_message(message.chat.id, "Введите Ваш номер телефона: ")
bot.register_next_step_handler(msg, process_subjects_civil_law_step_employer)
except Exception as e:
bot.reply_to(message, 'ooooooooooooops:')
def process_subjects_civil_law_step_employer(message):
try:
a = int(message.text)
if len(str(a)) == 11:
user_id = message.from_user.id
user = user_data[user_id]
user.phone_number = message.text
markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
itembtn1 = types.KeyboardButton('Физическое лицо')
itembtn2 = types.KeyboardButton('Юридическое лицо')
markup.add(itembtn1, itembtn2)
msg = bot.send_message(message.chat.id, "Укажите вы являетесь юридическим или физическим лицом: ",
reply_markup=markup)
bot.register_next_step_handler(msg, process_region_step_employer)
else:
bot.send_message(message.chat.id)
bot.register_next_step_handler(process_subjects_civil_law_step_employer)
except Exception as e:
msg = bot.reply_to(message, 'Не являеться номером телефона. Пожалуйста введите номер телефона.')
bot.register_next_step_handler(msg, process_subjects_civil_law_step_employer)
def process_region_step_employer(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.subjects_civil_law = message.text
markup = types.ReplyKeyboardRemove(selective=False)
msg = bot.send_message(message.chat.id, "Укажите Ваш город: ", reply_markup=markup)
bot.register_next_step_handler(msg, process_services_provided_step_employer)
except Exception as e:
msg = bot.reply_to(message, 'Вы ввели что-то не верное')
bot.register_next_step_handler(msg, process_region_step)
def process_services_provided_step_employer(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.region = message.text
markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
itembtn1 = types.KeyboardButton('Строительство')
itembtn2 = types.KeyboardButton('Проектирование')
itembtn3 = types.KeyboardButton('Программирование')
itembtn4 = types.KeyboardButton('Оказание услуг в сфере обслуживания')
itembtn5 = types.KeyboardButton('Грузовые перевозки')
markup.add(itembtn1, itembtn2, itembtn3, itembtn4, itembtn5)
msg = bot.send_message(message.chat.id, "Каким видом деятельности вы занимаетесь: ", reply_markup=markup)
bot.register_next_step_handler(msg, process_last_step_employer)
except Exception as e:
bot.reply_to(message, 'oooops')
def process_last_step_employer(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.services_provided = message.text
markup = types.ReplyKeyboardRemove(selective=False)
sql = "INSERT INTO users_employer (first_name, last_name, middle_name, phone_number, subjects_civil_law, region, services_provided, user_id) \
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
val = (
user.first_name, user.last_name, user.middle_name, user.phone_number, user.subjects_civil_law, user.region,
user.services_provided, user_id)
mycursor.execute(sql, val)
mydb.commit()
bot.send_message(message.chat.id,
"Вы успешно зарегестрированны," + " " + user.first_name + " " + user.middle_name,
reply_markup=markup)
except Exception as e:
bot.send_message(message, "ooooooooooooops")
@bot.message_handler(commands=['reg_workers'])
def send_welcome(message):
user_id = message.from_user.id
list = []
sql = "SELECT user_id FROM users_workers "
mycursor.execute(sql)
rows = mycursor.fetchall()
for row in rows:
list.append(row[0])
if user_id not in list:
markup = types.ReplyKeyboardRemove(selective=False)
msg = bot.send_message(message.chat.id, "Введите Ваше имя: ", reply_markup=markup)
bot.register_next_step_handler(msg, process_lastname_step)
else:
sql = "SELECT first_name, last_name FROM users_workers WHERE user_id LIKE %s"
val = (user_id,)
mycursor.execute(sql, val)
rows = mycursor.fetchall()
for row in rows:
first_name = row[0]
last_name = row[1]
bot.send_message(message.chat.id, "Вы уже зарегистрированы, " + first_name + " " + last_name)
def process_lastname_step(message):
try:
user_id = message.from_user.id
user_data[user_id] = User(message.text)
user = user_data[user_id]
msg = bot.send_message(message.chat.id, "Введите Вашу фамилию: ")
bot.register_next_step_handler(msg, process_middlename_step)
except Exception as e:
bot.reply_to(message, "ooooooooooooops ")
def process_middlename_step(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.last_name = message.text
msg = bot.send_message(message.chat.id, "Введите Ваше отчество: ")
bot.register_next_step_handler(msg, process_phonenumber_step)
except Exception as e:
bot.reply_to(message, 'ooooooooooooops')
def process_phonenumber_step(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.middle_name = message.text
msg = bot.send_message(message.chat.id, "Введите Ваш номер телефона: ")
bot.register_next_step_handler(msg, process_age_step)
except Exception as e:
bot.reply_to(message, 'ooooooooooooops:')
def process_age_step(message):
try:
a = int(message.text)
if len(str(a)) == 11:
user_id = message.from_user.id
user = user_data[user_id]
user.phone_number = message.text
msg = bot.send_message(message.chat.id, "Укажите Ваш возраст: ")
bot.register_next_step_handler(msg, process_region_step)
else:
bot.send_message(message.chat.id)
bot.register_next_step_handler(process_age_step)
except Exception as e:
msg = bot.reply_to(message, 'Не являеться номером телефона. Пожалуйста введите номер телефона.')
bot.register_next_step_handler(msg, process_age_step)
def process_region_step(message):
try:
int(message.text)
user_id = message.from_user.id
user = user_data[user_id]
user.age = message.text
markup = types.ReplyKeyboardRemove(selective=False)
msg = bot.send_message(message.chat.id, "Укажите Ваш город: ", reply_markup=markup)
bot.register_next_step_handler(msg, process_services_provided_step)
except Exception as e:
msg = bot.reply_to(message, 'Не являеться номером возрастом. Укажите Ваш возраст:')
bot.register_next_step_handler(msg, process_region_step)
def process_services_provided_step(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.region = message.text
markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
itembtn1 = types.KeyboardButton('Строительство')
itembtn2 = types.KeyboardButton('Проектирование')
itembtn3 = types.KeyboardButton('Программирование')
itembtn4 = types.KeyboardButton('Оказание услуг в сфере обслуживания')
itembtn5 = types.KeyboardButton('Грузовые перевозки')
markup.add(itembtn1, itembtn2, itembtn3, itembtn4, itembtn5)
msg = bot.send_message(message.chat.id, "Каким видом деятельности вы занимаетесь: ", reply_markup=markup)
bot.register_next_step_handler(msg, process_last_step)
except Exception as e:
bot.reply_to(message, 'oooops')
def process_last_step(message):
try:
user_id = message.from_user.id
user = user_data[user_id]
user.services_provided = message.text
markup = types.ReplyKeyboardRemove(selective=False)
sql = "INSERT INTO users_workers (first_name, last_name, middle_name, phone_number, age, region, services_provided, user_id) \
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
val = (
user.first_name, user.last_name, user.middle_name, user.phone_number, user.age, user.region,
user.services_provided, user_id)
mycursor.execute(sql, val)
mydb.commit()
bot.send_message(message.chat.id,
"Вы успешно зарегестрированны," + " " + user.first_name + " " + user.middle_name,
reply_markup=markup)
except Exception as e:
bot.send_message(message, "Вы уже зарегестрированны," + " " + user.first_name + " " + user.middle_name)
Если напрямую в callback_data передаю функцию send_welcome_employer, он выдает ошибку: "send_welcome_employer() takes 1 positional argument but 2 were given" не смог понять понять какие аргументы передает, поэтому добавил просто *args
А если в send_welcome_employer передать *args, то будет такая ошибка: 'Update' object has no attribute 'from_user' И как тут исправить я не знаю.
Строго не судите, пока только учусь.