این کد  بات تلگرامی من هستش متاسفانه گزینه های منو در بات به درستی به کاربر نشون داده نمیشه میتونی بررسی کنی مشکل چیه و کل کد رو اصلاح و برای من بفرتستی 

import os
import asyncio
import logging
import random
from aiogram import Bot, Dispatcher, types, F
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.filters import Command, StateFilter
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from sqlalchemy import create_engine, Column, Integer, String, Text, Float
from sqlalchemy.orm import declarative_base, sessionmaker
from datetime import datetime
from config import BOT_TOKEN, ADMIN_USER_ID
from sqlalchemy.exc import SQLAlchemyError

Base = declarative_base()

# Models
class User(Base):
    __tablename__ = 'users'
    user_id = Column(Integer, primary_key=True)
    start_time = Column(String)
    balance = Column(Float, default=0.0)

class Order(Base):
    __tablename__ = 'orders'
    order_id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, nullable=False)
    link = Column(String, nullable=False)
    status = Column(String, nullable=False)

class TextMessages(Base):
    __tablename__ = 'text_messages'
    id = Column(Integer, primary_key=True)
    key = Column(String, nullable=False, unique=True)
    content = Column(Text, nullable=False)

class Log(Base):
    __tablename__ = 'logs'
    id = Column(Integer, primary_key=True, autoincrement=True)
    level = Column(String, nullable=False)
    message = Column(Text, nullable=False)
    timestamp = Column(String, nullable=False)

# Custom logging handler
class DatabaseLogHandler(logging.Handler):
    def __init__(self, session):
        super().__init__()
        self.session = session

    def emit(self, record):
        log_entry = Log(
            level=record.levelname,
            message=record.getMessage(),
            timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        )
        self.session.add(log_entry)
        self.session.commit()

class FileUploadState(StatesGroup):
    waiting_for_file = State()

class AdminBalanceUpdateState(StatesGroup):
    waiting_for_balance = State()

# Database setup
async def create_db():
    db_path = 'DB/bot_database.db'
    if not os.path.exists(db_path):
        engine = create_engine(f'sqlite:///{db_path}')
        Base.metadata.create_all(engine)
        logging.info('Database created.')
    else:
        engine = create_engine(f'sqlite:///{db_path}')
        logging.info('Using existing database.')
    Session = sessionmaker(bind=engine)
    return Session

# User registration
async def register_user(session, user_id):
    existing_user = session.query(User).filter_by(user_id=user_id).first()
    if existing_user:
        logging.info(f'User {user_id} already exists.')
        return
    
    start_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    user = User(user_id=user_id, start_time=start_time)
    session.add(user)
    session.commit()
    logging.info(f'New user registered: {user_id}')

# Text message management
async def add_text_message(session, key, content):
    text_message = TextMessages(key=key, content=content)
    session.add(text_message)
    session.commit()
    logging.info(f'Text message added: {key}')

async def get_text_message(session, key):
    text_message = session.query(TextMessages).filter_by(key=key).first()
    return text_message.content if text_message else None

# State classes
class NewOrderState(StatesGroup):
    link = State()

class AdminResponseState(StatesGroup):
    waiting_for_response = State()

# Command handlers
async def start_command(message: types.Message):
    user_id = message.from_user.id
    Session = await create_db()
    session = Session()
    await register_user(session, user_id)
    
    text = await get_text_message(session, 'start_message')
    if text:
        await message.answer(text, parse_mode="Markdown")
    else:
        await message.answer("متن خوش‌آمدگویی یافت نشد.", parse_mode="Markdown")
    
    logging.info(f'Received /start command from user: {user_id}')

async def neworder_command(message: types.Message, state: FSMContext):
    await state.set_state(NewOrderState.link)
    await message.answer("لطفا لینک فایل درخواستی خود را وارد کنید:")

