231 lines
10 KiB
Python
231 lines
10 KiB
Python
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}")
|