-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
240 lines (191 loc) · 7.45 KB
/
bot.py
File metadata and controls
240 lines (191 loc) · 7.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Application,
CommandHandler,
MessageHandler,
CallbackQueryHandler,
ContextTypes,
filters,
)
from config import TELEGRAM_BOT_TOKEN, MANAGER_CHAT_ID
from database import (
init_db,
close_pool,
get_conversation_history,
save_conversation_history,
save_seller_lead,
get_user_language,
set_user_language,
)
from agent import get_ai_response
from locales import get_message
from listing_parser import parse_urls_from_message, format_listings_context
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO
)
logger = logging.getLogger(__name__)
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /start command - always show language selection first"""
await show_language_selection(update)
async def show_language_selection(update: Update):
"""Show language selection buttons"""
keyboard = [
[
InlineKeyboardButton("🇬🇧 English", callback_data="lang_en"),
InlineKeyboardButton("🇺🇦 Українська", callback_data="lang_uk"),
]
]
reply_markup = InlineKeyboardMarkup(keyboard)
text = (
"👋 Welcome! Please select your language:\n"
"👋 Вітаю! Будь ласка, оберіть мову:"
)
await update.message.reply_text(text, reply_markup=reply_markup)
async def language_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle language selection callback"""
query = update.callback_query
await query.answer()
user = query.from_user
user_id = user.id
username = user.username
language = "en" if query.data == "lang_en" else "uk"
await set_user_language(user_id, username, language)
selected_msg = get_message(language, "language_selected")
welcome_msg = get_message(language, "welcome", name=user.first_name)
await query.edit_message_text(f"{selected_msg}\n\n{welcome_msg}")
async def reset_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Reset conversation history"""
user_id = update.effective_user.id
username = update.effective_user.username
language = await get_user_language(user_id) or "en"
await save_conversation_history(user_id, username, [])
await update.message.reply_text(get_message(language, "reset_success"))
async def language_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /language command - allow changing language"""
await show_language_selection(update)
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle incoming messages"""
user = update.effective_user
user_id = user.id
username = user.username
user_message = update.message.text
language = await get_user_language(user_id)
if not language:
await show_language_selection(update)
return
logger.info(f"Message from {username} ({user_id}): {user_message}")
await context.bot.send_chat_action(
chat_id=update.effective_chat.id,
action="typing"
)
history = await get_conversation_history(user_id)
# Parse any listing URLs in the message
listing_context = ""
try:
parsed_listings = await parse_urls_from_message(user_message)
if parsed_listings:
listing_context = format_listings_context(parsed_listings, language)
logger.info(f"Parsed {len(parsed_listings)} listing(s) from message")
except Exception as e:
logger.error(f"Error parsing listing URLs: {e}")
try:
response, seller_lead_data = await get_ai_response(
history, user_message, language, listing_context=listing_context
)
history.append({"role": "user", "content": user_message})
history.append({"role": "assistant", "content": response})
if len(history) > 20:
history = history[-20:]
await save_conversation_history(user_id, username, history)
await update.message.reply_text(response)
if seller_lead_data:
await handle_seller_lead(
context, user_id, username, seller_lead_data, language
)
except Exception as e:
logger.error(f"Error processing message: {e}")
await update.message.reply_text(get_message(language, "error"))
async def handle_seller_lead(
context: ContextTypes.DEFAULT_TYPE,
user_id: int,
username: str,
seller_lead_data: dict,
language: str
):
"""Handle seller lead for exclusive agreement"""
await save_seller_lead(
user_id=user_id,
username=username,
client_name=seller_lead_data["name"],
phone=seller_lead_data["phone"],
property_type=seller_lead_data.get("property_type", ""),
address=seller_lead_data.get("address", ""),
rooms=seller_lead_data.get("rooms", ""),
area=seller_lead_data.get("area", ""),
price=seller_lead_data.get("price", ""),
callback_time=seller_lead_data.get("callback_time", "")
)
if MANAGER_CHAT_ID:
notification = get_message(
language,
"seller_lead_notification",
name=seller_lead_data["name"],
phone=seller_lead_data["phone"],
property_type=seller_lead_data.get("property_type", "N/A"),
address=seller_lead_data.get("address", "N/A"),
rooms=seller_lead_data.get("rooms", "N/A"),
area=seller_lead_data.get("area", "N/A"),
price=seller_lead_data.get("price", "N/A"),
callback_time=seller_lead_data.get("callback_time", "N/A"),
username=username or "N/A"
)
try:
await context.bot.send_message(
chat_id=MANAGER_CHAT_ID,
text=notification
)
logger.info(f"Seller lead notification sent for user {user_id}")
except Exception as e:
logger.error(f"Failed to send seller lead notification to manager: {e}")
def create_bot() -> Application:
"""Create and configure bot"""
# Disable JobQueue due to Python 3.14 compatibility issues
application = (
Application.builder()
.token(TELEGRAM_BOT_TOKEN)
.job_queue(None)
.build()
)
application.add_handler(CommandHandler("start", start_command))
application.add_handler(CommandHandler("reset", reset_command))
application.add_handler(CommandHandler("language", language_command))
application.add_handler(CallbackQueryHandler(language_callback, pattern="^lang_"))
application.add_handler(
MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)
)
return application
def run_bot():
"""Run bot"""
import asyncio
async def main():
await init_db()
application = create_bot()
logger.info("Bot started!")
await application.initialize()
await application.start()
await application.updater.start_polling(allowed_updates=Update.ALL_TYPES)
# Keep running until stopped
try:
while True:
await asyncio.sleep(1)
except asyncio.CancelledError:
pass
finally:
logger.info("Shutting down...")
await application.updater.stop()
await application.stop()
await application.shutdown()
await close_pool()
asyncio.run(main())