Update bot_telegram.py
Browse files- bot_telegram.py +59 -3
bot_telegram.py
CHANGED
|
@@ -4,18 +4,21 @@ import asyncio
|
|
| 4 |
import requests
|
| 5 |
from telegram import Update
|
| 6 |
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
|
|
|
|
| 7 |
|
|
|
|
| 8 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 9 |
|
|
|
|
| 10 |
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
| 11 |
BASE_URL = os.getenv("BASE_URL")
|
| 12 |
API_USERNAME = os.getenv("API_USERNAME")
|
| 13 |
API_PASSWORD = os.getenv("API_PASSWORD")
|
| 14 |
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
AUTHENTICATED_USERS = set()
|
| 20 |
AWAITING_PASSWORD = set()
|
| 21 |
|
|
@@ -33,6 +36,7 @@ class TelegramBot:
|
|
| 33 |
# API Endpoints
|
| 34 |
self.login_url = f"{self.base_url}/api/v1/auth/login"
|
| 35 |
self.ai_url = f"{self.base_url}/api/v1/questions/text"
|
|
|
|
| 36 |
|
| 37 |
# Start Telegram Bot
|
| 38 |
self.app = Application.builder().token(self.bot_token).build()
|
|
@@ -155,10 +159,62 @@ class TelegramBot:
|
|
| 155 |
|
| 156 |
await update.message.reply_text(bot_reply)
|
| 157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
def setup_handlers(self):
|
| 159 |
"""Set up Telegram command and message handlers."""
|
| 160 |
self.app.add_handler(CommandHandler("start", self.start_command))
|
| 161 |
self.app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_message))
|
|
|
|
|
|
|
| 162 |
|
| 163 |
def run(self):
|
| 164 |
"""Start the bot and listen for messages."""
|
|
|
|
| 4 |
import requests
|
| 5 |
from telegram import Update
|
| 6 |
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
|
| 7 |
+
import aiohttp
|
| 8 |
|
| 9 |
+
# Configure logging
|
| 10 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 11 |
|
| 12 |
+
# Load environment variables from Hugging Face Secrets
|
| 13 |
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
| 14 |
BASE_URL = os.getenv("BASE_URL")
|
| 15 |
API_USERNAME = os.getenv("API_USERNAME")
|
| 16 |
API_PASSWORD = os.getenv("API_PASSWORD")
|
| 17 |
|
| 18 |
+
# Set the secret password for authentication
|
| 19 |
+
SECRET_PASSWORD = "secure123" # Change this to your desired password
|
| 20 |
|
| 21 |
+
# Dictionary to store authenticated users
|
|
|
|
|
|
|
| 22 |
AUTHENTICATED_USERS = set()
|
| 23 |
AWAITING_PASSWORD = set()
|
| 24 |
|
|
|
|
| 36 |
# API Endpoints
|
| 37 |
self.login_url = f"{self.base_url}/api/v1/auth/login"
|
| 38 |
self.ai_url = f"{self.base_url}/api/v1/questions/text"
|
| 39 |
+
self.excel_url = f"{self.base_url}/api/v1/questions/excel"
|
| 40 |
|
| 41 |
# Start Telegram Bot
|
| 42 |
self.app = Application.builder().token(self.bot_token).build()
|
|
|
|
| 159 |
|
| 160 |
await update.message.reply_text(bot_reply)
|
| 161 |
|
| 162 |
+
async def handle_excel(self, update: Update, context: CallbackContext):
|
| 163 |
+
"""Handles Excel file uploads."""
|
| 164 |
+
user_id = update.message.from_user.id
|
| 165 |
+
|
| 166 |
+
if user_id not in AUTHENTICATED_USERS:
|
| 167 |
+
await update.message.reply_text("❌ You are not authenticated. Please enter the password first.")
|
| 168 |
+
return
|
| 169 |
+
|
| 170 |
+
if not self.auth_token:
|
| 171 |
+
self.authenticate()
|
| 172 |
+
|
| 173 |
+
if not self.auth_token:
|
| 174 |
+
await update.message.reply_text("Authentication failed. Please try again later.")
|
| 175 |
+
return
|
| 176 |
+
|
| 177 |
+
try:
|
| 178 |
+
# Get file from Telegram
|
| 179 |
+
file = await context.bot.get_file(update.message.document.file_id)
|
| 180 |
+
file_bytes = await file.download_as_bytearray()
|
| 181 |
+
|
| 182 |
+
# Prepare the file upload
|
| 183 |
+
headers = {
|
| 184 |
+
"Authorization": f"Bearer {self.auth_token}",
|
| 185 |
+
"accept": "application/json"
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
# Create form data with the file
|
| 189 |
+
form_data = aiohttp.FormData()
|
| 190 |
+
form_data.add_field('file',
|
| 191 |
+
file_bytes,
|
| 192 |
+
filename=update.message.document.file_name,
|
| 193 |
+
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
| 194 |
+
|
| 195 |
+
async with aiohttp.ClientSession() as session:
|
| 196 |
+
async with session.post(self.excel_url, headers=headers, data=form_data) as response:
|
| 197 |
+
if response.status == 200:
|
| 198 |
+
response_json = await response.json()
|
| 199 |
+
await update.message.reply_text(response_json.get("message", "Excel file processed successfully!"))
|
| 200 |
+
elif response.status == 401:
|
| 201 |
+
logging.warning("Authorization expired. Re-authenticating...")
|
| 202 |
+
self.authenticate()
|
| 203 |
+
await self.handle_excel(update, context)
|
| 204 |
+
else:
|
| 205 |
+
error_text = await response.text()
|
| 206 |
+
await update.message.reply_text(f"Error processing Excel file: {error_text}")
|
| 207 |
+
|
| 208 |
+
except Exception as e:
|
| 209 |
+
logging.error(f"Error handling Excel file: {e}")
|
| 210 |
+
await update.message.reply_text(f"Error processing Excel file: {str(e)}")
|
| 211 |
+
|
| 212 |
def setup_handlers(self):
|
| 213 |
"""Set up Telegram command and message handlers."""
|
| 214 |
self.app.add_handler(CommandHandler("start", self.start_command))
|
| 215 |
self.app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_message))
|
| 216 |
+
# Add handler for document messages
|
| 217 |
+
self.app.add_handler(MessageHandler(filters.Document.FileExtension("xlsx") | filters.Document.FileExtension("xls"), self.handle_excel))
|
| 218 |
|
| 219 |
def run(self):
|
| 220 |
"""Start the bot and listen for messages."""
|