async def process_link(message: types.Message, state: FSMContext, bot: Bot):
    link = message.text
    user_id = message.from_user.id
    Session = await create_db()
    session = Session()
    
    order_id = random.randint(10000, 99999)

    order = Order(order_id=order_id, user_id=user_id, link=link, status='در حال انجام')
    session.add(order)
    session.commit()

    await message.answer(f"سفارش شما با شماره {order_id} ثبت شد.")
    logging.info(f'New order created by user {user_id} with Order ID {order_id}: {link}')

    try:
        await send_order_notification(bot, link, user_id, order_id)
    except Exception as e:
        logging.error(f"Error sending order notification: {e}")
        await message.answer("خطایی در ارسال اعلان رخ داد. لطفاً با پشتیبانی تماس بگیرید.")

    await state.clear()

async def send_order_notification(bot: Bot, order_link, creator_id, order_id):
    message = f"یک سفارش جدید توسط کاربر با آیدی {creator_id} ثبت شد:\n\nشماره سفارش: {order_id}\nلینک: {order_link}"

    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text="پاسخ به سفارش", callback_data=f"respond_{creator_id}_{order_id}")]
    ])

    try:
        await bot.send_message(chat_id=ADMIN_USER_ID, text=message, reply_markup=keyboard)
        logging.info(f'Order notification sent to admin for order ID {order_id} created by user {creator_id}')
    except Exception as e:
        logging.error(f"Error sending order notification: {e}")
        raise

async def orderlist_command(message: types.Message):
    user_id = message.from_user.id
    Session = await create_db()
    session = Session()
    orders = session.query(Order).filter_by(user_id=user_id, status='در حال انجام').all()
    if orders:
        response = "\n".join([f"Order ID: {order.order_id}, Link: {order.link}" for order in orders])
    else:
        response = "هیچ سفارشی در حال انجام نیست."
    await message.answer(response)
    logging.info(f'User {user_id} requested list of ongoing orders')

async def completeorder_command(message: types.Message):
    user_id = message.from_user.id
    Session = await create_db()
    session = Session()
    orders = session.query(Order).filter_by(user_id=user_id, status='کامل شده').all()

    if orders:
        response = "\n".join([f"Order ID: {order.order_id}, Link: {order.link}" for order in orders])
    else:
        response = "هیچ سفارشی کامل نشده است."
    
    await message.answer(response)
    logging.info(f'User {user_id} requested list of completed orders')

async def support_command(message: types.Message):
    Session = await create_db()
    session = Session()
    text = await get_text_message(session, 'support_message')
    text1 = await get_text_message(session, 'support_message_2')

    if text and text1:
        await message.answer(text, parse_mode="Markdown")
        await message.answer(text1, parse_mode="Markdown")
    else:
        await message.answer("متن‌های پشتیبانی یافت نشد.", parse_mode="Markdown")
    
    logging.info(f'User {message.from_user.id} requested support')

async def admin_command(message: types.Message):
    if message.from_user.id != ADMIN_USER_ID:
        await message.answer("شما مجوز دسترسی به این بخش را ندارید.")
        return
    
    Session = await create_db()
    session = Session()
    orders = session.query(Order).filter_by(status='در حال انجام').all()
    if orders:
        response = "\n".join([f"Order ID: {order.order_id}, Link: {order.link}, User ID: {order.user_id}" for order in orders])
    else:
        response = "هیچ سفارشی در حال انجام نیست."
    await message.answer(response)
    logging.info(f'Admin {message.from_user.id} requested list of ongoing orders')

async def process_admin_response(callback_query: types.CallbackQuery, state: FSMContext):
    data = callback_query.data.split('_')
    creator_id = data[1]
    order_id = data[2]

    await state.update_data(creator_id=creator_id, order_id=order_id)
    await state.set_state(AdminResponseState.waiting_for_response)
    await callback_query.message.answer(f"لطفا پاسخ خود را برای سفارش {order_id} وارد کنید:")
    logging.info(f'Admin {callback_query.from_user.id} initiated response to order {order_id} by user {creator_id}')

