hyperliqbot/telegram_bot/onboarding.py
Cipher Zero Protocol 620b345f3d more kinda works
2025-06-09 02:46:59 +03:00

231 lines
10 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from datetime import datetime
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, InputMediaPhoto
from telegram.ext import CallbackContext
logger = logging.getLogger(__name__)
class OnboardingHandler:
"""
Handles the onboarding flow for new users:
- Welcome tutorial
- Agent wallet creation guide
- Funding instructions (with QR code)
- First trade walkthrough
- Safety guidelines
"""
def __init__(self, wallet_manager):
self.wallet_manager = wallet_manager
async def start_onboarding(self, update: Update, context: CallbackContext):
"""Entry point for onboarding tutorial."""
welcome_msg = (
"๐Ÿ‘‹ *Welcome to Hyperliquid Alpha Bot!*\n\n"
"This quick tutorial will help you:\n"
"1๏ธโƒฃ Create your secure agent wallet\n"
"2๏ธโƒฃ Fund your wallet (with QR code)\n"
"3๏ธโƒฃ Place your first trade\n"
"4๏ธโƒฃ Learn safety best practices\n\n"
"Ready to get started?"
)
keyboard = [
[InlineKeyboardButton("๐Ÿš€ Start Tutorial", callback_data="onboard_step_1")],
[InlineKeyboardButton("Skip Tutorial", callback_data="onboard_skip")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(welcome_msg, parse_mode='Markdown', reply_markup=reply_markup)
async def handle_onboarding_callback(self, update: Update, context: CallbackContext):
"""Handles onboarding steps via callback queries."""
query = update.callback_query
data = query.data
user_id = query.from_user.id
if data == "onboard_step_1":
await self.agent_wallet_guide(query, context)
elif data == "onboard_step_2":
await self.funding_instructions(query, context)
elif data == "onboard_step_3":
await self.first_trade_walkthrough(query, context)
elif data == "onboard_step_4":
await self.safety_guidelines(query, context)
elif data == "onboard_complete":
await self.onboarding_complete(query, context)
elif data == "onboard_skip":
await query.edit_message_text("You can access the tutorial anytime with /tutorial.", parse_mode='Markdown')
else:
await query.answer("Unknown onboarding step.")
async def agent_wallet_guide(self, query, context):
"""Guide users through agent wallet creation"""
msg = (
"๐Ÿ” *Step 1: Create Your Agent Wallet*\n\n"
"Agent wallets let you trade securely without exposing your private key.\n\n"
"**How it works:**\n"
"โ€ข The bot creates a dedicated trading wallet for you\n"
"โ€ข You fund it with USDC for trading\n"
"โ€ข All trades happen through this secure wallet\n"
"โ€ข You maintain full control of your funds\n\n"
"Ready to create your wallet?"
)
keyboard = [
[InlineKeyboardButton("โœ… Create Agent Wallet", callback_data="create_agent")],
[InlineKeyboardButton("โ“ Learn More", callback_data="agent_wallet_info")],
[InlineKeyboardButton("Next: Funding โ†’", callback_data="onboard_step_2")]
]
await query.edit_message_text(msg, parse_mode='Markdown', reply_markup=InlineKeyboardMarkup(keyboard))
async def funding_instructions(self, query, context):
"""Show detailed funding instructions with QR code"""
user_id = query.from_user.id
user_wallet = await self.wallet_manager.get_user_wallet(user_id) if self.wallet_manager else None
address = user_wallet['address'] if user_wallet else "0x1234...abcd"
msg = (
"๐Ÿ’ฐ *Step 2: Fund Your Agent Wallet*\n\n"
f"**Your Agent Wallet Address:**\n`{address}`\n\n"
"**Funding Instructions:**\n"
"โ€ข Send USDC (minimum 10 USDC) to the address above\n"
"โ€ข Use *Arbitrum One* network only\n"
"โ€ข Funding typically takes 1-2 minutes\n"
"โ€ข The bot will notify you when funds arrive\n\n"
"**Important:** Only send USDC on Arbitrum network!"
)
keyboard = [
[InlineKeyboardButton("๐Ÿ“‹ Copy Address", callback_data=f"copy_address_{address}")],
[InlineKeyboardButton("โœ… I've Funded My Wallet", callback_data="onboard_step_3")],
[InlineKeyboardButton("โ† Back", callback_data="onboard_step_1")]
]
# Generate QR code for the address
qr_url = f"https://api.qrserver.com/v1/create-qr-code/?size=300x300&data={address}&format=png"
try:
await query.edit_message_media(
media=InputMediaPhoto(qr_url, caption=msg, parse_mode='Markdown'),
reply_markup=InlineKeyboardMarkup(keyboard)
)
except Exception as e:
# Fallback to text message if image fails
logger.warning(f"Failed to send QR code: {e}")
await query.edit_message_text(msg, parse_mode='Markdown', reply_markup=InlineKeyboardMarkup(keyboard))
async def first_trade_walkthrough(self, query, context):
"""Walk users through their first trade"""
msg = (
"๐Ÿ“ˆ *Step 3: Place Your First Trade*\n\n"
"Once your wallet is funded, you can start trading!\n\n"
"**Available Strategies:**\n"
"โ€ข **Grid Trading:** `/start_trading grid BTC 10 0.002`\n"
" Automated buy/sell orders at different price levels\n\n"
"โ€ข **Momentum Trading:** `/start_trading momentum ETH`\n"
" Follows price trends and market momentum\n\n"
"**Monitoring Your Trades:**\n"
"โ€ข `/portfolio` - View your positions and P&L\n"
"โ€ข `/status` - Check wallet and trading status\n"
"โ€ข `/stop_trading` - Stop all strategies\n\n"
"Ready for the final safety tips?"
)
keyboard = [
[InlineKeyboardButton("๐Ÿ›ก๏ธ Next: Safety Tips", callback_data="onboard_step_4")],
[InlineKeyboardButton("๐Ÿ”„ Test Grid Trading", callback_data="demo_grid_trade")],
[InlineKeyboardButton("โ† Back", callback_data="onboard_step_2")]
]
await query.edit_message_text(msg, parse_mode='Markdown', reply_markup=InlineKeyboardMarkup(keyboard))
async def safety_guidelines(self, query, context):
"""Show comprehensive safety guidelines"""
msg = (
"๐Ÿ›ก๏ธ *Step 4: Safety & Security Guidelines*\n\n"
"**Security Best Practices:**\n"
"โ€ข Never share your private keys with anyone\n"
"โ€ข Only fund from trusted wallet addresses\n"
"โ€ข Start with small amounts while learning\n"
"โ€ข Always verify transactions before confirming\n\n"
"**Risk Management:**\n"
"โ€ข Set stop-losses for protection\n"
"โ€ข Don't invest more than you can afford to lose\n"
"โ€ข Monitor your positions regularly\n"
"โ€ข Use `/emergency_stop` if needed\n\n"
"**Getting Help:**\n"
"โ€ข `/help` - List all commands\n"
"โ€ข `/status` - Check system status\n"
"โ€ข Contact support for urgent issues\n\n"
"๐ŸŽ‰ **Congratulations! You're ready to trade securely!**"
)
keyboard = [
[InlineKeyboardButton("๐ŸŽฏ Complete Tutorial", callback_data="onboard_complete")],
[InlineKeyboardButton("๐Ÿ“š Advanced Features", callback_data="show_advanced_features")],
[InlineKeyboardButton("โ† Back", callback_data="onboard_step_3")]
]
await query.edit_message_text(msg, parse_mode='Markdown', reply_markup=InlineKeyboardMarkup(keyboard))
async def onboarding_complete(self, query, context):
"""Complete the onboarding process"""
user_id = query.from_user.id
completion_msg = (
"๐ŸŽ‰ *Onboarding Complete!*\n\n"
"You're now ready to start trading with Hyperliquid Alpha Bot!\n\n"
"**Quick Start Commands:**\n"
"โ€ข `/agent` - Manage your agent wallet\n"
"โ€ข `/portfolio` - View your portfolio\n"
"โ€ข `/start_trading grid BTC` - Start grid trading\n"
"โ€ข `/analytics` - View detailed analytics\n\n"
"**Need Help?**\n"
"โ€ข `/help` - Full command list\n"
"โ€ข `/tutorial` - Restart this tutorial\n\n"
"Happy trading! ๐Ÿš€"
)
keyboard = [
[InlineKeyboardButton("๐Ÿ” Go to Agent Wallet", callback_data="agent_status_shortcut")],
[InlineKeyboardButton("๐Ÿ“Š View Analytics", callback_data="show_analytics")],
[InlineKeyboardButton("๐ŸŽฏ Start Trading", callback_data="trading_quick_start")]
]
await query.edit_message_text(completion_msg, parse_mode='Markdown', reply_markup=InlineKeyboardMarkup(keyboard))
# Mark user as onboarded in database if available
if hasattr(self, 'database') and self.database:
try:
await self.database.execute(
"UPDATE users SET onboarded = 1, onboard_date = ? WHERE user_id = ?",
[datetime.now().isoformat(), user_id]
)
except Exception as e:
logger.warning(f"Failed to mark user {user_id} as onboarded: {e}")
async def handle_funding_notification(self, user_id: int, balance: float, telegram_app):
"""Handle funding notification from wallet manager"""
try:
funding_msg = f"""
๐ŸŽ‰ **Wallet Funded Successfully!**
๐Ÿ’ฐ **Balance:** ${balance:.2f} USDC
โœ… **Status:** Ready for trading
Choose your trading strategy to get started:
"""
keyboard = [
[InlineKeyboardButton("๐Ÿš€ Choose Strategy", callback_data="choose_strategy")],
[InlineKeyboardButton("๐Ÿ“Š View Portfolio", callback_data="view_portfolio")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
# Send notification to user
await telegram_app.bot.send_message(
chat_id=user_id,
text=funding_msg,
parse_mode='Markdown',
reply_markup=reply_markup
)
logger.info(f"Sent funding notification to user {user_id}")
except Exception as e:
logger.error(f"Error sending funding notification to user {user_id}: {e}")