TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
ADMIN_ID = os.getenv("ADMIN_ID") # باید به صورت رشته باشد
ADMIN_USERNAME = os.getenv("ADMIN_USERNAME")
CARD_NUMBER = os.getenv("CARD_NUMBER")
CARD_HOLDER = os.getenv("CARD_HOLDER")
EXCHANGE_RATE = float(os.getenv("EXCHANGE_RATE", "1300"))
def check_rate_limit(user_id: str, limit: int = 5, window: int = 3600) -> bool:
now = datetime.now()
user_requests = request_limits[user_id]
# حذف درخواستهای قدیمیتر از پنجره زمانی
user_requests = [req for req in user_requests if now - req < timedelta(seconds=window)]
request_limits[user_id] = user_requests
code
if len(user_requests) >= limit:
return False
request_limits[user_id].append(now)
return True
def load_orders_data():
if os.path.exists(DATA_FILE):
with open(DATA_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
return {}
def save_orders_data(data):
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
backup_data(data)
def backup_data(data):
backup_file = f'backup_{datetime.now().strftime("%Y%m%d_%H%M%S")}.json'
with open(backup_file, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
logger.info(f"پشتیبانگیری انجام شد: {backup_file}")
اعتبارسنجی نام و نام خانوادگی (فقط حروف و فاصله مجاز است)
async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
photo = update.message.photo[-1] # دریافت بهترین کیفیت عکس
code
# دریافت فایل عکس
file = await photo.get_file()
file_path = file.file_path
# ایجاد پوشه برای ذخیره عکسها در صورت عدم وجود
os.makedirs(RECEIPTS_DIR, exist_ok=True)
# نامگذاری فایل عکس به صورت یکتای شامل شناسه کاربر و زمان
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
file_name = f"{RECEIPTS_DIR}/{user_id}_{timestamp}.jpg"
# دانلود و ذخیره عکس در سرور
await file.download_to_drive(file_name)
# یافتن سفارش مربوطه که وضعیت آن 'pending' است
user_orders = [o for o in orders_data.values() if o.get('user_id') == user_id and o.get('status') == 'pending']
if not user_orders:
await update.message.reply_text("❌ سفارشی یافت نشد که منتظر ارسال رسید باشد.\nلطفاً با ادمین تماس بگیرید.")
return ConversationHandler.END
# فرض میکنیم آخرین سفارش کاربر
order = sorted(user_orders, key=lambda x: x['order_date'], reverse=True)[0]
order_id = order['order_id']
orders_data[order_id]['receipt'] = file_name
orders_data[order_id]['status'] = 'processing'
save_orders_data(orders_data)
# اطلاعرسانی به کاربر
await update.message.reply_text(
"✅ رسید پرداخت شما دریافت شد و در حال پردازش است. پس از تایید، شارژ سیمکارت شما اعمال خواهد شد.\n\nبرای پیگیری وضعیت سفارش میتوانید از قسمت '📜 تاریخچه سفارشها' استفاده کنید."
)
logger.info(f"دریافت رسید برای سفارش {order_id} از کاربر {user_id}")
# پایان مکالمه
return ConversationHandler.END
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
if not check_rate_limit(user_id):
await update.message.reply_text("⚠️ لطفاً کمی صبر کنید و سپس دوباره تلاش کنید.", reply_markup=main_keyboard())
return
code
# پیام خوشآمدگویی
welcome_text = (
f"سلام {update.effective_user.first_name} عزیز! 👋\n\n"
"به ربات شارژ سیمکارتهای افغانستان خوش آمدید.\n"
"ما بهترین قیمتها و سریعترین خدمات را ارائه میدهیم.\n"
"همین حالا شروع کنید و از تخفیفات ویژه بهرهمند شوید!"
)
# تعریف دکمههای اینلاین
inline_keyboard = [
[InlineKeyboardButton("🔄 ثبت سفارش شارژ", callback_data='new_order')],
[InlineKeyboardButton("📜 تاریخچه سفارشها", callback_data='history')],
[InlineKeyboardButton("📞 تماس با پشتیبانی", callback_data='support')],
[InlineKeyboardButton("ℹ️ راهنما", callback_data='help')]
]
reply_markup = InlineKeyboardMarkup(inline_keyboard)
# پیام پیشنهاد ویژه همراه با دکمههای اینلاین
special_offer = (
"🎉 پیشنهاد ویژه 🌟\n"
"با شارژ بالای ۵۰۰ افغانی از تخفیف ۱۰٪ بهرهمند شوید!"
)
# ارسال پیام خوشآمدگویی
await update.message.reply_text(welcome_text)
# ارسال پیام پیشنهاد ویژه همراه با دکمههای اینلاین
await update.message.reply_text(special_offer, reply_markup=reply_markup)
فرمان /admin
async def admin_panel(update: Update, context: ContextTypes.DEFAULT_TYPE):
if str(update.effective_user.id) != str(ADMIN_ID):
await update.message.reply_text("⛔️ شما دسترسی به این بخش ندارید.")
return
code
keyboard = [
[InlineKeyboardButton("📊 مشاهده همه سفارشها", callback_data='view_all_orders')],
[InlineKeyboardButton("🔍 جستجوی سفارش", callback_data='search_order')],
[InlineKeyboardButton("📈 آمار کلی", callback_data='statistics')],
[InlineKeyboardButton("💱 تغییر نرخ تبدیل", callback_data='change_rate')],
[InlineKeyboardButton("❌ حذف سفارش", callback_data='delete_order')],
[InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data='back_to_main')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
"🔰 پنل مدیریت\n"
f"💱 نرخ فعلی تبدیل: هر افغانی = {EXCHANGE_RATE} تومان\n\n"
"لطفاً یک گزینه را انتخاب کنید:",
reply_markup=reply_markup
)
فرمان /verify_payment
async def verify_payment(update: Update, context: ContextTypes.DEFAULT_TYPE):
if str(update.effective_user.id) != str(ADMIN_ID):
await update.message.reply_text("⛔️ شما دسترسی به این فرمان ندارید.")
return
code
if not context.args:
await update.message.reply_text("❌ لطفاً شناسه سفارش را وارد کنید.\nمثال: /verify_payment ORDER_123")
return
order_id = context.args[0]
if order_id in orders_data:
orders_data[order_id]['status'] = 'paid'
save_orders_data(orders_data)
user_id = orders_data[order_id].get('user_id')
if user_id:
try:
await context.bot.send_message(
chat_id=user_id,
text=f"✅ پرداخت سفارش {order_id} تایید شد و شارژ به زودی انجام خواهد شد."
)
await update.message.reply_text(f"✅ وضعیت سفارش {order_id} به 'پرداخت شده' تغییر کرد.")
logger.info(f"سفارش {order_id} پرداخت شد و به کاربر {user_id} اطلاع داده شد.")
except Exception as e:
await update.message.reply_text("❌ خطا در ارسال پیام به کاربر.")
logger.error(f"Error sending message to user {user_id}: {e}")
else:
await update.message.reply_text("❌ سفارشی با این شناسه یافت نشد.")
فرمان /report
async def generate_report(update: Update, context: ContextTypes.DEFAULT_TYPE):
if str(update.effective_user.id) != str(ADMIN_ID):
await update.message.reply_text("⛔️ شما دسترسی به این فرمان ندارید.")
return
code
total_orders = len(orders_data)
completed_orders = len([o for o in orders_data.values() if o['status'] == 'completed'])
total_revenue = sum(float(o['amount_ir']) for o in orders_data.values() if o['status'] == 'completed')
pending_orders = len([o for o in orders_data.values() if o['status'] == 'pending'])
report = f"""📊 گزارش عملکرد:
📦 کل سفارشها: {total_orders}
✅ سفارشهای تکمیل شده: {completed_orders}
⏳ سفارشهای در انتظار: {pending_orders}
💰 درآمد کل: {total_revenue:,} تومان
"""
await update.message.reply_text(report)
logger.info("گزارش عملکرد توسط ادمین تولید شد.")
await update.callback_query.message.reply_text(
"👤 لطفاً نام و نام خانوادگی خود را وارد کنید:",
reply_markup=reply_markup
)
return NAME
مرحله ورود نام و نام خانوادگی
async def order_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
text = update.message.text.strip()
if not validate_name(text):
await update.message.reply_text("❌ لطفاً نام و نام خانوادگی را به درستی وارد کنید (فقط حروف و فاصله).")
return NAME
context.user_data['name'] = text
await update.message.reply_text("💰 لطفاً مقدار شارژ مورد نظر را به افغانی وارد کنید:")
return AMOUNT
مرحله ورود مقدار شارژ
async def order_amount(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = update.message.text.strip()
if not validate_amount(text):
await update.message.reply_text("❌ لطفاً یک عدد معتبر و منطقی وارد کنید (بین ۱۰ تا ۱۰۰٬۰۰۰ افغانی).")
return AMOUNT
amount = float(text)
context.user_data['amount'] = amount
await update.message.reply_text("📱 لطفاً شماره تلفن مقصد را وارد کنید:")
return PHONE
مرحله ورود شماره تلفن
async def order_phone(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = update.message.text.strip()
if not validate_phone(text):
await update.message.reply_text("❌ لطفاً یک شماره تلفن معتبر وارد کنید (مثلاً ۰۷۱۲۳۴۵۶۷۸۹).")
return PHONE
context.user_data['phone'] = text
await show_invoice(update, context)
return CONFIRM
invoice_text = (
"📋 پیشفاکتور سفارش شما:\n\n"
f"👤 نام و نام خانوادگی: {order_data['name']}\n"
f"💰 مقدار شارژ: {amount_af} افغانی\n"
f"💶 مبلغ قابل پرداخت: {amount_ir:,} تومان\n"
f"📱 شماره تلفن مقصد: {order_data['phone']}\n\n"
f"💳 شماره کارت جهت واریز:\n"
f"{CARD_NUMBER}\n"
f"بنام: {CARD_HOLDER}\n\n"
"لطفاً صحت اطلاعات را بررسی و تأیید کنید."
)
keyboard = [
[
InlineKeyboardButton("✅ تأیید و پرداخت", callback_data='confirm_order'),
InlineKeyboardButton("❌ لغو سفارش", callback_data='cancel_order')
],
[InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data='back_to_main')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
if update.callback_query:
# اگر فراخوانی از طریق دکمه اینلاین بوده است
await update.callback_query.message.reply_text(invoice_text, reply_markup=reply_markup)
else:
# اگر فراخوانی از طریق پیام متنی بوده است
await update.message.reply_text(invoice_text, reply_markup=reply_markup)
orders_data[order_id] = order_data.copy()
save_orders_data(orders_data)
admin_message = (
"🆕 سفارش جدید:\n\n"
f"🔹 شناسه سفارش: {order_id}\n"
f"👤 نام مشتری: {order_data['name']}\n"
f"💰 مقدار شارژ: {amount_af} افغانی\n"
f"💶 مبلغ به تومان: {amount_ir:,} تومان\n"
f"📱 شماره تلفن: {order_data['phone']}\n"
f"📅 تاریخ: {order_data['order_date']}"
)
try:
await context.bot.send_message(chat_id=ADMIN_ID, text=admin_message)
logger.info(f"سفارش {order_id} توسط کاربر {user_id} ثبت شد.")
except Exception as e:
logger.error(f"Failed to send message to admin: {e}")
payment_text = (
"✅ سفارش شما ثبت شد.\n\n"
f"💳 لطفاً مبلغ {amount_ir:,} تومان را به شماره کارت زیر واریز کنید:\n"
f"{CARD_NUMBER}\n"
f"بنام: {CARD_HOLDER}\n\n"
"📸 پس از واریز، لطفاً تصویر رسید پرداخت را ارسال کنید."
)
keyboard = [[InlineKeyboardButton("🏠 بازگشت به منوی اصلی", callback_data='back_to_main')]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.callback_query.edit_message_text(payment_text, reply_markup=reply_markup)
context.user_data.clear()
return RECEIPT
لغو سفارش
async def cancel_order(update: Update, context: ContextTypes.DEFAULT_TYPE):
context.user_data.clear()
await update.callback_query.edit_message_text(
"❌ سفارش شما لغو شد.\n"
"برای ثبت سفارش جدید از منوی اصلی اقدام کنید.",
reply_markup=main_keyboard()
)
return ConversationHandler.END
نمایش تاریخچه سفارشها
async def show_history(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = str(update.effective_user.id)
user_orders = [o for o in orders_data.values() if o.get('user_id') == user_id]
code
if not user_orders:
await update.callback_query.message.reply_text("📝 شما هیچ سفارشی ثبت نکردهاید.", reply_markup=main_keyboard())
return
history_text = "📜 تاریخچه سفارشهای شما:\n\n"
for order in user_orders:
history_text += (
f"🔹 شناسه سفارش: {order['order_id']}\n"
f"💰 مقدار شارژ: {order['amount']} افغانی\n"
f"💶 مبلغ به تومان: {order['amount_ir']:,} تومان\n"
f"📱 شماره تلفن: {order['phone']}\n"
f"📅 تاریخ: {order['order_date']}\n"
f"📋 وضعیت: {ORDER_STATUS.get(order['status'], 'نامشخص')}\n"
"➖➖➖➖➖➖➖➖➖➖\n"
)
keyboard = [[KeyboardButton("🏠 بازگشت به منوی اصلی")]]
reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=False)
await update.callback_query.message.reply_text(history_text, reply_markup=reply_markup)
logger.info(f"کاربر {user_id} تاریخچه سفارشهای خود را مشاهده کرد.")
تماس با پشتیبانی
async def show_support(update: Update, context: ContextTypes.DEFAULT_TYPE):
support_text = (
"📞 راههای ارتباط با پشتیبانی:\n\n"
f"🔹 تلگرام: @{ADMIN_USERNAME}\n"
"🔸 ساعات پاسخگویی: 8 صبح تا 8 شب\n\n"
"برای ارتباط سریعتر لطفاً از تلگرام استفاده کنید."
)
keyboard = [[KeyboardButton("🏠 بازگشت به منوی اصلی")]]
reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=False)
async def show_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
help_text = (
"🔰 راهنمای استفاده از ربات:\n\n"
"1️⃣ برای ثبت سفارش، دکمه '🔰 شروع' را فشار دهید.\n"
"2️⃣ اطلاعات درخواستی را به ترتیب وارد کنید.\n"
"3️⃣ فاکتور نهایی را بررسی و تأیید کنید.\n"
"4️⃣ مبلغ را به شماره کارت اعلام شده واریز کنید.\n"
"5️⃣ تصویر رسید پرداخت را ارسال کنید.\n\n"
"❗️ در صورت نیاز به راهنمایی با پشتیبانی تماس بگیرید."
)
keyboard = [[KeyboardButton("🏠 بازگشت به منوی اصلی")]]
reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=False)
async def show_all_orders(update: Update, context: ContextTypes.DEFAULT_TYPE):
if str(update.effective_user.id) != str(ADMIN_ID):
await update.callback_query.message.reply_text("⛔️ شما دسترسی به این بخش ندارید.")
return
code
if not orders_data:
await update.callback_query.message.reply_text("📝 هیچ سفارشی ثبت نشده است.")
return
for order_id, order_data in orders_data.items():
order_text = (
f"🔹 شناسه سفارش: {order_id}\n"
f"👤 نام: {order_data.get('name', 'نامشخص')}\n"
f"💰 مقدار شارژ: {order_data.get('amount', 0)} افغانی\n"
f"💶 مبلغ به تومان: {order_data.get('amount_ir', 0):,} تومان\n"
f"📱 شماره تلفن: {order_data.get('phone', 'نامشخص')}\n"
f"📅 تاریخ: {order_data.get('order_date', 'نامشخص')}\n"
f"📋 وضعیت: {ORDER_STATUS.get(order_data.get('status', 'pending'), 'نامشخص')}\n"
"➖➖➖➖➖➖➖➖➖➖\n"
)
await update.callback_query.message.reply_text(order_text)
logger.info(f"ادمین سفارش {order_id} را مشاهده کرد.")
شروع جستجوی سفارش توسط ادمین
async def start_order_search(update: Update, context: ContextTypes.DEFAULT_TYPE):
if str(update.effective_user.id) != str(ADMIN_ID):
await update.callback_query.message.reply_text("⛔️ شما دسترسی به این بخش ندارید.")
return
context.user_data['admin_state'] = 'waiting_order_id'
await update.callback_query.message.reply_text("🔍 لطفاً شناسه سفارش را وارد کنید:")
نمایش آمار کلی
async def show_statistics(update: Update, context: ContextTypes.DEFAULT_TYPE):
if str(update.effective_user.id) != str(ADMIN_ID):
await update.callback_query.message.reply_text("⛔️ شما دسترسی به این بخش ندارید.")
return
code
total_orders = len(orders_data)
completed_orders = len([o for o in orders_data.values() if o['status'] == 'completed'])
pending_orders = len([o for o in orders_data.values() if o['status'] == 'pending'])
total_revenue = sum(float(o['amount_ir']) for o in orders_data.values() if o['status'] == 'completed')
stats_text = (
"📊 آمار کلی سیستم:\n\n"
f"📦 تعداد کل سفارشها: {total_orders}\n"
f"✅ سفارشهای تکمیل شده: {completed_orders}\n"
f"⏳ سفارشهای در انتظار: {pending_orders}\n"
f"💰 درآمد کل: {total_revenue:,} تومان"
)
await update.callback_query.message.reply_text(stats_text)
logger.info("ادمین آمار کلی سیستم را مشاهده کرد.")
مدیریت تغییر نرخ تبدیل
async def start_rate_change(update: Update, context: ContextTypes.DEFAULT_TYPE):
if str(update.effective_user.id) != str(ADMIN_ID):
await update.callback_query.message.reply_text("⛔️ شما دسترسی به این بخش ندارید.")
return
context.user_data['admin_state'] = 'waiting_new_rate'
await update.callback_query.message.reply_text(
"💱 لطفاً نرخ جدید تبدیل افغانی به تومان را وارد کنید:\n"
"مثال: 1300"
)
مدیریت حذف سفارش
async def start_order_delete(update: Update, context: ContextTypes.DEFAULT_TYPE):
if str(update.effective_user.id) != str(ADMIN_ID):
await update.callback_query.message.reply_text("⛔️ شما دسترسی به این بخش ندارید.")
return
context.user_data['admin_state'] = 'waiting_delete_id'
await update.callback_query.message.reply_text("❌ لطفاً شناسه سفارش مورد نظر برای حذف را وارد کنید:")
admin_state = context.user_data.get('admin_state')
if admin_state == 'waiting_new_rate':
if not validate_amount(update.message.text):
await update.message.reply_text("❌ لطفاً یک عدد معتبر و منطقی وارد کنید.")
return
try:
new_rate = float(update.message.text)
global EXCHANGE_RATE
EXCHANGE_RATE = new_rate
await update.message.reply_text(f"✅ نرخ تبدیل با موفقیت به {new_rate:,} تومان تغییر کرد.")
# بهروزرسانی نرخ در تمام سفارشهای مقدماتی
for order in orders_data.values():
if order.get('status') == 'pending':
order['amount_ir'] = order['amount'] * EXCHANGE_RATE
save_orders_data(orders_data)
logger.info(f"نرخ تبدیل به {new_rate} تومان تغییر کرد و سفارشهای معلق بهروزرسانی شدند.")
except ValueError:
await update.message.reply_text("❌ لطفاً یک عدد معتبر وارد کنید.")
context.user_data['admin_state'] = None
elif admin_state == 'waiting_order_id':
order_id = update.message.text.strip()
if order_id in orders_data:
order_data = orders_data[order_id]
order_text = (
f"🔹 اطلاعات سفارش:\n\n"
f"شناسه: {order_id}\n"
f"👤 نام: {order_data.get('name', 'نامشخص')}\n"
f"💰 مقدار شارژ: {order_data.get('amount', 0)} افغانی\n"
f"💶 مبلغ به تومان: {order_data.get('amount_ir', 0):,} تومان\n"
f"📱 شماره تلفن: {order_data.get('phone', 'نامشخص')}\n"
f"📅 تاریخ: {order_data.get('order_date', 'نامشخص')}\n"
f"📋 وضعیت: {ORDER_STATUS.get(order_data.get('status', 'pending'), 'نامشخص')}"
)
await update.message.reply_text(order_text)
logger.info(f"ادمین سفارش {order_id} را جستجو کرد و مشاهده کرد.")
else:
await update.message.reply_text("❌ سفارشی با این شناسه یافت نشد.")
context.user_data['admin_state'] = None
elif admin_state == 'waiting_delete_id':
order_id = update.message.text.strip()
if order_id in orders_data:
del orders_data[order_id]
save_orders_data(orders_data)
await update.message.reply_text(f"✅ سفارش {order_id} با موفقیت حذف شد.")
logger.info(f"سفارش {order_id} توسط ادمین حذف شد.")
else:
await update.message.reply_text("❌ سفارشی با این شناسه یافت نشد.")
context.user_data['admin_state'] = None
فرمان /help
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
help_text = (
"🔰 راهنمای استفاده از ربات:\n\n"
"1️⃣ برای ثبت سفارش، دکمه '🔰 شروع' را فشار دهید.\n"
"2️⃣ اطلاعات درخواستی را به ترتیب وارد کنید.\n"
"3️⃣ فاکتور نهایی را بررسی و تأیید کنید.\n"
"4️⃣ مبلغ را به شماره کارت اعلام شده واریز کنید.\n"
"5️⃣ تصویر رسید پرداخت را ارسال کنید.\n\n"
"❗️ در صورت نیاز به راهنمایی با پشتیبانی تماس بگیرید."
)
keyboard = [[KeyboardButton("🏠 بازگشت به منوی اصلی")]]
reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=False)
def main():
if not TOKEN:
logger.error("توکن بات تنظیم نشده است. لطفاً متغیر محیطی TELEGRAM_BOT_TOKEN را تنظیم کنید.")
return
if not ADMIN_ID:
logger.error("شناسه ادمین تنظیم نشده است. لطفاً متغیر محیطی ADMIN_ID را تنظیم کنید.")
return
code
application = Application.builder().token(TOKEN).build()
# تعریف ConversationHandler برای ثبت سفارش
conv_handler = ConversationHandler(
entry_points=[CallbackQueryHandler(start_order, pattern='^new_order$')],
states={
NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, order_name)],
AMOUNT: [MessageHandler(filters.TEXT & ~filters.COMMAND, order_amount)],
PHONE: [MessageHandler(filters.TEXT & ~filters.COMMAND, order_phone)],
CONFIRM: [
CallbackQueryHandler(confirm_order, pattern='^confirm_order$'),
CallbackQueryHandler(cancel_order, pattern='^cancel_order$')
],
RECEIPT: [MessageHandler(filters.PHOTO, handle_photo)]
},
fallbacks=[CallbackQueryHandler(cancel_order, pattern='^cancel_order$')]
)
# افزودن ConversationHandler قبل از هندلرهای عمومی
application.add_handler(conv_handler)
# افزودن هندلرهای فرمان
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("admin", admin_panel))
application.add_handler(CommandHandler("verify_payment", verify_payment))
application.add_handler(CommandHandler("report", generate_report))
application.add_handler(CommandHandler("help", help_command))
# افزودن هندلر CallbackQuery برای دکمههای اینلاین که خارج از ConversationHandler هستند
application.add_handler(CallbackQueryHandler(button_handler))
# افزودن هندلر PHOTO-only بعد از ConversationHandler
application.add_handler(MessageHandler(filters.PHOTO, handle_photo))
# حذف هندلر عمومی MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)
# اگر نیاز دارید، میتوانید آن را با یک شرط اضافه کنید
logger.info("Bot started...")
application.run_polling(allowed_updates=Update.ALL_TYPES)
if name == 'main':
main()
Your Telegram bot implementation for sim card recharges is comprehensive and covers a wide range of functionalities, including user interactions, admin controls, order management, and data persistence. Below is a detailed review of your code, highlighting strengths, potential issues, and suggestions for improvements to enhance functionality, performance, and maintainability.
1. Code Structure and Organization
Strengths:
Modular Functions: You've organized the code into helper functions for tasks like data loading/saving, validation, and rate limiting, which enhances readability and maintainability.
Conversation Handling: Using ConversationHandler to manage multi-step user interactions is an excellent approach for guiding users through the ordering process.
Logging: Implementing logging with both file and stream handlers is beneficial for monitoring and debugging.
Suggestions:
Modularization: Consider splitting the code into separate modules or files (e.g., handlers, utilities, admin functions) to improve readability and manageability, especially as the bot scales.
Configuration Management: Use a dedicated configuration file (e.g., config.py, .env) to manage environment variables and constants more effectively.
2. Environment Variables and Configuration
Strengths:
Environment Variables: Storing sensitive information like TOKEN, ADMIN_ID, etc., as environment variables is a good security practice.
Suggestions:
Validation of Environment Variables:
Ensure all required environment variables are present at startup and handle missing variables gracefully.
Convert ADMIN_ID to int if it's meant to be a numeric Telegram user ID. Currently, it's treated as a string, which may lead to mismatches during comparisons.
python
ADMIN_ID = os.getenv("ADMIN_ID")
if ADMIN_ID:
ADMIN_ID = int(ADMIN_ID)
Default Values and Type Casting:
Cast environment variables to appropriate types immediately after retrieval to avoid type-related issues later.
This is correctly implemented, but ensure all numeric environment variables are handled similarly.
3. Data Persistence and Management
Strengths:
JSON for Data Storage: Using JSON for storing orders is straightforward and human-readable, which is suitable for small-scale applications.
Potential Issues:
Concurrency Issues:
Race Conditions: Reading from and writing to orders_data.json without locks can lead to race conditions if multiple parts of the bot try to access it simultaneously.
Data Corruption: Simultaneous writes might corrupt the JSON file.
Suggestions:
Use Thread Locks: Implement threading locks around file read/write operations to prevent race conditions.
python
import threading
data_lock = threading.Lock()
def load_orders_data():
with data_lock:
if os.path.exists(DATA_FILE):
with open(DATA_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
return {}
def save_orders_data(data):
with data_lock:
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
backup_data(data)
Consider Using a Database:
For scalability and better concurrency handling, consider using a lightweight database like SQLite or a full-fledged solution like PostgreSQL.
Libraries such as SQLAlchemy can help manage database interactions more efficiently.
4. Rate Limiting
Strengths:
Prevents Spam: Implementing check_rate_limit helps prevent abuse by limiting the number of requests a user can make within a specific time window.
Potential Issues:
Mutable Default Arguments: Using mutable objects like defaultdict for request_limits can lead to unintended side effects.
Suggestions:
Avoid Mutable Defaults: Ensure that mutable default arguments are handled correctly to prevent unexpected behaviors.
Your current implementation is fine since defaultdict is initialized outside the function. Just ensure that the request_limits dictionary is managed properly.
Enhance Feedback:
Notify users when they hit the rate limit with information about when they can retry.
python
from datetime import datetime
def check_rate_limit(user_id: str, limit: int = 5, window: int = 3600) -> (bool, int):
now = datetime.now()
user_requests = request_limits[user_id]
user_requests = [req for req in user_requests if now - req < timedelta(seconds=window)]
request_limits[user_id] = user_requests
if len(user_requests) >= limit:
reset_time = (user_requests[0] + timedelta(seconds=window) - now).seconds
return False, reset_time
request_limits[user_id].append(now)
return True, 0
Update the usage accordingly to inform the user about when they can make the next request.
5. Validation Functions
Strengths:
Input Validation: Implementing functions like validate_name, validate_amount, and validate_phone ensures that user inputs meet expected formats.
Potential Issues:
Internationalization: The validate_name function currently only accepts Persian and English letters. Consider if support for other languages or special characters is needed.
The regex for phone numbers assumes specific patterns (e.g., starting with 07 followed by certain digits). Ensure it covers all valid phone number formats you expect.
Make error messages more informative by specifying exactly what is expected (e.g., "Please enter a valid Afghan phone number starting with 07...").
6. Handling User Orders
Strengths:
Comprehensive Order Flow: The conversation handles collecting necessary information, confirming the order, and processing receipts, which provides a smooth user experience.
Potential Issues:
Order Identification:
Generating order_id based solely on the timestamp (ORDER_YYYYMMDD_HHMMSS) can lead to duplicate IDs if multiple orders are placed within the same second.
Order Retrieval:
When handling receipts, you retrieve the latest pending order, which might not always correspond to the order the user intended to update.
Suggestions:
Ensure Unique Order IDs:
Incorporate a unique identifier, such as a UUID, to guarantee uniqueness.
Consider tagging each user session with the specific order ID to ensure receipts are associated with the correct order, especially if multiple orders are allowed.
Error Handling:
Implement error handling for scenarios where the order data might be inconsistent or missing expected fields.
7. Admin Functionalities
Strengths:
Comprehensive Admin Controls: The admin panel allows viewing all orders, searching, changing exchange rates, deleting orders, and generating reports, which are essential management features.
Access Control: Properly restricts admin functionalities to authorized users based on ADMIN_ID.
Potential Issues:
Global Variable for Exchange Rate:
Changing EXCHANGE_RATE via admin updates a global variable, which isn’t persisted. If the bot restarts, the updated rate is lost unless it's reloaded from a persistent storage.
Concurrent Admin Actions:
Similar to user data, concurrent admin actions (like multiple rate changes) can lead to inconsistent states.
Suggestions:
Persist Exchange Rate:
Store the exchange rate in the orders_data.json or a separate configuration file to persist changes across bot restarts.
Ensure that admin actions that modify global states (like exchange rates) are thread-safe.
Enhance Admin Feedback:
Provide confirmations after admin actions (e.g., "Exchange rate updated successfully") and handle invalid inputs gracefully.
Secure Admin Commands:
Ensure that admin commands cannot be accessed by non-admin users. While you have some checks, it's crucial to wrap admin-specific handlers with decorators or checks to enforce access control consistently.
8. Handling Images (Receipts)
Strengths:
Receipt Processing: Allows users to upload payment receipts, which are then associated with their orders.
Potential Issues:
File Storage Management:
Over time, the receipts directory might accumulate many images, leading to storage issues.
File Naming Conflicts:
Although you use timestamps, using unique identifiers like UUIDs can better prevent naming conflicts.
Security Concerns:
Storing user-uploaded images without proper sanitization can pose security risks.
Suggestions:
Organize Receipts:
Organize receipts into subdirectories based on user IDs or order IDs to manage files better.
Extensive Logging: Logging important actions like order creation, admin actions, and errors helps in monitoring and debugging.
Potential Issues:
Unhandled Exceptions: Some parts of the code may raise exceptions that aren't caught, potentially causing the bot to crash.
Suggestions:
Global Exception Handling:
Implement a global error handler to catch and log unexpected errors without crashing the bot.
python
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE):
logger.error(msg="Exception while handling an update:", exc_info=context.error)
# Optionally notify the admin
if str(update.effective_user.id) != str(ADMIN_ID):
await update.message.reply_text("❌ مشکلی رخ داد. لطفاً بعداً دوباره تلاش کنید.")
# Add to the main function
application.add_error_handler(error_handler)
Detailed Logging:
Include more contextual information in logs (e.g., user ID, order ID) to make debugging easier.
10. Security Considerations
Potential Issues:
Sensitive Information Exposure:
Displaying sensitive information such as CARD_NUMBER and CARD_HOLDER in messages can be a security risk.
Suggestions:
Mask Sensitive Data:
Show only partial credit card numbers to users and ensure that sensitive details are protected.
Ensure that orders_data.json and receipt images are stored securely with appropriate file permissions to prevent unauthorized access.
Use HTTPS and Secure Channels:
Ensure all communications, especially when dealing with payments, occur over secure channels.
Input Sanitization:
Sanitize all user inputs to prevent injection attacks or malicious inputs.
11. Scalability and Performance
Potential Issues:
Data Persistence with JSON:
As the number of orders grows, performance can degrade due to the limitations of JSON for concurrent access and larger datasets.
Suggestions:
Adopt a Database Solution:
Transition to using a database like SQLite, PostgreSQL, or MongoDB to handle data persistence more efficiently and support scalability.
Asynchronous File Operations:
Consider using asynchronous file I/O to prevent blocking the event loop, especially if sticking with JSON.
python
import aiofiles
async def load_orders_data():
if os.path.exists(DATA_FILE):
async with aiofiles.open(DATA_FILE, 'r', encoding='utf-8') as f:
data = await f.read()
return json.loads(data)
return {}
Caching Mechanisms:
Implement caching for frequently accessed data to reduce I/O operations and improve response times.
12. User Experience Enhancements
Suggestions:
Internationalization (i18n):
If you plan to support multiple languages, integrate an internationalization library to manage translations efficiently.
Inline Keyboards and Menus:
Enhance the user interface with more intuitive inline keyboards and navigation options to improve user engagement.
Persistent Menus:
Implement persistent menus using the force_reply or similar mechanisms to guide users back to main options without navigating through multiple menus.
Feedback and Confirmation:
Provide immediate feedback and confirmations after each user action to reassure users that their actions are being processed.
Timeout Mechanisms:
Implement timeouts for conversations so that inactive sessions are closed gracefully, freeing up resources and maintaining data integrity.
python
conv_handler = ConversationHandler(
# ... existing setup ...
conversation_timeout=300, # 5 minutes
# ... rest of the code ...
)
13. Testing and Deployment
Suggestions:
Unit Testing:
Write unit tests for critical functions like validation, data handling, and admin actions to ensure reliability.
Continuous Integration (CI):
Set up CI pipelines to automate testing and deployment processes, ensuring that new changes don't break existing functionality.
Deployment Considerations:
Use process managers like systemd, supervisord, or containerization tools like Docker to manage the bot's deployment and ensure high availability.
14. Additional Functional Enhancements
Suggestions:
Payment Integration:
Instead of manual payment receipt uploads, integrate with payment gateways or APIs to automate payment verification, enhancing security and efficiency.
Notification System:
Implement notifications for users about order status changes, adding more transparency and improving user trust.
Analytics and Reporting:
Enhance reporting features with more detailed analytics, such as daily, weekly, or monthly reports, and support exporting data in various formats (e.g., CSV, Excel).
Multi-language Support:
If your user base is diverse, consider adding support for multiple languages to cater to a broader audience.
Conclusion
Your bot covers essential features required for managing sim card recharge orders effectively. By addressing the suggestions above, you can enhance the bot's reliability, security, scalability, and overall user experience. Implementing robust error handling, secure data management practices, and considering scalability aspects will ensure that your bot remains efficient as your user base grows. Additionally, continuously seeking user feedback and iterating on the bot's functionalities will help in aligning it closely with user needs and expectations.
If you have any specific issues or need further assistance on particular parts of your code, feel free to ask!