"""
Instagram AI Bot - Complete Streamlit Application
Auto-reply to DMs and Comments using Llama 3.1 AI
Created with ๐
"""
import streamlit as st
import time
import json
import random
from datetime import datetime
from pathlib import Path
from instagram_handler import InstagramHandler
from ai_engine import AIEngine
from bot_engine import BotEngine
from config import DEFAULT_SYSTEM_PROMPT, BOT_CONFIG, MODEL_CONFIG
# ============================================================
# PAGE CONFIGURATION
# ============================================================
st.set_page_config(
page_title="InstaBot AI ๐ค๐",
page_icon="๐ค",
layout="centered",
initial_sidebar_state="collapsed",
)
# ============================================================
# CUSTOM CSS (same as Section 1 - keeping it complete)
# ============================================================
st.markdown("""
""", unsafe_allow_html=True)
# ============================================================
# SESSION STATE INITIALIZATION
# ============================================================
def init_session_state():
defaults = {
"ig_handler": None,
"ai_engine": None,
"bot_engine": None,
"logged_in": False,
"login_error": "",
"show_2fa": False,
"show_challenge": False,
"login_username": "",
"profile_info": {},
"system_prompt": "",
"auto_dm_enabled": False,
"auto_comment_enabled": False,
"bot_running": False,
"activity_log": [],
"total_dms_replied": 0,
"total_comments_replied": 0,
"bot_start_time": None,
"model_loaded": False,
"model_loading": False,
"model_status": "",
"current_page": "login",
}
for key, val in defaults.items():
if key not in st.session_state:
st.session_state[key] = val
init_session_state()
# ============================================================
# HELPER FUNCTIONS
# ============================================================
def add_log(message: str, log_type: str = "info"):
timestamp = datetime.now().strftime("%H:%M:%S")
emoji_map = {
"success": "โ
", "error": "โ", "info": "โน๏ธ",
"warning": "โ ๏ธ", "dm": "๐", "comment": "๐ฌ", "bot": "๐ค",
}
emoji = emoji_map.get(log_type, "๐")
st.session_state.activity_log.insert(0, {
"time": timestamp,
"message": f"{emoji} {message}",
"type": log_type,
})
if len(st.session_state.activity_log) > 100:
st.session_state.activity_log = st.session_state.activity_log[:100]
def format_number(num: int) -> str:
if num >= 1_000_000: return f"{num / 1_000_000:.1f}M"
elif num >= 1_000: return f"{num / 1_000:.1f}K"
return str(num)
def get_ig_handler() -> InstagramHandler:
if st.session_state.ig_handler is None:
st.session_state.ig_handler = InstagramHandler()
return st.session_state.ig_handler
def get_ai_engine() -> AIEngine:
if st.session_state.ai_engine is None:
st.session_state.ai_engine = AIEngine()
return st.session_state.ai_engine
def get_bot_engine() -> BotEngine:
if st.session_state.bot_engine is None:
ig = get_ig_handler()
ai = get_ai_engine()
st.session_state.bot_engine = BotEngine(
ig_handler=ig,
ai_engine=ai,
log_callback=add_log,
)
return st.session_state.bot_engine
def render_header():
st.markdown("""
""", unsafe_allow_html=True)
# ============================================================
# LOGIN PAGE
# ============================================================
def render_login_page():
render_header()
st.markdown('', unsafe_allow_html=True)
st.markdown('
๐ Instagram Login
', unsafe_allow_html=True)
st.markdown("""
๐ก Tera login info sirf is device pe save hoga. Hum kuch store nahi karte server pe.
""", unsafe_allow_html=True)
username = st.text_input("Username", placeholder="Instagram username", key="login_user_input", label_visibility="collapsed")
password = st.text_input("Password", type="password", placeholder="Password", key="login_pass_input", label_visibility="collapsed")
st.markdown("
", unsafe_allow_html=True)
# 2FA Section
if st.session_state.show_2fa:
st.markdown('', unsafe_allow_html=True)
st.markdown('
๐ Two-Factor Auth
', unsafe_allow_html=True)
st.markdown('
Authenticator app ya SMS se 2FA code daalo.
', unsafe_allow_html=True)
tfa_code = st.text_input("2FA Code", placeholder="6-digit code", max_chars=6, key="tfa_input", label_visibility="collapsed")
if st.button("โ
Verify Code", key="verify_2fa"):
if tfa_code:
handler = get_ig_handler()
with st.spinner("Verifying... โณ"):
result = handler.complete_two_factor(tfa_code)
if result["success"]:
st.session_state.logged_in = True
st.session_state.show_2fa = False
st.session_state.current_page = "dashboard"
add_log(f"Logged in as @{username}", "success")
st.rerun()
else:
st.error(result.get("error", "Failed"))
st.markdown("
", unsafe_allow_html=True)
# Challenge Section
if st.session_state.show_challenge:
st.markdown('', unsafe_allow_html=True)
st.markdown('
โ ๏ธ Security Challenge
', unsafe_allow_html=True)
st.markdown('
Email/phone pe aaya verification code daalo.
', unsafe_allow_html=True)
ch_code = st.text_input("Security Code", placeholder="Code", max_chars=6, key="challenge_input", label_visibility="collapsed")
if st.button("โ
Verify", key="verify_challenge"):
if ch_code:
handler = get_ig_handler()
with st.spinner("Verifying... โณ"):
result = handler.complete_challenge(ch_code)
if result["success"]:
st.session_state.logged_in = True
st.session_state.show_challenge = False
st.session_state.current_page = "dashboard"
add_log(f"Logged in as @{username}", "success")
st.rerun()
else:
st.error(result.get("error", "Failed"))
st.markdown("
", unsafe_allow_html=True)
# Login Button
if st.button("๐ Login to Instagram", key="login_btn"):
if not username or not password:
st.error("Username aur password dono daalo! ๐ค")
else:
handler = get_ig_handler()
with st.spinner("Logging in... โณ"):
result = handler.login(username, password)
if result.get("success"):
st.session_state.logged_in = True
st.session_state.current_page = "dashboard"
st.session_state.login_username = username
st.session_state.login_error = ""
add_log(f"Logged in as @{username}", "success")
st.balloons()
st.rerun()
elif result.get("two_factor"):
st.session_state.show_2fa = True
st.rerun()
elif result.get("challenge"):
st.session_state.show_challenge = True
st.rerun()
else:
st.session_state.login_error = result.get("error", "Login failed")
st.error(result.get("error", "Login failed"))
if st.session_state.login_error and not st.session_state.show_2fa and not st.session_state.show_challenge:
st.markdown(f'{st.session_state.login_error}
', unsafe_allow_html=True)
st.markdown("""
๐ Credentials sirf login ke liye use hote hain. Kuch store nahi hota.
""", unsafe_allow_html=True)
# ============================================================
# DASHBOARD PAGE
# ============================================================
def render_dashboard():
handler = get_ig_handler()
ai = get_ai_engine()
bot = get_bot_engine()
if not handler.is_logged_in:
st.session_state.logged_in = False
st.session_state.current_page = "login"
st.rerun()
return
if not st.session_state.profile_info:
with st.spinner("Loading profile... โจ"):
st.session_state.profile_info = handler.get_profile_info()
profile = st.session_state.profile_info
# Sync bot stats
if bot.is_running:
stats = bot.get_stats()
st.session_state.total_dms_replied = stats["total_dms_replied"]
st.session_state.total_comments_replied = stats["total_comments_replied"]
st.session_state.bot_running = True
# ---- TOP BAR ----
col1, col2, col3 = st.columns([1, 2, 1])
with col1:
if st.button("โ๏ธ", key="settings_btn", help="Settings"):
st.session_state.current_page = "settings"
st.rerun()
with col2:
st.markdown('InstaBot AI ๐ค
', unsafe_allow_html=True)
with col3:
if st.button("๐", key="logs_btn", help="Logs"):
st.session_state.current_page = "logs"
st.rerun()
# ---- PROFILE CARD ----
username_display = profile.get("username", handler.username)
fullname_display = profile.get("full_name", "User")
first_letter = fullname_display[0].upper() if fullname_display else "U"
bot_status = st.session_state.bot_running
st.markdown(f"""
{first_letter}
{fullname_display}
@{username_display}
{'๐ข Bot ON' if bot_status else '๐ด Bot OFF'}
{format_number(profile.get('follower_count', 0))}
Followers
{format_number(profile.get('following_count', 0))}
Following
{format_number(profile.get('media_count', 0))}
Posts
""", unsafe_allow_html=True)
# ---- AI MODEL STATUS ----
ai_status = ai.get_status()
if ai_status["model_loaded"]:
model_badge = '๐ง AI Ready'
elif ai_status["fallback_mode"]:
model_badge = 'โก Smart Fallback'
else:
model_badge = 'โ Not Loaded'
st.markdown(f"""
๐ฆ AI Engine
{ai_status.get('gpu_name', ai_status['device'].upper())}
{'โข ' + ai_status.get('gpu_memory_allocated', '') if ai_status.get('gpu_memory_allocated') else ''}
{model_badge}
""", unsafe_allow_html=True)
# Load Model Button (if not loaded)
if not ai_status["model_loaded"] and not ai_status["fallback_mode"]:
st.markdown('', unsafe_allow_html=True)
if st.button("๐ง Load AI Model", key="load_model_btn"):
with st.spinner("Loading Llama 3.1 8B... This may take 2-5 minutes โณ๐ฆ"):
result = ai.load_model()
if result["success"]:
st.session_state.model_loaded = True
add_log(result["message"], "success")
st.success(result["message"])
st.rerun()
else:
st.error(result.get("message", "Failed to load model"))
st.markdown('
', unsafe_allow_html=True)
# ---- BOT STATS ----
st.markdown(f"""
๐ Bot Stats
{st.session_state.total_dms_replied}
DMs Replied
{st.session_state.total_comments_replied}
Comments
{len(st.session_state.activity_log)}
Actions
""", unsafe_allow_html=True)
# ---- QUICK CONTROLS ----
st.markdown('', unsafe_allow_html=True)
st.markdown('
โก Quick Controls
', unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
auto_dm = st.checkbox("๐ Auto DM", value=st.session_state.auto_dm_enabled, key="q_dm")
st.session_state.auto_dm_enabled = auto_dm
with col2:
auto_comment = st.checkbox("๐ฌ Auto Comment", value=st.session_state.auto_comment_enabled, key="q_comment")
st.session_state.auto_comment_enabled = auto_comment
st.markdown("
", unsafe_allow_html=True)
# ---- PROMPT PREVIEW ----
current_prompt = st.session_state.system_prompt or DEFAULT_SYSTEM_PROMPT
prompt_preview = current_prompt[:80] + "..." if len(current_prompt) > 80 else current_prompt
prompt_label = "Custom" if st.session_state.system_prompt else "Default"
st.markdown(f"""
๐ง AI Prompt ({prompt_label})
{prompt_preview}
โ๏ธ Settings mein jaake change karo
""", unsafe_allow_html=True)
# ---- START / STOP BOT ----
st.markdown("
", unsafe_allow_html=True)
if not st.session_state.bot_running:
if st.button("๐ Start Bot", key="start_bot"):
if not st.session_state.auto_dm_enabled and not st.session_state.auto_comment_enabled:
st.error("Pehle koi feature enable karo! DM ya Comment ๐ค")
else:
bot = get_bot_engine()
# Load AI model if not loaded
if not ai.is_loaded and not ai.use_fallback:
with st.spinner("Loading AI model first... โณ"):
ai.load_model()
result = bot.start(
auto_dm=st.session_state.auto_dm_enabled,
auto_comment=st.session_state.auto_comment_enabled,
system_prompt=st.session_state.system_prompt,
)
if result["success"]:
st.session_state.bot_running = True
st.session_state.bot_start_time = datetime.now()
st.success(result["message"])
st.rerun()
else:
st.error(result["message"])
else:
# Running status
if st.session_state.bot_start_time:
uptime = datetime.now() - st.session_state.bot_start_time
hours, remainder = divmod(int(uptime.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
st.markdown(f"""
๐ข Bot is running!
Uptime: {hours}h {minutes}m {seconds}s
Checking every 2-3 minutes โข 30-60s delay between actions
""", unsafe_allow_html=True)
st.markdown('', unsafe_allow_html=True)
if st.button("โน๏ธ Stop Bot", key="stop_bot"):
bot = get_bot_engine()
result = bot.stop()
st.session_state.bot_running = False
st.session_state.bot_start_time = None
st.info(result["message"])
st.rerun()
st.markdown('
', unsafe_allow_html=True)
# ---- TEST AI REPLY ----
with st.expander("๐งช Test AI Reply"):
test_msg = st.text_input("Test message:", placeholder="hi kaise ho?", key="test_msg")
test_type = st.selectbox("Type:", ["dm", "comment"], key="test_type")
if st.button("Generate Reply", key="test_gen"):
if test_msg:
with st.spinner("Generating... ๐ง "):
result = ai.generate_reply(
message=test_msg,
system_prompt=st.session_state.system_prompt,
message_type=test_type,
)
st.markdown(f"""
Reply: {result['reply']}
Method: {result['method']}
""", unsafe_allow_html=True)
# ---- RECENT ACTIVITY ----
if st.session_state.activity_log:
st.markdown('', unsafe_allow_html=True)
st.markdown('
๐ Recent Activity
', unsafe_allow_html=True)
log_html = '
'
for log in st.session_state.activity_log[:5]:
tc = {"success": "log-success", "error": "log-error", "info": "log-info",
"warning": "log-warning", "dm": "log-success", "comment": "log-info",
"bot": "log-warning"}.get(log['type'], 'log-info')
log_html += f'
[{log["time"]}]{log["message"]}
'
log_html += '
'
st.markdown(log_html, unsafe_allow_html=True)
st.markdown("
", unsafe_allow_html=True)
# ---- LOGOUT ----
st.markdown("
", unsafe_allow_html=True)
st.markdown('', unsafe_allow_html=True)
if st.button("๐ช Logout", key="logout_btn"):
bot = get_bot_engine()
if bot.is_running:
bot.stop()
handler.logout()
for key in list(st.session_state.keys()):
del st.session_state[key]
st.rerun()
st.markdown('
', unsafe_allow_html=True)
# ---- AUTO REFRESH (when bot running) ----
if st.session_state.bot_running:
time.sleep(0.1)
st.markdown("""
""", unsafe_allow_html=True)
# ============================================================
# SETTINGS PAGE
# ============================================================
def render_settings():
if st.button("โ Back", key="back_settings"):
st.session_state.current_page = "dashboard"
st.rerun()
st.markdown("""
""", unsafe_allow_html=True)
# ---- AI PROMPT ----
st.markdown('', unsafe_allow_html=True)
st.markdown('
๐ง AI Personality Prompt
', unsafe_allow_html=True)
st.markdown("""
๐ก AI ko batao kaisi baat kare. Kuch nahi likhogi toh default use hoga
(cute ladki jo Hinglish mein baat karti hai). Apna khud ka prompt bhi likh sakti ho!
""", unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
if st.button("๐ Default Prompt Load Karo", key="load_default"):
st.session_state.system_prompt = DEFAULT_SYSTEM_PROMPT
st.rerun()
st.markdown('
', unsafe_allow_html=True)
prompt_input = st.text_area(
"Prompt",
value=st.session_state.system_prompt or "",
placeholder="Custom prompt yahan likho...\n\nJaise: 'Tu ek cool ladki hai jo Hinglish mein baat karti hai...'\n\nKhali chhodogi toh default prompt chalega ๐",
height=200,
key="prompt_area",
label_visibility="collapsed",
)
st.markdown("
", unsafe_allow_html=True)
# ---- FEATURES ----
st.markdown('', unsafe_allow_html=True)
st.markdown('
๐๏ธ Features
', unsafe_allow_html=True)
st.markdown('
๐ Auto DM Reply
', unsafe_allow_html=True)
auto_dm = st.checkbox("Enable DM Reply", value=st.session_state.auto_dm_enabled, key="s_dm", label_visibility="collapsed")
st.markdown('
๐ฌ Auto Comment Reply
', unsafe_allow_html=True)
auto_comment = st.checkbox("Enable Comment Reply", value=st.session_state.auto_comment_enabled, key="s_comment", label_visibility="collapsed")
st.markdown("
", unsafe_allow_html=True)
# ---- AI MODEL INFO ----
ai = get_ai_engine()
ai_status = ai.get_status()
st.markdown('', unsafe_allow_html=True)
st.markdown('
๐ฆ AI Model Info
', unsafe_allow_html=True)
st.markdown(f"""
๐ฆ Model: {MODEL_CONFIG['model_name'].split('/')[-1]}
๐ป Device: {ai_status['device'].upper()}
๐ง Quantization: 4-bit (NF4)
๐ Status:
{'โ
Loaded' if ai_status['model_loaded'] else 'โก Fallback Mode' if ai_status['fallback_mode'] else 'โ Not Loaded'}
{'๐ฎ GPU: ' + ai_status.get('gpu_name', 'N/A') + '
' if ai_status.get('gpu_name') else ''}
{'๐พ VRAM Used: ' + ai_status.get('gpu_memory_allocated', 'N/A') + '' if ai_status.get('gpu_memory_allocated') else ''}
""", unsafe_allow_html=True)
st.markdown("
", unsafe_allow_html=True)
# ---- SAFETY SETTINGS ----
st.markdown('', unsafe_allow_html=True)
st.markdown('
๐ก๏ธ Safety (Anti-Ban)
', unsafe_allow_html=True)
st.markdown(f"""
โฑ๏ธ Action delay: {BOT_CONFIG['action_delay_min']}-{BOT_CONFIG['action_delay_max']}s
๐ Check interval: {BOT_CONFIG['check_interval_min']//60}-{BOT_CONFIG['check_interval_max']//60} min
๐ Max actions/hour: {BOT_CONFIG['max_actions_per_hour']}
๐ Session expiry: {BOT_CONFIG['session_expiry_days']} days
""", unsafe_allow_html=True)
st.markdown("
", unsafe_allow_html=True)
# ---- SAVE ----
st.markdown("
", unsafe_allow_html=True)
if st.button("๐พ Save & Apply", key="save_settings"):
st.session_state.system_prompt = prompt_input.strip() if prompt_input.strip() else ""
st.session_state.auto_dm_enabled = auto_dm
st.session_state.auto_comment_enabled = auto_comment
# Update running bot settings
bot = get_bot_engine()
if bot.is_running:
bot.update_settings(
auto_dm=auto_dm,
auto_comment=auto_comment,
system_prompt=st.session_state.system_prompt,
)
status = "Custom prompt saved โ๏ธ" if st.session_state.system_prompt else "Default prompt active ๐"
add_log(f"Settings saved! {status}", "success")
st.success(f"Saved! {status}")
time.sleep(1)
st.session_state.current_page = "dashboard"
st.rerun()
# ============================================================
# LOGS PAGE
# ============================================================
def render_logs():
if st.button("โ Back", key="back_logs"):
st.session_state.current_page = "dashboard"
st.rerun()
st.markdown("""
""", unsafe_allow_html=True)
if not st.session_state.activity_log:
st.markdown("""
๐ญ
Koi activity nahi hui abhi tak. Bot start karo!
""", unsafe_allow_html=True)
else:
# Filter tabs
tab1, tab2, tab3, tab4 = st.tabs(["๐ All", "๐ DMs", "๐ฌ Comments", "โ Errors"])
def show_logs(logs):
if not logs:
st.markdown('Kuch nahi hai yahan ๐ญ
', unsafe_allow_html=True)
return
log_html = ''
for log in logs:
tc = {"success": "log-success", "error": "log-error", "info": "log-info",
"warning": "log-warning", "dm": "log-success", "comment": "log-info",
"bot": "log-warning"}.get(log['type'], 'log-info')
log_html += f'
[{log["time"]}]{log["message"]}
'
log_html += '
'
st.markdown(log_html, unsafe_allow_html=True)
with tab1:
show_logs(st.session_state.activity_log)
with tab2:
dm_logs = [l for l in st.session_state.activity_log if l['type'] == 'dm']
show_logs(dm_logs)
with tab3:
comment_logs = [l for l in st.session_state.activity_log if l['type'] == 'comment']
show_logs(comment_logs)
with tab4:
error_logs = [l for l in st.session_state.activity_log if l['type'] == 'error']
show_logs(error_logs)
st.markdown("
", unsafe_allow_html=True)
st.markdown('', unsafe_allow_html=True)
if st.button("๐๏ธ Clear All Logs", key="clear_logs"):
st.session_state.activity_log = []
st.rerun()
st.markdown('
', unsafe_allow_html=True)
st.markdown(f'Total: {len(st.session_state.activity_log)} entries โข Max 100
', unsafe_allow_html=True)
# ============================================================
# MAIN ROUTER
# ============================================================
def main():
if not st.session_state.logged_in:
render_login_page()
else:
page = st.session_state.current_page
if page == "settings":
render_settings()
elif page == "logs":
render_logs()
else:
render_dashboard()
st.markdown("""
Made with ๐ โข InstaBot AI v1.0 โข Powered by Llama 3.1 ๐ฆ
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()