async def process_admin_text_response(message: types.Message, state: FSMContext, bot: Bot):
    data = await state.get_data()
    creator_id = data['creator_id']
    order_id = data['order_id']
    response_text = message.text
    document = message.document

    Session = await create_db()
    session = Session()

    try:
        if document:
            file_info = await bot.get_file(document.file_id)
            file_name = document.file_name
            save_dir = 'saved_files'
            os.makedirs(save_dir, exist_ok=True)
            local_file_path = os.path.join(save_dir, file_name)
            downloaded_file = await bot.download_file(file_info.file_path, destination=local_file_path)
            await bot.send_document(chat_id=creator_id, document=document.file_id, caption=f"پاسخ به سفارش {order_id}")
            logging.info(f'Admin response with file sent to user {creator_id} and saved at {local_file_path}')
        else:
            await bot.send_message(chat_id=creator_id, text=f"پاسخ به سفارش {order_id}: {response_text}")
            logging.info(f'Admin response sent to user {creator_id}')

        order = session.query(Order).filter_by(order_id=order_id).first()
        if order:
            order.status = 'کامل شده'
            session.commit()

        await message.answer(f"پاسخ شما ارسال شد و وضعیت سفارش {order_id} به 'کامل شده' تغییر کرد.")
    except Exception as e:
        logging.error(f"Error sending admin response: {e}")
        await message.answer("خطایی در ارسال پاسخ رخ داد. لطفاً دوباره تلاش کنید.")
    
    await state.clear()

async def upload_file_command(message: types.Message, state: FSMContext):
    await state.set_state(FileUploadState.waiting_for_file)
    await message.answer("لطفا تصویر مورد نظر خود را ارسال کنید.")

async def handle_file_upload(message: types.Message, state: FSMContext, bot: Bot):
    logging.info(f"File upload initiated by user {message.from_user.id}")
    if message.document or message.photo:
        user_id = message.from_user.id
        
        if message.document:
            file_id = message.document.file_id
            file_name = message.document.file_name
            logging.info(f"Document received: {file_name}")
        else:
            file_id = message.photo[-1].file_id
            file_name = f"{user_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
            logging.info(f"Photo received: {file_name}")

        save_dir = os.path.join('saved_files', 'bank')
        os.makedirs(save_dir, exist_ok=True)

        file = await bot.get_file(file_id)
        file_path = os.path.join(save_dir, file_name)
        await bot.download_file(file.file_path, file_path)
        logging.info(f"File saved at: {file_path}")

        await message.answer("تصویر شما با موفقیت آپلود شد.")

        try:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text="به‌روزرسانی موجودی", callback_data=f"update_balance_{user_id}")]
            ])
            
            if message.document:
                await bot.send_document(
                    chat_id=ADMIN_USER_ID, 
                    document=file_id, 
                    caption=f"تصویر آپلود شده توسط کاربر {user_id}",
                    reply_markup=keyboard
                )
            else:
                await bot.send_photo(
                    chat_id=ADMIN_USER_ID, 
                    photo=file_id, 
                    caption=f"تصویر آپلود شده توسط کاربر {user_id}",
                    reply_markup=keyboard
                )

            logging.info(f"File '{file_name}' uploaded by user {user_id} and forwarded to admin")
        except Exception as e:
            logging.error(f"Error sending file to admin: {e}")
            await message.answer("خطایی در ارسال فایل به ادمین رخ داد. لطفا با پشتیبانی تماس بگیرید.")
            await state.clear()
    else:
        await message.answer("لطفا یک تصویر یا فایل ارسال کنید.")
        await state.clear()

