rastof9 commited on
Commit
08086e8
·
verified ·
1 Parent(s): 3db3fa2

Create bot.py

Browse files
Files changed (1) hide show
  1. bot.py +143 -0
bot.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # bot.py
2
+
3
+ import logging
4
+ import os
5
+ from telegram import Update, ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardButton, InlineKeyboardMarkup
6
+ from telegram.ext import (
7
+ Application,
8
+ CommandHandler,
9
+ ContextTypes,
10
+ ConversationHandler,
11
+ MessageHandler,
12
+ CallbackQueryHandler,
13
+ filters,
14
+ )
15
+
16
+ import config
17
+ import database
18
+ from generate import GenerationService
19
+
20
+ # --- Setup Logging ---
21
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
22
+ logger = logging.getLogger(__name__)
23
+
24
+ # --- State Definitions for Conversation ---
25
+ # We define states to keep track of where the user is in the conversation.
26
+ SELECTING_ACTION, SELECTING_STYLE, SELECTING_GENDER = range(3)
27
+
28
+ # --- Initialize the Generation Service ---
29
+ # This loads the heavy AI models into memory once when the bot starts.
30
+ logger.info("Initializing Generation Service... This may take a while.")
31
+ try:
32
+ generation_service = GenerationService()
33
+ logger.info("Generation Service initialized successfully.")
34
+ except Exception as e:
35
+ logger.error(f"FATAL: Could not initialize GenerationService. Bot cannot start. Error: {e}")
36
+ # In a real deployment, you might want to exit or send an alert here.
37
+ generation_service = None
38
+
39
+
40
+ # --- Command Handlers ---
41
+
42
+ async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
43
+ """
44
+ Handles the /start command. Greets the user, creates their account in the DB if needed,
45
+ and shows them their credit balance.
46
+ """
47
+ user = update.effective_user
48
+ logger.info(f"User {user.id} ({user.username}) started the bot.")
49
+
50
+ # Get or create user in the database
51
+ db_user = database.get_or_create_user(user.id, user.username)
52
+
53
+ if not db_user:
54
+ await update.message.reply_text("😕 Sorry, there was a problem setting up your account. Please try again later.")
55
+ return ConversationHandler.END
56
+
57
+ credits = db_user.get('credits', 0)
58
+
59
+ welcome_message = (
60
+ f"👋 Welcome to the Magic Face Bot, {user.first_name}!\n\n"
61
+ "I can transform your face into legendary characters using AI.\n\n"
62
+ f"You currently have **{credits}** credits.\n\n"
63
+ "To get started, just send me a clear photo of your face."
64
+ )
65
+
66
+ await update.message.reply_text(welcome_message, parse_mode='Markdown')
67
+
68
+ # We don't enter a state here yet; we wait for the user to send a photo.
69
+ return SELECTING_ACTION
70
+
71
+
72
+ async def credits_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
73
+ """
74
+ Handles the /credits command. Shows the user their current credit balance.
75
+ """
76
+ user_id = update.effective_user.id
77
+ credits = database.get_user_credits(user_id)
78
+ await update.message.reply_text(f"You have **{credits}** credits remaining.", parse_mode='Markdown')
79
+
80
+
81
+ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
82
+ """
83
+ Handles the /help command.
84
+ """
85
+ help_text = (
86
+ "**How to use the Magic Face Bot:**\n\n"
87
+ "1. Send a clear, well-lit photo of your face.\n"
88
+ "2. Choose a transformation style from the menu.\n"
89
+ "3. Select your gender.\n"
90
+ "4. Wait for the AI to work its magic!\n\n"
91
+ "**Commands:**\n"
92
+ "/start - Restart the bot.\n"
93
+ "/credits - Check your credit balance.\n"
94
+ "/help - Show this message."
95
+ )
96
+ await update.message.reply_text(help_text, parse_mode='Markdown')
97
+
98
+
99
+ # --- Main Application ---
100
+ def main() -> None:
101
+ """
102
+ Starts the bot.
103
+ """
104
+ if not generation_service:
105
+ logger.error("Generation service not available. Bot is shutting down.")
106
+ return
107
+
108
+ # Create the Application and pass it your bot's token.
109
+ application = Application.builder().token(config.TELEGRAM_TOKEN).build()
110
+
111
+ # --- Conversation Handler (to be built out) ---
112
+ # For now, we just have the entry point and basic commands.
113
+ conv_handler = ConversationHandler(
114
+ entry_points=[
115
+ CommandHandler("start", start_command),
116
+ # We will add a MessageHandler for photos here later
117
+ ],
118
+ states={
119
+ SELECTING_ACTION: [
120
+ # Handlers for when the user sends a photo will go here
121
+ ],
122
+ SELECTING_STYLE: [
123
+ # Handlers for when the user chooses a style
124
+ ],
125
+ SELECTING_GENDER: [
126
+ # Handlers for when the user chooses a gender
127
+ ],
128
+ },
129
+ fallbacks=[CommandHandler("start", start_command)],
130
+ )
131
+
132
+ application.add_handler(conv_handler)
133
+ application.add_handler(CommandHandler("help", help_command))
134
+ application.add_handler(CommandHandler("credits", credits_command))
135
+
136
+ # Run the bot until the user presses Ctrl-C
137
+ logger.info("Bot is starting to poll for updates...")
138
+ application.run_polling()
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
143
+