-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
193 lines (149 loc) · 6.32 KB
/
Copy pathbot.py
File metadata and controls
193 lines (149 loc) · 6.32 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
"""
TechSmart Support Telegram Bot
Main bot module with handlers and commands
"""
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Application,
CommandHandler,
MessageHandler,
CallbackQueryHandler,
ContextTypes,
filters
)
from config import TELEGRAM_BOT_TOKEN, MESSAGES
from knowledge_base import get_knowledge_base
# Configure logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Initialize knowledge base
kb = None
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle /start command"""
keyboard = [
[
InlineKeyboardButton("📦 Доставка", callback_data="delivery"),
InlineKeyboardButton("🛡️ Гарантия", callback_data="warranty")
],
[
InlineKeyboardButton("❓ FAQ", callback_data="faq"),
InlineKeyboardButton("📞 Оператор", callback_data="operator")
]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
MESSAGES["welcome"],
reply_markup=reply_markup
)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle /help command"""
await update.message.reply_text(MESSAGES["help"])
async def delivery_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle /delivery command"""
global kb
if kb:
info = kb.get_delivery_info()
await update.message.reply_text(f"📦 *Доставка и возврат*\n\n{info}", parse_mode="Markdown")
else:
await update.message.reply_text(MESSAGES["error"])
async def warranty_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle /warranty command"""
global kb
if kb:
info = kb.get_warranty_info()
await update.message.reply_text(f"🛡️ *Гарантийная политика*\n\n{info}", parse_mode="Markdown")
else:
await update.message.reply_text(MESSAGES["error"])
async def faq_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle /faq command"""
global kb
if kb:
info = kb.get_faq()
await update.message.reply_text(f"❓ *Часто задаваемые вопросы*\n\n{info}", parse_mode="Markdown")
else:
await update.message.reply_text(MESSAGES["error"])
async def operator_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle /operator command"""
await update.message.reply_text(MESSAGES["operator_contact"])
async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle inline button callbacks"""
query = update.callback_query
await query.answer()
global kb
if query.data == "delivery":
if kb:
info = kb.get_delivery_info()
await query.message.reply_text(f"📦 *Доставка и возврат*\n\n{info}", parse_mode="Markdown")
else:
await query.message.reply_text(MESSAGES["error"])
elif query.data == "warranty":
if kb:
info = kb.get_warranty_info()
await query.message.reply_text(f"🛡️ *Гарантийная политика*\n\n{info}", parse_mode="Markdown")
else:
await query.message.reply_text(MESSAGES["error"])
elif query.data == "faq":
if kb:
info = kb.get_faq()
await query.message.reply_text(f"❓ *Часто задаваемые вопросы*\n\n{info}", parse_mode="Markdown")
else:
await query.message.reply_text(MESSAGES["error"])
elif query.data == "operator":
await query.message.reply_text(MESSAGES["operator_contact"])
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle user text messages - main Q&A functionality"""
global kb
user_message = update.message.text
user = update.effective_user
logger.info(f"Question from {user.username or user.id}: {user_message}")
# Send "thinking" message
thinking_msg = await update.message.reply_text(MESSAGES["thinking"])
try:
if kb:
# Get answer from knowledge base
answer = kb.get_answer(user_message)
if answer:
await thinking_msg.edit_text(answer)
else:
await thinking_msg.edit_text(MESSAGES["no_answer"])
else:
await thinking_msg.edit_text(MESSAGES["error"])
except Exception as e:
logger.error(f"Error processing message: {e}")
await thinking_msg.edit_text(MESSAGES["error"])
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle errors"""
logger.error(f"Update {update} caused error {context.error}")
def main() -> None:
"""Main function to run the bot"""
global kb
# Check for token
if not TELEGRAM_BOT_TOKEN:
print("❌ Error: TELEGRAM_BOT_TOKEN not set in .env file")
print("Please copy .env.example to .env and add your bot token")
return
# Initialize knowledge base
print("[BOT] Starting TechSmart Support Bot...")
kb = get_knowledge_base()
# Create application
application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
# Add handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("delivery", delivery_command))
application.add_handler(CommandHandler("warranty", warranty_command))
application.add_handler(CommandHandler("faq", faq_command))
application.add_handler(CommandHandler("operator", operator_command))
application.add_handler(CallbackQueryHandler(button_callback))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
# Add error handler
application.add_error_handler(error_handler)
# Start the bot
print("[OK] Bot is running! Press Ctrl+C to stop.")
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()