async def handle_admin_balance_input(message: types.Message, state: FSMContext, bot: Bot):
    if message.from_user.id != ADMIN_USER_ID:
        return

    try:
        balance = float(message.text)
        data = await state.get_data()
        user_id = data['user_id']

        Session = await create_db()
        session = Session()
        user = session.query(User).filter_by(user_id=user_id).first()
        if user:
            user.balance = balance
            session.commit()
            await message.answer(f"موجودی حساب کاربر {user_id} به {balance} به‌روزرسانی شد.")
            await bot.send_message(user_id, f"موجودی حساب شما به {balance} به‌روزرسانی شد.")
        else:
            await message.answer(f"کاربر با شناسه {user_id} یافت نشد.")
        
    except ValueError:
        await message.answer("لطفا یک عدد معتبر وارد کنید.")
    
    await state.clear()

async def handle_unknown_message(message: types.Message):
    logging.info(f"Received unknown message type from user {message.from_user.id}: {message.content_type}")
    await message.reply("متاسفانه نمی‌توانم این نوع پیام را پردازش کنم. لطفاً از دستورات موجود استفاده کنید.")

async def admin_update_balance_command(message: types.Message, state: FSMContext):
    if message.from_user.id != ADMIN_USER_ID:
        await message.answer("شما مجوز دسترسی به این بخش را ندارید.")
        return
    
    await state.set_state(AdminBalanceUpdateState.waiting_for_user_id)
    await message.answer("لطفا شناسه کاربر (user_id) را وارد کنید:")

async def handle_user_id_input(message: types.Message, state: FSMContext):
    if message.from_user.id != ADMIN_USER_ID:
        return

    try:
        user_id = int(message.text)
        await state.update_data(user_id=user_id)
        await state.set_state(AdminBalanceUpdateState.waiting_for_balance)
        await message.answer(f"لطفا موجودی جدید برای کاربر {user_id} را وارد کنید:")
    except ValueError:
        await message.answer("لطفا یک شناسه کاربری معتبر (عدد صحیح) وارد کنید.")

async def update_balance_callback(callback_query: types.CallbackQuery, state: FSMContext):
    if callback_query.from_user.id != ADMIN_USER_ID:
        await callback_query.answer("شما مجوز دسترسی به این بخش را ندارید.")
        return

    user_id = int(callback_query.data.split('_')[2])
    await state.update_data(user_id=user_id)
    await state.set_state(AdminBalanceUpdateState.waiting_for_balance)
    await callback_query.message.answer(f"لطفا موجودی جدید برای کاربر {user_id} را وارد کنید:")
    await callback_query.answer()

# Main bot setup
async def main():
    logging.basicConfig(level=logging.INFO)
    
    bot = Bot(token=BOT_TOKEN)
    dp = Dispatcher(storage=MemoryStorage())

    Session = await create_db()
    session = Session()

    db_handler = DatabaseLogHandler(session)
    logging.getLogger().addHandler(db_handler)

    dp.message.register(start_command, Command("start"))
    dp.message.register(neworder_command, Command("neworder"))
    dp.message.register(orderlist_command, Command("orderlist"))
    dp.message.register(completeorder_command, Command("completeorder"))
    dp.message.register(support_command, Command("support"))
    dp.message.register(admin_command, Command("admin"))
    dp.message.register(upload_file_command, Command("upload"))
   
    dp.message.register(process_link, NewOrderState.link)
    
    dp.callback_query.register(process_admin_response, F.data.startswith("respond_"))
    dp.message.register(process_admin_text_response, AdminResponseState.waiting_for_response)

    dp.message.register(handle_file_upload, FileUploadState.waiting_for_file)
    dp.callback_query.register(update_balance_callback, F.data.startswith("update_balance_"))
    dp.message.register(handle_admin_balance_input, AdminBalanceUpdateState.waiting_for_balance)

    dp.message.register(handle_unknown_message)

    @dp.message()
    async def log_message(message: types.Message):
        logging.info(f"Received message from user {message.from_user.id}: {message.text}")

    await bot.delete_webhook(drop_pending_updates=True)
    await dp.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())