added authentication to the bot. added bot commnads. added create button for when the db is empty or no data is available to show.

This commit is contained in:
Hosein
2026-01-05 23:40:13 +03:30
parent 4b5b24c97c
commit caac6c3a08
18 changed files with 369 additions and 47 deletions
+5 -1
View File
@@ -25,7 +25,11 @@ def register(bot):
bot.send_message(
message.chat.id, "Here is the data:", reply_markup=markup)
else:
bot.reply_to(message, "No data found.")
markup = types.InlineKeyboardMarkup(row_width=1)
markup.add(types.InlineKeyboardButton(
" Create New Category", callback_data="create_category"))
bot.reply_to(message, "No data found.", reply_markup=markup)
except Exception as e:
logger.error(f"Error in 'Show Categories' handler: {e}")
bot.reply_to(message, "Sorry, an error occurred.")
+6 -1
View File
@@ -1,4 +1,9 @@
from telebot import types
from bot.handlers.start import startMessage
def register(bot):
@bot.message_handler(func=lambda message: True)
def handle_unknown(message):
bot.reply_to(message, f"You said: {message.text}")
bot.reply_to(
message, f"You said: {message.text}. send /start to get started.")
+4 -1
View File
@@ -24,7 +24,10 @@ def register(bot):
bot.send_message(
message.chat.id, "Here is the data:", reply_markup=markup)
else:
bot.reply_to(message, "No data found.")
markup = types.InlineKeyboardMarkup(row_width=1)
markup.add(types.InlineKeyboardButton(
" Create New Course", callback_data="create_course"))
bot.reply_to(message, "No data found.", reply_markup=markup)
except Exception as e:
logger.error(f"Error in (Show Courses) handler: {e}")
bot.reply_to(message, "Sorry, an error occurred.")
+15 -1
View File
@@ -1,11 +1,25 @@
from . import start, students, teachers, courses, tags, categories, common
from . import start, students, teachers, courses, tags, categories, common, login
from bot.callbacks.init import register_all_callbacks
from telebot import types
def register_all_handlers(bot):
"""Register all handlers and callbacks"""
# Set bot commands
commands = [
types.BotCommand(command="start", description="Start the bot"),
types.BotCommand(command="login", description="Login to your account"),
types.BotCommand(command="logout",
description="Logout of your account"),
types.BotCommand(command="session",
description="Info about your session"),
]
bot.set_my_commands(commands)
# Message handlers
start.register(bot)
login.register(bot)
students.register(bot)
teachers.register(bot)
courses.register(bot)
+110
View File
@@ -0,0 +1,110 @@
from telebot import types, TeleBot
from database.models import Admins
from bot.handlers.start import startMarkup
def register(bot: TeleBot):
@bot.message_handler(commands=['login'])
def start_login(message):
# Check if already authenticated
if Admins.is_authenticated(message.from_user.id):
session_info = Admins.get_session_info(message.from_user.id)
bot.send_message(
message.chat.id,
f"✅ You are already logged in!\n\n"
f"Session expires in: {session_info['time_remaining']}"
)
return
msg = bot.send_message(
message.chat.id,
"🔐 Please enter your username:"
)
bot.register_next_step_handler(msg, get_password)
def get_password(message):
"""Get username and ask for password"""
username = message.text.strip()
try:
bot.delete_message(message.chat.id, message.message_id)
except:
pass
msg = bot.send_message(
message.chat.id,
f"Username: {username}\n\n🔑 Now enter your password:"
)
bot.register_next_step_handler(msg, verify_and_login, username)
def verify_and_login(message, username):
"""Verify credentials and create session"""
password = message.text.strip()
telegram_id = message.from_user.id
try:
bot.delete_message(message.chat.id, message.message_id)
except:
pass
# Attempt login (this creates the session)
if Admins.login(username, password, telegram_id):
bot.send_message(
message.chat.id,
f"✅ Login successful!\n\n"
f"Welcome back, {username}!\n"
f"Session valid for: {Admins.SESSION_TIMEOUT_HOURS} hours\n"
f"Use /session for info about your session, or /logout to logout.",
reply_markup=startMarkup()
)
else:
bot.send_message(
message.chat.id,
"❌ Invalid credentials or unauthorized Telegram account.\n\n"
"Please check your username and password.\nContact @HoseinA05 for support."
)
@bot.message_handler(commands=['logout'])
def logout(message):
"""Logout user manually"""
if not Admins.is_authenticated(message.from_user.id):
bot.send_message(message.chat.id, "You are not logged in.")
return
if Admins.logout(message.from_user.id):
bot.send_message(
message.chat.id,
"✅ You have been logged out successfully.\n\n"
"Use /login to access admin features again."
)
else:
bot.send_message(
message.chat.id, "❌ Logout failed. Please try again later.")
@bot.message_handler(commands=['session'])
def check_session(message):
"""Check current session status"""
session_info = Admins.get_session_info(message.from_user.id)
if not session_info:
bot.send_message(
message.chat.id, "❌ You don't have an admin account.")
return
if session_info['is_active']:
bot.send_message(
message.chat.id,
f"✅ Active Session\n\n"
f"Username: {session_info['username']}\n"
f"Last Login: {session_info['last_login']}\n"
f"Time Remaining: {session_info['time_remaining']}"
)
else:
bot.send_message(
message.chat.id,
f"⏱️ Session Expired\n\n"
f"Username: {session_info['username']}\n"
f"Please use /login to continue."
)
+10 -10
View File
@@ -1,5 +1,4 @@
from telebot import types
from bot.utils.auth import is_authenticated
# TODO: Add Pagincation to Showing rows of entities (To all entities)
@@ -7,16 +6,17 @@ from bot.utils.auth import is_authenticated
def register(bot):
@bot.message_handler(commands=["start"])
def start_handler(message):
if is_authenticated(message.from_user.id):
bot.send_message(
message.chat.id, "authorized user! Welcome.")
else:
bot.send_message(
message.chat.id, "Welcome! Use buttons to fetch from database.")
startMessage(bot, message=message)
markup = startMarkup()
bot.reply_to(message, "Use buttons to fetch from database.",
reply_markup=markup)
def startMessage(bot, message):
# if is_authenticated(message.from_user.id):
# bot.send_message(
# message.chat.id, "authorized user! Welcome.")
markup = startMarkup()
bot.reply_to(message, "Use buttons to fetch from database.",
reply_markup=markup)
def startMarkup():
+13 -5
View File
@@ -1,13 +1,18 @@
import logging
from telebot import types
from database.models import Students
from telebot import types, TeleBot
from database.models import Students, Admins
logger = logging.getLogger(__name__)
def register(bot):
def register(bot: TeleBot):
@bot.message_handler(func=lambda message: message.text == "Show Students")
def get_students(message):
if not Admins.is_authenticated(message.from_user.id):
bot.send_message(
message.chat.id, "⛔ Unauthorized access!\nPlease /login first.")
return
try:
data = Students.getAllStudents()
if data:
@@ -20,12 +25,15 @@ def register(bot):
# add button for creating a new student
markup.add(types.InlineKeyboardButton(
" Create New Student", callback_data="create_student"))
" Create New Student 🔒", callback_data="create_student"))
bot.send_message(
message.chat.id, "Here is the data:", reply_markup=markup)
else:
bot.reply_to(message, "No data found.")
markup = types.InlineKeyboardMarkup(row_width=1)
markup.add(types.InlineKeyboardButton(
" Create New Student 🔒", callback_data="create_student"))
bot.reply_to(message, "No data found.", reply_markup=markup)
except Exception as e:
logger.error(f"Error in get_students handler: {e}")
bot.reply_to(message, "Sorry, an error occurred.")
+2 -2
View File
@@ -25,11 +25,11 @@ def register(bot: TeleBot):
bot.send_message(
message.chat.id, "Here is the data:", reply_markup=markup)
else:
markup = types.InlineKeyboardMarkup(row_width=2)
markup = types.InlineKeyboardMarkup(row_width=1)
markup.add(types.InlineKeyboardButton(
" Create New Tag", callback_data="create_tag"))
bot.reply_to(message, "No data found.", markup=markup)
bot.reply_to(message, "No data found.", reply_markup=markup)
except Exception as e:
logger.error(f"Error in 'Show Tags' handler: {e}")
bot.reply_to(message, "Sorry, an error occurred.")
+5 -2
View File
@@ -19,12 +19,15 @@ def register(bot):
markup.add(btn)
# add button for creating a new teacher
markup.add(types.InlineKeyboardButton(
" Create New Teacher", callback_data="create_teacher"))
" Create New Teacher 🔒", callback_data="create_teacher"))
bot.send_message(
message.chat.id, "Here is the data:", reply_markup=markup)
else:
bot.reply_to(message, "No data found.")
markup = types.InlineKeyboardMarkup(row_width=1)
markup.add(types.InlineKeyboardButton(
" Create New Teacher 🔒", callback_data="create_teacher"))
bot.reply_to(message, "No data found.", reply_markup=markup)
except Exception as e:
logger.error(f"Error in get_teachers handler: {e}")
bot.reply_to(message, "Sorry, an error occurred.")