Update bot.py
Browse files
bot.py
CHANGED
@@ -13,47 +13,51 @@ from telegram.ext import (
|
|
13 |
CallbackContext
|
14 |
)
|
15 |
|
|
|
16 |
# -------------------------
|
17 |
# Configure logging
|
18 |
# -------------------------
|
19 |
-
logging.basicConfig(
|
20 |
-
format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO
|
21 |
-
)
|
22 |
logger = logging.getLogger(__name__)
|
23 |
|
|
|
24 |
# -------------------------
|
25 |
# Environment variables
|
26 |
# -------------------------
|
27 |
-
# Get
|
28 |
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
29 |
if not TOKEN:
|
30 |
raise ValueError("Missing Telegram Bot Token. Please set TELEGRAM_BOT_TOKEN environment variable.")
|
31 |
|
32 |
-
# Get the domain for webhook (publicly accessible, e.g., your-space.hf.space)
|
33 |
-
WEBHOOK_DOMAIN = os.getenv("WEBHOOK_DOMAIN")
|
34 |
-
if not WEBHOOK_DOMAIN:
|
35 |
-
|
36 |
|
37 |
|
38 |
-
# -------------------------
|
39 |
-
# Webhook configuration
|
40 |
-
# -------------------------
|
41 |
-
# Define a unique webhook path using the bot token
|
42 |
-
# WEBHOOK_PATH = f"/{TOKEN}"
|
43 |
-
# Construct the full webhook URL (must be HTTPS as required by Telegram)
|
44 |
-
WEBHOOK_URL = f"https://{WEBHOOK_DOMAIN}"
|
|
|
45 |
|
46 |
# -------------------------
|
47 |
# API URL of the FastAPI server (running on Hugging Face)
|
48 |
# -------------------------
|
49 |
API_URL = "https://demaking-decision-helper-bot.hf.space/generate_response"
|
50 |
|
51 |
-
bot = Bot(token=TOKEN)
|
52 |
|
53 |
# -------------------------
|
54 |
# Function to fetch response from FastAPI (unchanged)
|
55 |
# -------------------------
|
56 |
async def fetch_response(user_text: str):
|
|
|
|
|
|
|
57 |
async with httpx.AsyncClient(timeout=45.0) as client:
|
58 |
try:
|
59 |
response = await client.post(API_URL, json={"text": user_text})
|
@@ -74,6 +78,9 @@ async def fetch_response(user_text: str):
|
|
74 |
# Command handler for /start
|
75 |
# -------------------------
|
76 |
async def start(update: Update, context: CallbackContext):
|
|
|
|
|
|
|
77 |
# Respond to the /start command.
|
78 |
await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.")
|
79 |
logger.info("Start command received.")
|
@@ -83,6 +90,10 @@ async def start(update: Update, context: CallbackContext):
|
|
83 |
# Message handler for incoming text messages
|
84 |
# -------------------------
|
85 |
async def handle_message(update: Update, context: CallbackContext):
|
|
|
|
|
|
|
|
|
86 |
user_text = update.message.text
|
87 |
logger.info(f"User message: {user_text}")
|
88 |
|
@@ -122,36 +133,39 @@ async def handle_message(update: Update, context: CallbackContext):
|
|
122 |
# -------------------------
|
123 |
# Delete Telegram webhook
|
124 |
# -------------------------
|
125 |
-
async def delete_webhook():
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
|
134 |
|
135 |
# -------------------------
|
136 |
# Set Telegram webhook
|
137 |
# -------------------------
|
138 |
-
async def set_webhook():
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
|
148 |
|
149 |
# -------------------------
|
150 |
# Main function to run the bot using Webhook mode
|
151 |
# -------------------------
|
152 |
async def main():
|
153 |
-
|
154 |
-
|
|
|
|
|
|
|
155 |
|
156 |
# Build the Application with the Telegram Bot Token
|
157 |
application = Application.builder().token(TOKEN).build()
|
@@ -160,19 +174,22 @@ async def main():
|
|
160 |
application.add_handler(CommandHandler("start", start))
|
161 |
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
162 |
|
163 |
-
# Log: starting the bot in webhook mode.
|
164 |
-
logger.info("Starting bot in webhook mode...")
|
165 |
-
|
|
|
|
|
|
|
166 |
|
167 |
|
168 |
# Run the application using webhook mode.
|
169 |
# The bot will listen on all interfaces (0.0.0.0) at the specified port.
|
170 |
-
await application.run_webhook(
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
)
|
176 |
|
177 |
|
178 |
# -------------------------
|
@@ -181,17 +198,22 @@ async def main():
|
|
181 |
if __name__ == "__main__":
|
182 |
# Apply nest_asyncio to support nested event loops if required.
|
183 |
nest_asyncio.apply()
|
184 |
-
# asyncio.run(main())
|
185 |
-
|
186 |
-
# Instead of asyncio.run(), which may try to close an already running loop,
|
187 |
-
# get the current loop and run main() until complete.
|
188 |
-
loop = asyncio.get_event_loop()
|
189 |
-
# loop.run_until_complete(main())
|
190 |
-
|
191 |
try:
|
192 |
-
|
193 |
except Exception as e:
|
194 |
logger.error(f"Error in main loop: {e}")
|
195 |
print(f"Error in main loop: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
196 |
# finally:
|
197 |
# await bot.shutdown()
|
|
|
13 |
CallbackContext
|
14 |
)
|
15 |
|
16 |
+
|
17 |
# -------------------------
|
18 |
# Configure logging
|
19 |
# -------------------------
|
20 |
+
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO)
|
|
|
|
|
21 |
logger = logging.getLogger(__name__)
|
22 |
|
23 |
+
|
24 |
# -------------------------
|
25 |
# Environment variables
|
26 |
# -------------------------
|
27 |
+
# Get Telegram bot token from environment variables
|
28 |
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
29 |
if not TOKEN:
|
30 |
raise ValueError("Missing Telegram Bot Token. Please set TELEGRAM_BOT_TOKEN environment variable.")
|
31 |
|
32 |
+
# # Get the domain for webhook (publicly accessible, e.g., your-space.hf.space)
|
33 |
+
# WEBHOOK_DOMAIN = os.getenv("WEBHOOK_DOMAIN")
|
34 |
+
# if not WEBHOOK_DOMAIN:
|
35 |
+
# raise ValueError("Missing Webhook Domain. Please set WEBHOOK_DOMAIN environment variable.")
|
36 |
|
37 |
|
38 |
+
# # -------------------------
|
39 |
+
# # Webhook configuration
|
40 |
+
# # -------------------------
|
41 |
+
# # Define a unique webhook path using the bot token
|
42 |
+
# # WEBHOOK_PATH = f"/{TOKEN}"
|
43 |
+
# # Construct the full webhook URL (must be HTTPS as required by Telegram)
|
44 |
+
# WEBHOOK_URL = f"https://{WEBHOOK_DOMAIN}"
|
45 |
+
|
46 |
|
47 |
# -------------------------
|
48 |
# API URL of the FastAPI server (running on Hugging Face)
|
49 |
# -------------------------
|
50 |
API_URL = "https://demaking-decision-helper-bot.hf.space/generate_response"
|
51 |
|
52 |
+
# bot = Bot(token=TOKEN)
|
53 |
|
54 |
# -------------------------
|
55 |
# Function to fetch response from FastAPI (unchanged)
|
56 |
# -------------------------
|
57 |
async def fetch_response(user_text: str):
|
58 |
+
"""
|
59 |
+
Sends a POST request to the FastAPI API with the user's text and returns the JSON response.
|
60 |
+
"""
|
61 |
async with httpx.AsyncClient(timeout=45.0) as client:
|
62 |
try:
|
63 |
response = await client.post(API_URL, json={"text": user_text})
|
|
|
78 |
# Command handler for /start
|
79 |
# -------------------------
|
80 |
async def start(update: Update, context: CallbackContext):
|
81 |
+
""""
|
82 |
+
Handler for the /start command.
|
83 |
+
"""
|
84 |
# Respond to the /start command.
|
85 |
await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.")
|
86 |
logger.info("Start command received.")
|
|
|
90 |
# Message handler for incoming text messages
|
91 |
# -------------------------
|
92 |
async def handle_message(update: Update, context: CallbackContext):
|
93 |
+
"""
|
94 |
+
Handler for incoming messages.
|
95 |
+
Sends the user's message to the API and replies with the response.
|
96 |
+
"""
|
97 |
user_text = update.message.text
|
98 |
logger.info(f"User message: {user_text}")
|
99 |
|
|
|
133 |
# -------------------------
|
134 |
# Delete Telegram webhook
|
135 |
# -------------------------
|
136 |
+
# async def delete_webhook():
|
137 |
+
# try:
|
138 |
+
# await bot.delete_webhook(drop_pending_updates=True)
|
139 |
+
# logger.info("Webhook deleted successfully")
|
140 |
+
# print("deleted webhook successfully")
|
141 |
+
# except Exception as e:
|
142 |
+
# logger.error(f"Failed to delete webhook manually. Error: {e}")
|
143 |
+
# print(f"error deleting bot webhook. Error: {e}")
|
144 |
|
145 |
|
146 |
# -------------------------
|
147 |
# Set Telegram webhook
|
148 |
# -------------------------
|
149 |
+
# async def set_webhook():
|
150 |
+
# # bot = Bot(token=TOKEN)
|
151 |
+
# try:
|
152 |
+
# await bot.set_webhook(url=WEBHOOK_URL) # This call will set the webhook to the given URL.
|
153 |
+
# logger.info(f"Webhook set successfully to: {WEBHOOK_URL}")
|
154 |
+
# print("webhook set succesfully")
|
155 |
+
# except Exception as e:
|
156 |
+
# logger.error(f"Failed to set webhook. Error: {e}")
|
157 |
+
# print(f"error in setting bot webhook. Error: {e}")
|
158 |
|
159 |
|
160 |
# -------------------------
|
161 |
# Main function to run the bot using Webhook mode
|
162 |
# -------------------------
|
163 |
async def main():
|
164 |
+
"""
|
165 |
+
Main function to run the Telegram Bot in polling mode.
|
166 |
+
"""
|
167 |
+
# await delete_webhook()
|
168 |
+
# await set_webhook()
|
169 |
|
170 |
# Build the Application with the Telegram Bot Token
|
171 |
application = Application.builder().token(TOKEN).build()
|
|
|
174 |
application.add_handler(CommandHandler("start", start))
|
175 |
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
176 |
|
177 |
+
# # Log: starting the bot in webhook mode.
|
178 |
+
# logger.info("Starting bot in webhook mode...")
|
179 |
+
logger.info("Starting bot in polling mode...")
|
180 |
+
print("Starting bot in polling mode...")
|
181 |
+
await application.run_polling()
|
182 |
+
|
183 |
|
184 |
|
185 |
# Run the application using webhook mode.
|
186 |
# The bot will listen on all interfaces (0.0.0.0) at the specified port.
|
187 |
+
# await application.run_webhook(
|
188 |
+
# listen="0.0.0.0", # Listen on all available interfaces
|
189 |
+
# port=7860, # Port to listen on
|
190 |
+
# # url_path=TELEGRAM_WEBHOOK, # The webhook path; here, we use the bot token
|
191 |
+
# webhook_url=WEBHOOK_URL # The webhook URL that Telegram will use to send updates
|
192 |
+
# )
|
193 |
|
194 |
|
195 |
# -------------------------
|
|
|
198 |
if __name__ == "__main__":
|
199 |
# Apply nest_asyncio to support nested event loops if required.
|
200 |
nest_asyncio.apply()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
try:
|
202 |
+
asyncio.run(main())
|
203 |
except Exception as e:
|
204 |
logger.error(f"Error in main loop: {e}")
|
205 |
print(f"Error in main loop: {e}")
|
206 |
+
|
207 |
+
|
208 |
+
# Instead of asyncio.run(), which may try to close an already running loop,
|
209 |
+
# get the current loop and run main() until complete.
|
210 |
+
# loop = asyncio.get_event_loop()
|
211 |
+
# # loop.run_until_complete(main())
|
212 |
+
|
213 |
+
# try:
|
214 |
+
# loop.run_until_complete(main())
|
215 |
+
# except Exception as e:
|
216 |
+
# logger.error(f"Error in main loop: {e}")
|
217 |
+
# print(f"Error in main loop: {e}")
|
218 |
# finally:
|
219 |
# await bot.shutdown()
|