Upload 3 files
Browse files- Dockerfile +3 -3
- bot_telegram.py +57 -17
- requirements.txt +0 -1
Dockerfile
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
-
# Use
|
| 2 |
FROM python:3.10-slim
|
| 3 |
|
| 4 |
-
# Set working directory inside the container
|
| 5 |
WORKDIR /app
|
| 6 |
|
| 7 |
-
# Copy
|
| 8 |
COPY . .
|
| 9 |
|
| 10 |
# Install dependencies
|
|
|
|
| 1 |
+
# Use a minimal Python image
|
| 2 |
FROM python:3.10-slim
|
| 3 |
|
| 4 |
+
# Set the working directory inside the container
|
| 5 |
WORKDIR /app
|
| 6 |
|
| 7 |
+
# Copy bot files into the container
|
| 8 |
COPY . .
|
| 9 |
|
| 10 |
# Install dependencies
|
bot_telegram.py
CHANGED
|
@@ -1,80 +1,120 @@
|
|
| 1 |
import os
|
| 2 |
import logging
|
|
|
|
| 3 |
import requests
|
| 4 |
-
import gradio as gr
|
| 5 |
from threading import Thread
|
| 6 |
from telegram import Update
|
| 7 |
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
|
| 8 |
|
| 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 |
class TelegramBot:
|
|
|
|
|
|
|
| 16 |
def __init__(self, bot_token, base_url, username, password):
|
|
|
|
| 17 |
self.bot_token = bot_token
|
| 18 |
self.base_url = base_url
|
| 19 |
self.username = username
|
| 20 |
self.password = password
|
| 21 |
self.auth_token = None
|
|
|
|
|
|
|
| 22 |
self.login_url = f"{self.base_url}/api/v1/auth/login"
|
| 23 |
self.ai_url = f"{self.base_url}/api/v1/questions/text"
|
|
|
|
|
|
|
| 24 |
self.app = Application.builder().token(self.bot_token).build()
|
| 25 |
self.setup_handlers()
|
|
|
|
|
|
|
| 26 |
self.authenticate()
|
| 27 |
|
| 28 |
def authenticate(self):
|
|
|
|
| 29 |
payload = {"username": self.username, "password": self.password}
|
| 30 |
headers = {"Content-Type": "application/x-www-form-urlencoded", "accept": "application/json"}
|
|
|
|
| 31 |
try:
|
| 32 |
response = requests.post(self.login_url, headers=headers, data=payload)
|
|
|
|
| 33 |
if response.status_code == 200:
|
| 34 |
self.auth_token = response.json().get("access_token")
|
| 35 |
-
logging.info("Successfully authenticated with API!")
|
| 36 |
else:
|
| 37 |
-
logging.error(f"Authentication failed: {response.status_code} - {response.text}")
|
|
|
|
| 38 |
except Exception as e:
|
| 39 |
-
logging.error(f"Authentication Error: {e}")
|
| 40 |
|
| 41 |
async def start_command(self, update: Update, context: CallbackContext):
|
|
|
|
| 42 |
await update.message.reply_text("Hello! Ask me any question.")
|
| 43 |
|
| 44 |
async def chat_with_ai(self, update: Update, context: CallbackContext):
|
|
|
|
| 45 |
if not self.auth_token:
|
| 46 |
self.authenticate()
|
|
|
|
| 47 |
if not self.auth_token:
|
| 48 |
await update.message.reply_text("Authentication failed. Please try again later.")
|
| 49 |
return
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
try:
|
| 54 |
response = requests.post(self.ai_url, headers=headers, data=payload)
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
except Exception as e:
|
| 57 |
-
bot_reply = f"Connection error: {e}"
|
| 58 |
|
| 59 |
await update.message.reply_text(bot_reply)
|
| 60 |
|
| 61 |
def setup_handlers(self):
|
|
|
|
| 62 |
self.app.add_handler(CommandHandler("start", self.start_command))
|
| 63 |
self.app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.chat_with_ai))
|
| 64 |
|
| 65 |
def run(self):
|
| 66 |
-
|
|
|
|
|
|
|
| 67 |
self.app.run_polling()
|
| 68 |
|
|
|
|
| 69 |
def start_telegram_bot():
|
| 70 |
-
bot = TelegramBot(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
bot.run()
|
| 72 |
|
|
|
|
| 73 |
telegram_thread = Thread(target=start_telegram_bot, daemon=True)
|
| 74 |
telegram_thread.start()
|
| 75 |
-
|
| 76 |
-
def status():
|
| 77 |
-
return "✅ Telegram Bot is Running on Hugging Face!"
|
| 78 |
-
|
| 79 |
-
iface = gr.Interface(fn=status, inputs=[], outputs="text", title="Telegram Bot Status")
|
| 80 |
-
iface.launch(share=True)
|
|
|
|
| 1 |
import os
|
| 2 |
import logging
|
| 3 |
+
import asyncio
|
| 4 |
import requests
|
|
|
|
| 5 |
from threading import Thread
|
| 6 |
from telegram import Update
|
| 7 |
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
|
| 8 |
|
| 9 |
+
# Load environment variables from Hugging Face Secrets
|
| 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 |
class TelegramBot:
|
| 16 |
+
"""A Telegram bot that communicates with an AI model via API."""
|
| 17 |
+
|
| 18 |
def __init__(self, bot_token, base_url, username, password):
|
| 19 |
+
"""Initialize the bot with Telegram API token, API credentials, and endpoints."""
|
| 20 |
self.bot_token = bot_token
|
| 21 |
self.base_url = base_url
|
| 22 |
self.username = username
|
| 23 |
self.password = password
|
| 24 |
self.auth_token = None
|
| 25 |
+
|
| 26 |
+
# API Endpoints
|
| 27 |
self.login_url = f"{self.base_url}/api/v1/auth/login"
|
| 28 |
self.ai_url = f"{self.base_url}/api/v1/questions/text"
|
| 29 |
+
|
| 30 |
+
# Start Telegram Bot
|
| 31 |
self.app = Application.builder().token(self.bot_token).build()
|
| 32 |
self.setup_handlers()
|
| 33 |
+
|
| 34 |
+
# Authenticate on startup
|
| 35 |
self.authenticate()
|
| 36 |
|
| 37 |
def authenticate(self):
|
| 38 |
+
"""Authenticate with the API and retrieve an access token."""
|
| 39 |
payload = {"username": self.username, "password": self.password}
|
| 40 |
headers = {"Content-Type": "application/x-www-form-urlencoded", "accept": "application/json"}
|
| 41 |
+
|
| 42 |
try:
|
| 43 |
response = requests.post(self.login_url, headers=headers, data=payload)
|
| 44 |
+
|
| 45 |
if response.status_code == 200:
|
| 46 |
self.auth_token = response.json().get("access_token")
|
| 47 |
+
logging.info("✅ Successfully authenticated with API!")
|
| 48 |
else:
|
| 49 |
+
logging.error(f"❌ Authentication failed: {response.status_code} - {response.text}")
|
| 50 |
+
|
| 51 |
except Exception as e:
|
| 52 |
+
logging.error(f"❌ Authentication Error: {e}")
|
| 53 |
|
| 54 |
async def start_command(self, update: Update, context: CallbackContext):
|
| 55 |
+
"""Handles the /start command."""
|
| 56 |
await update.message.reply_text("Hello! Ask me any question.")
|
| 57 |
|
| 58 |
async def chat_with_ai(self, update: Update, context: CallbackContext):
|
| 59 |
+
"""Handles messages and sends them to the AI API."""
|
| 60 |
if not self.auth_token:
|
| 61 |
self.authenticate()
|
| 62 |
+
|
| 63 |
if not self.auth_token:
|
| 64 |
await update.message.reply_text("Authentication failed. Please try again later.")
|
| 65 |
return
|
| 66 |
|
| 67 |
+
user_message = update.message.text
|
| 68 |
+
|
| 69 |
+
headers = {
|
| 70 |
+
"Authorization": f"Bearer {self.auth_token}",
|
| 71 |
+
"Content-Type": "application/x-www-form-urlencoded",
|
| 72 |
+
"accept": "application/json"
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
payload = {"question": user_message}
|
| 76 |
+
|
| 77 |
try:
|
| 78 |
response = requests.post(self.ai_url, headers=headers, data=payload)
|
| 79 |
+
|
| 80 |
+
if response.status_code == 200:
|
| 81 |
+
bot_reply = response.json().get("answer", "I didn't understand that.")
|
| 82 |
+
elif response.status_code == 401: # If unauthorized, refresh the token and retry
|
| 83 |
+
logging.warning("⚠️ Authorization expired. Re-authenticating...")
|
| 84 |
+
self.authenticate()
|
| 85 |
+
await self.chat_with_ai(update, context) # Retry after re-authentication
|
| 86 |
+
return
|
| 87 |
+
elif response.status_code == 422:
|
| 88 |
+
bot_reply = "⚠️ Error: The API rejected the request. Check payload format."
|
| 89 |
+
else:
|
| 90 |
+
bot_reply = f"⚠️ Error: {response.status_code}"
|
| 91 |
+
|
| 92 |
except Exception as e:
|
| 93 |
+
bot_reply = f"⚠️ Connection error: {e}"
|
| 94 |
|
| 95 |
await update.message.reply_text(bot_reply)
|
| 96 |
|
| 97 |
def setup_handlers(self):
|
| 98 |
+
"""Set up Telegram command and message handlers."""
|
| 99 |
self.app.add_handler(CommandHandler("start", self.start_command))
|
| 100 |
self.app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.chat_with_ai))
|
| 101 |
|
| 102 |
def run(self):
|
| 103 |
+
"""Start the bot and listen for messages."""
|
| 104 |
+
logging.info("🚀 Bot is now listening for messages...")
|
| 105 |
+
asyncio.set_event_loop(asyncio.new_event_loop()) # Fixes event loop issue
|
| 106 |
self.app.run_polling()
|
| 107 |
|
| 108 |
+
# --- Function to Start Bot Thread ---
|
| 109 |
def start_telegram_bot():
|
| 110 |
+
bot = TelegramBot(
|
| 111 |
+
bot_token=BOT_TOKEN,
|
| 112 |
+
base_url=BASE_URL,
|
| 113 |
+
username=API_USERNAME,
|
| 114 |
+
password=API_PASSWORD
|
| 115 |
+
)
|
| 116 |
bot.run()
|
| 117 |
|
| 118 |
+
# Start the bot in a separate thread
|
| 119 |
telegram_thread = Thread(target=start_telegram_bot, daemon=True)
|
| 120 |
telegram_thread.start()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,3 +1,2 @@
|
|
| 1 |
python-telegram-bot
|
| 2 |
requests
|
| 3 |
-
gradio
|
|
|
|
| 1 |
python-telegram-bot
|
| 2 |
requests
|
|
|