baha-99 commited on
Commit
018195c
·
1 Parent(s): efd47cf

fix: adapt bot initialization for Hugging Face environment

Browse files
Files changed (1) hide show
  1. bot_telegram.py +33 -5
bot_telegram.py CHANGED
@@ -9,11 +9,15 @@ import asyncio
9
  from concurrent.futures import ThreadPoolExecutor
10
  import time
11
  import pandas as pd
 
12
 
13
  # Configure logging
14
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
15
 
16
- # Load environment variables from Hugging Face Secrets
 
 
 
17
  BOT_SECRET_PASSWORD = os.getenv("BOT_SECRET_PASSWORD")
18
  BOT_TOKEN = os.getenv("BOT_TOKEN")
19
  BASE_URL = os.getenv("BASE_URL")
@@ -31,10 +35,16 @@ AWAITING_PASSWORD = set()
31
 
32
  logging.info("Bot starting... v0.1.0") # Add version number
33
 
 
 
 
 
 
 
34
  class TelegramBot:
35
  """A Telegram bot with password-based authentication."""
36
 
37
- def __init__(self, bot_token, base_url):
38
  """Initialize the bot with Telegram API token, API credentials, and authentication."""
39
  self.bot_token = bot_token
40
  self.base_url = base_url
@@ -47,7 +57,7 @@ class TelegramBot:
47
  self.ai_url = f"{self.base_url}/api/v1/questions/text"
48
  self.excel_url = f"{self.base_url}/api/v1/questions/excel"
49
 
50
- # Executors (keep only one instance of each)
51
  self.text_executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix="text_worker")
52
  self.excel_executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix="excel_worker")
53
  self.excel_semaphore = asyncio.Semaphore(10)
@@ -57,7 +67,10 @@ class TelegramBot:
57
  self.active_excel_files = {}
58
 
59
  # Start Telegram Bot
60
- self.app = Application.builder().token(self.bot_token).build()
 
 
 
61
  self.setup_handlers()
62
 
63
  # Authenticate with API
@@ -506,4 +519,19 @@ class TelegramBot:
506
  await self.app.shutdown()
507
 
508
  def init_bot():
509
- return TelegramBot(bot_token=BOT_TOKEN,base_url=BASE_URL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  from concurrent.futures import ThreadPoolExecutor
10
  import time
11
  import pandas as pd
12
+ from dotenv import load_dotenv
13
 
14
  # Configure logging
15
  logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
16
 
17
+ # Load environment variables
18
+ load_dotenv()
19
+
20
+ # Load environment variables from .env file
21
  BOT_SECRET_PASSWORD = os.getenv("BOT_SECRET_PASSWORD")
22
  BOT_TOKEN = os.getenv("BOT_TOKEN")
23
  BASE_URL = os.getenv("BASE_URL")
 
35
 
36
  logging.info("Bot starting... v0.1.0") # Add version number
37
 
38
+ # Add debug logging
39
+ logging.info(f"BOT_TOKEN loaded: {'yes' if BOT_TOKEN else 'no'}")
40
+ logging.info(f"BASE_URL loaded: {'yes' if BASE_URL else 'no'}")
41
+ logging.info(f"HF_TOKEN loaded: {'yes' if HF_TOKEN else 'no'}")
42
+ logging.info(f"BOT_SECRET_PASSWORD loaded: {'yes' if BOT_SECRET_PASSWORD else 'no'}")
43
+
44
  class TelegramBot:
45
  """A Telegram bot with password-based authentication."""
46
 
47
+ def __init__(self, bot_token, base_url, application=None):
48
  """Initialize the bot with Telegram API token, API credentials, and authentication."""
49
  self.bot_token = bot_token
50
  self.base_url = base_url
 
57
  self.ai_url = f"{self.base_url}/api/v1/questions/text"
58
  self.excel_url = f"{self.base_url}/api/v1/questions/excel"
59
 
60
+ # Executors
61
  self.text_executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix="text_worker")
62
  self.excel_executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix="excel_worker")
63
  self.excel_semaphore = asyncio.Semaphore(10)
 
67
  self.active_excel_files = {}
68
 
69
  # Start Telegram Bot
70
+ if application:
71
+ self.app = application
72
+ else:
73
+ self.app = Application.builder().token(self.bot_token).build()
74
  self.setup_handlers()
75
 
76
  # Authenticate with API
 
519
  await self.app.shutdown()
520
 
521
  def init_bot():
522
+ load_dotenv()
523
+ logging.info("Initializing bot...")
524
+
525
+ try:
526
+ if os.getenv('SPACE_ID'): # Check if running on Hugging Face
527
+ logging.info("Running on Hugging Face, using custom settings...")
528
+ application = Application.builder().token(BOT_TOKEN).base_url(
529
+ "https://api.telegram.org/bot"
530
+ ).get_updates_connection_pool_size(100).connection_pool_size(100).connect_timeout(30).read_timeout(30).write_timeout(30).pool_timeout(30).build()
531
+ return TelegramBot(bot_token=BOT_TOKEN, base_url=BASE_URL, application=application)
532
+ else:
533
+ logging.info("Running locally, using default settings...")
534
+ return TelegramBot(bot_token=BOT_TOKEN, base_url=BASE_URL)
535
+ except Exception as e:
536
+ logging.error(f"Error initializing bot: {str(e)}")
537
+ raise