Ref / bot.py
VLADIMIROFF777's picture
Update bot.py
8a69d07 verified
async def main():
if not BOT_TOKEN or not API_ID or not API_HASH:
logger.error("❌ Missing Environment Variables! Please set BOT_TOKEN, API_ID, and API_HASH.")
return
print("[*] Initializing Landing Bot (Cloud Mode)...")
# Session name (stored in memory or ephemeral file)
# Use ConnectionHttp to avoid TimeoutError on some cloud providers
bot = TelegramClient(
'hf_bot_session',
API_ID,
API_HASH,
connection=ConnectionHttp,
connection_retries=None
)
await bot.start(bot_token=BOT_TOKEN)
me = await bot.get_me()
print(f"[+] Bot Started: @{me.username} (ID: {me.id})")
print(f"[*] Admin ID set to: {ADMIN_ID}")
# --- HANDLERS ---
@bot.on(events.NewMessage(pattern='/start'))
async def start_handler(event):
sender = await event.get_sender()
# Ensure sender has a first name
first_name = sender.first_name if sender and sender.first_name else "Friend"
buttons = [
[Button.inline("🇷🇺 РФ", b"q1_yes"), Button.inline("Другое", b"q1_no")]
]
await event.respond(
f"Привет, {first_name}! 👋\n\n"
"Чтобы проверить, доступен ли тебе бонус 1500₽, ответь на 3 простых вопроса.\n\n"
"1️⃣ <b>У тебя гражданство РФ?</b>",
buttons=buttons,
parse_mode='html'
)
@bot.on(events.CallbackQuery)
async def callback_handler(event):
data = event.data.decode()
sender_id = event.sender_id
# Question 1: Citizenship
if data == "q1_yes":
buttons = [[Button.inline("✅ Да, 14+", b"q2_yes"), Button.inline("❌ Нет", b"q2_no")]]
await event.edit(
"✅ Гражданство: РФ\n\n"
"2️⃣ <b>Тебе есть 14 лет?</b>",
buttons=buttons, parse_mode='html'
)
elif data == "q1_no":
await event.edit("🚫 Извини, акция доступна только для граждан РФ (нужен паспорт РФ).")
# Question 2: Age
elif data == "q2_yes":
buttons = [[Button.inline("❌ Нет, я новый клиент", b"q3_yes"), Button.inline("✅ Да, есть", b"q3_no")]]
await event.edit(
"✅ Гражданство: РФ\n✅ Возраст: 14+\n\n"
"3️⃣ <b>У тебя уже есть карты Т-Банка (Тинькофф)?</b>",
buttons=buttons, parse_mode='html'
)
elif data == "q2_no":
await event.edit("🚫 Извини, акция только с 14 лет.")
# Question 3: Existing Cards (Target: No cards)
elif data == "q3_yes": # "Нет, я новый" -> Success
sender = await event.get_sender()
first_name = sender.first_name if sender and sender.first_name else "User"
username = f"@{sender.username}" if sender and sender.username else "No Username"
# User Feedback
await event.edit(
"🎉 <b>Отлично! Ты подходишь.</b>\n\n"
"⏳ <i>Отправляю твою заявку администратору... \nОжидай ссылку в этом чате.</i>",
parse_mode='html'
)
# Notify Admin
msg = (
"🔔 <b>НОВАЯ ЗАЯВКА НА T-BANK</b>\n"
f"👤 Пользователь: {first_name}\n"
f"🆔 ID: <code>{sender_id}</code>\n"
f"Username: {username}\n"
"-------------------\n"
"✅ Гражданство РФ\n"
"✅ Возраст 14+\n"
"✅ Карт нет (новый клиент)\n\n"
"👉 <b>ВВЕДИТЕ ССЫЛКУ:</b>\n"
"Ответьте (Reply) на это сообщение ссылкой или текстом, и я перешлю его пользователю."
)
try:
await bot.send_message(ADMIN_ID, msg, parse_mode='html')
except Exception as e:
logger.error(f"Failed to notify admin: {e}")
elif data == "q3_no": # "Да, есть" -> Fail
await event.edit("🚫 Бонус только для НОВЫХ клиентов (у кого еще нет карт Т-Банка).")
@bot.on(events.NewMessage)
async def admin_reply_handler(event):
# We only care if Admin sends a Reply to a bot message
if event.sender_id == ADMIN_ID and event.is_reply:
reply_msg = await event.get_reply_message()
# Verify the replied message is one of our notifications
me = await bot.get_me()
if reply_msg.sender_id == me.id:
match = re.search(r"ID: <code>(\d+)</code>", reply_msg.text)
if match:
user_id = int(match.group(1))
try:
# Copy the admin's message to the user
await bot.send_message(user_id, event.message)
await event.respond(f"✅ Сообщение отправлено пользователю ({user_id})!")
except Exception as e:
await event.respond(f"❌ Ошибка отправки: {e}")
await bot.run_until_disconnected()
if __name__ == "__main__":
asyncio.run(main())