baha-99 commited on
Commit
8d1d329
·
verified ·
1 Parent(s): 025d507

Update bot_telegram.py

Browse files
Files changed (1) hide show
  1. bot_telegram.py +163 -129
bot_telegram.py CHANGED
@@ -1,129 +1,163 @@
1
- import os
2
- import logging
3
- import asyncio
4
- import requests
5
- from telegram import Update
6
- from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
7
-
8
- # Configure logging
9
- logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
10
-
11
- # Load environment variables from Hugging Face Secrets
12
- BOT_TOKEN = os.getenv("BOT_TOKEN")
13
- BASE_URL = os.getenv("BASE_URL")
14
- API_USERNAME = os.getenv("API_USERNAME")
15
- API_PASSWORD = os.getenv("API_PASSWORD")
16
-
17
- class TelegramBot:
18
- """A Telegram bot that communicates with an AI model via API."""
19
-
20
- def __init__(self, bot_token, base_url, username, password):
21
- """Initialize the bot with Telegram API token, API credentials, and endpoints."""
22
- self.bot_token = bot_token
23
- self.base_url = base_url
24
- self.username = username
25
- self.password = password
26
- self.auth_token = None
27
-
28
- # API Endpoints
29
- self.login_url = f"{self.base_url}/api/v1/auth/login"
30
- self.ai_url = f"{self.base_url}/api/v1/questions/text"
31
-
32
- # Start Telegram Bot
33
- self.app = Application.builder().token(self.bot_token).build()
34
- self.setup_handlers()
35
-
36
- # Authenticate on startup
37
- logging.info("Authenticating with API...")
38
- self.authenticate()
39
-
40
- def authenticate(self):
41
- """Authenticate with the API and retrieve an access token."""
42
- payload = {"username": self.username, "password": self.password}
43
- headers = {"Content-Type": "application/json", "accept": "application/json"} # Ensure JSON format
44
-
45
- try:
46
- response = requests.post(self.login_url, headers=headers, json=payload) # Send JSON request
47
-
48
- if response.status_code == 200:
49
- self.auth_token = response.json().get("access_token")
50
- logging.info("Successfully authenticated with API")
51
- else:
52
- logging.error(f"Authentication failed: {response.status_code} - {response.text}")
53
-
54
- except Exception as e:
55
- logging.error(f"Authentication Error: {e}")
56
-
57
- async def start_command(self, update: Update, context: CallbackContext):
58
- """Handles the /start command."""
59
- await update.message.reply_text("Hello! Ask me any question.")
60
-
61
- async def chat_with_ai(self, update: Update, context: CallbackContext):
62
- """Handles messages and sends them to the AI API."""
63
- if not self.auth_token:
64
- self.authenticate()
65
-
66
- if not self.auth_token:
67
- await update.message.reply_text("Authentication failed. Please try again later.")
68
- return
69
-
70
- user_message = update.message.text
71
-
72
- headers = {
73
- "Authorization": f"Bearer {self.auth_token}",
74
- "accept": "application/json"
75
- }
76
-
77
- json_payload = {"question": user_message}
78
- form_payload = {"question": user_message} # For x-www-form-urlencoded fallback
79
-
80
- try:
81
- logging.info(f"Sending payload as JSON: {json_payload}")
82
- response = requests.post(self.ai_url, headers={**headers, "Content-Type": "application/json"}, json=json_payload)
83
-
84
- if response.status_code == 422: # If JSON fails, try form-data
85
- logging.warning("JSON format rejected. Retrying with form-data...")
86
- response = requests.post(self.ai_url, headers={**headers, "Content-Type": "application/x-www-form-urlencoded"}, data=form_payload)
87
-
88
- logging.info(f"Response status: {response.status_code}")
89
- logging.info(f"Response content: {response.text}")
90
-
91
- if response.status_code == 200:
92
- bot_reply = response.json().get("answer", "I didn't understand that.")
93
- elif response.status_code == 401:
94
- logging.warning("Authorization expired. Re-authenticating...")
95
- self.authenticate()
96
- await self.chat_with_ai(update, context)
97
- return
98
- elif response.status_code == 422:
99
- bot_reply = "Error: The API rejected the request. Check payload format."
100
- else:
101
- bot_reply = f"Error: {response.status_code} - {response.text}"
102
-
103
- except Exception as e:
104
- bot_reply = f"Connection error: {e}"
105
-
106
- await update.message.reply_text(bot_reply)
107
-
108
- def setup_handlers(self):
109
- """Set up Telegram command and message handlers."""
110
- self.app.add_handler(CommandHandler("start", self.start_command))
111
- self.app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.chat_with_ai))
112
-
113
- def run(self):
114
- """Start the bot and listen for messages."""
115
- logging.info("Starting Telegram bot...")
116
- asyncio.set_event_loop(asyncio.new_event_loop()) # Fixes async event loop issue
117
- try:
118
- self.app.run_polling()
119
- except Exception as e:
120
- logging.error(f"Bot failed to start: {e}")
121
-
122
- if __name__ == "__main__":
123
- bot = TelegramBot(
124
- bot_token=BOT_TOKEN,
125
- base_url=BASE_URL,
126
- username=API_USERNAME,
127
- password=API_PASSWORD
128
- )
129
- bot.run()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import asyncio
4
+ import requests
5
+ from telegram import Update
6
+ from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
7
+
8
+ # Configure logging
9
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
10
+
11
+ # Load environment variables from Hugging Face Secrets
12
+ BOT_TOKEN = os.getenv("BOT_TOKEN")
13
+ BASE_URL = os.getenv("BASE_URL")
14
+ API_USERNAME = os.getenv("API_USERNAME")
15
+ API_PASSWORD = os.getenv("API_PASSWORD")
16
+
17
+ # Set the secret password for authentication
18
+ SECRET_PASSWORD = "secure123" # Change this to your desired password
19
+
20
+ # Dictionary to store authenticated users
21
+ AUTHENTICATED_USERS = set()
22
+
23
+ class TelegramBot:
24
+ """A Telegram bot with password-based authentication."""
25
+
26
+ def __init__(self, bot_token, base_url, username, password):
27
+ """Initialize the bot with Telegram API token, API credentials, and authentication."""
28
+ self.bot_token = bot_token
29
+ self.base_url = base_url
30
+ self.username = username
31
+ self.password = password
32
+ self.auth_token = None
33
+
34
+ # API Endpoints
35
+ self.login_url = f"{self.base_url}/api/v1/auth/login"
36
+ self.ai_url = f"{self.base_url}/api/v1/questions/text"
37
+
38
+ # Start Telegram Bot
39
+ self.app = Application.builder().token(self.bot_token).build()
40
+ self.setup_handlers()
41
+
42
+ # Authenticate with API
43
+ logging.info("Authenticating with API...")
44
+ self.authenticate()
45
+
46
+ def authenticate(self):
47
+ """Authenticate with the API and retrieve an access token."""
48
+ payload = {"username": self.username, "password": self.password}
49
+ headers = {"Content-Type": "application/json", "accept": "application/json"}
50
+
51
+ try:
52
+ response = requests.post(self.login_url, headers=headers, json=payload)
53
+
54
+ if response.status_code == 200:
55
+ self.auth_token = response.json().get("access_token")
56
+ logging.info("Successfully authenticated with API")
57
+ else:
58
+ logging.error(f"Authentication failed: {response.status_code} - {response.text}")
59
+
60
+ except Exception as e:
61
+ logging.error(f"Authentication Error: {e}")
62
+
63
+ async def start_command(self, update: Update, context: CallbackContext):
64
+ """Handles the /start command and asks for a password."""
65
+ user_id = update.message.from_user.id
66
+
67
+ if user_id in AUTHENTICATED_USERS:
68
+ await update.message.reply_text("You are already authenticated! You can start chatting.")
69
+ return
70
+
71
+ await update.message.reply_text("🔑 Please enter the secret password to access the bot.")
72
+
73
+ async def check_password(self, update: Update, context: CallbackContext):
74
+ """Checks if the password is correct and authenticates the user."""
75
+ user_id = update.message.from_user.id
76
+ user_message = update.message.text.strip()
77
+
78
+ if user_id in AUTHENTICATED_USERS:
79
+ await update.message.reply_text("✅ You are already authenticated!")
80
+ return
81
+
82
+ if user_message == SECRET_PASSWORD:
83
+ AUTHENTICATED_USERS.add(user_id)
84
+ await update.message.reply_text("✅ Authentication successful! You can now use the bot.")
85
+ else:
86
+ await update.message.reply_text("❌ Wrong password. Try again.")
87
+
88
+ async def chat_with_ai(self, update: Update, context: CallbackContext):
89
+ """Handles messages and sends them to the AI API."""
90
+ user_id = update.message.from_user.id
91
+
92
+ if user_id not in AUTHENTICATED_USERS:
93
+ await update.message.reply_text("❌ You are not authenticated. Please enter the password first.")
94
+ return
95
+
96
+ if not self.auth_token:
97
+ self.authenticate()
98
+
99
+ if not self.auth_token:
100
+ await update.message.reply_text("Authentication failed. Please try again later.")
101
+ return
102
+
103
+ user_message = update.message.text
104
+
105
+ headers = {
106
+ "Authorization": f"Bearer {self.auth_token}",
107
+ "accept": "application/json"
108
+ }
109
+
110
+ json_payload = {"question": user_message}
111
+ form_payload = {"question": user_message}
112
+
113
+ try:
114
+ logging.info(f"Sending payload as JSON: {json_payload}")
115
+ response = requests.post(self.ai_url, headers={**headers, "Content-Type": "application/json"}, json=json_payload)
116
+
117
+ if response.status_code == 422:
118
+ logging.warning("JSON format rejected. Retrying with form-data...")
119
+ response = requests.post(self.ai_url, headers={**headers, "Content-Type": "application/x-www-form-urlencoded"}, data=form_payload)
120
+
121
+ logging.info(f"Response status: {response.status_code}")
122
+ logging.info(f"Response content: {response.text}")
123
+
124
+ if response.status_code == 200:
125
+ bot_reply = response.json().get("answer", "I didn't understand that.")
126
+ elif response.status_code == 401:
127
+ logging.warning("Authorization expired. Re-authenticating...")
128
+ self.authenticate()
129
+ await self.chat_with_ai(update, context)
130
+ return
131
+ elif response.status_code == 422:
132
+ bot_reply = "Error: The API rejected the request. Check payload format."
133
+ else:
134
+ bot_reply = f"Error: {response.status_code} - {response.text}"
135
+
136
+ except Exception as e:
137
+ bot_reply = f"Connection error: {e}"
138
+
139
+ await update.message.reply_text(bot_reply)
140
+
141
+ def setup_handlers(self):
142
+ """Set up Telegram command and message handlers."""
143
+ self.app.add_handler(CommandHandler("start", self.start_command))
144
+ self.app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.check_password))
145
+ self.app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.chat_with_ai))
146
+
147
+ def run(self):
148
+ """Start the bot and listen for messages."""
149
+ logging.info("Starting Telegram bot...")
150
+ asyncio.set_event_loop(asyncio.new_event_loop())
151
+ try:
152
+ self.app.run_polling()
153
+ except Exception as e:
154
+ logging.error(f"Bot failed to start: {e}")
155
+
156
+ if __name__ == "__main__":
157
+ bot = TelegramBot(
158
+ bot_token=BOT_TOKEN,
159
+ base_url=BASE_URL,
160
+ username=API_USERNAME,
161
+ password=API_PASSWORD
162
+ )
163
+ bot.run()