mirror of
https://github.com/house-of-vanity/OutFleet.git
synced 2025-08-21 14:37:16 +00:00
Added TG bot
This commit is contained in:
0
telegram_bot/management/__init__.py
Normal file
0
telegram_bot/management/__init__.py
Normal file
0
telegram_bot/management/commands/__init__.py
Normal file
0
telegram_bot/management/commands/__init__.py
Normal file
99
telegram_bot/management/commands/run_telegram_bot.py
Normal file
99
telegram_bot/management/commands/run_telegram_bot.py
Normal file
@@ -0,0 +1,99 @@
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.utils import timezone
|
||||
from telegram_bot.models import BotSettings, BotStatus
|
||||
from telegram_bot.bot import TelegramBotManager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = 'Run the Telegram bot'
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.bot_manager = None
|
||||
self.running = False
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
'--force',
|
||||
action='store_true',
|
||||
help='Force start even if bot is disabled in settings',
|
||||
)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
"""Main command handler"""
|
||||
# Set up signal handlers
|
||||
signal.signal(signal.SIGINT, self.signal_handler)
|
||||
signal.signal(signal.SIGTERM, self.signal_handler)
|
||||
|
||||
# Check settings
|
||||
settings = BotSettings.get_settings()
|
||||
|
||||
if not settings.bot_token:
|
||||
self.stdout.write(
|
||||
self.style.ERROR('Bot token is not configured. Please configure it in the admin panel.')
|
||||
)
|
||||
return
|
||||
|
||||
if not settings.enabled and not options['force']:
|
||||
self.stdout.write(
|
||||
self.style.WARNING('Bot is disabled in settings. Use --force to override.')
|
||||
)
|
||||
return
|
||||
|
||||
# Initialize bot manager
|
||||
self.bot_manager = TelegramBotManager()
|
||||
|
||||
try:
|
||||
# Start the bot
|
||||
self.stdout.write(self.style.SUCCESS('Starting Telegram bot...'))
|
||||
self.bot_manager.start()
|
||||
self.running = True
|
||||
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS(f'Bot is running. Press Ctrl+C to stop.')
|
||||
)
|
||||
|
||||
# Keep the main thread alive
|
||||
while self.running:
|
||||
time.sleep(1)
|
||||
|
||||
# Check if bot is still running
|
||||
if not self.bot_manager.is_running:
|
||||
self.stdout.write(
|
||||
self.style.ERROR('Bot stopped unexpectedly. Check logs for errors.')
|
||||
)
|
||||
break
|
||||
|
||||
except KeyboardInterrupt:
|
||||
self.stdout.write('\nReceived interrupt signal...')
|
||||
|
||||
except Exception as e:
|
||||
self.stdout.write(
|
||||
self.style.ERROR(f'Error running bot: {e}')
|
||||
)
|
||||
logger.error(f'Error running bot: {e}', exc_info=True)
|
||||
|
||||
# Update status
|
||||
status = BotStatus.get_status()
|
||||
status.is_running = False
|
||||
status.last_error = str(e)
|
||||
status.last_stopped = timezone.now()
|
||||
status.save()
|
||||
|
||||
finally:
|
||||
# Stop the bot
|
||||
if self.bot_manager:
|
||||
self.stdout.write('Stopping bot...')
|
||||
self.bot_manager.stop()
|
||||
self.stdout.write(self.style.SUCCESS('Bot stopped.'))
|
||||
|
||||
def signal_handler(self, signum, frame):
|
||||
"""Handle shutdown signals"""
|
||||
self.stdout.write('\nShutting down gracefully...')
|
||||
self.running = False
|
112
telegram_bot/management/commands/telegram_bot_status.py
Normal file
112
telegram_bot/management/commands/telegram_bot_status.py
Normal file
@@ -0,0 +1,112 @@
|
||||
import logging
|
||||
import os
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.utils import timezone
|
||||
from telegram_bot.models import BotSettings, BotStatus
|
||||
from telegram_bot.bot import TelegramBotManager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = 'Check Telegram bot status and optionally start it'
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
'--auto-start',
|
||||
action='store_true',
|
||||
help='Automatically start bot if enabled in settings',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--sync-status',
|
||||
action='store_true',
|
||||
help='Sync database status with real bot state',
|
||||
)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
"""Check bot status"""
|
||||
try:
|
||||
manager = TelegramBotManager()
|
||||
settings = BotSettings.get_settings()
|
||||
status = BotStatus.get_status()
|
||||
|
||||
# Show current configuration
|
||||
self.stdout.write(f"Bot Configuration:")
|
||||
self.stdout.write(f" Enabled: {settings.enabled}")
|
||||
self.stdout.write(f" Token configured: {'Yes' if settings.bot_token else 'No'}")
|
||||
|
||||
# Show status
|
||||
real_running = manager.is_running
|
||||
db_running = status.is_running
|
||||
|
||||
self.stdout.write(f"\nBot Status:")
|
||||
self.stdout.write(f" Database status: {'Running' if db_running else 'Stopped'}")
|
||||
self.stdout.write(f" Real status: {'Running' if real_running else 'Stopped'}")
|
||||
|
||||
# Check lock file status
|
||||
from django.conf import settings as django_settings
|
||||
lock_dir = os.path.join(getattr(django_settings, 'BASE_DIR', '/tmp'), 'telegram_bot_locks')
|
||||
lock_path = os.path.join(lock_dir, 'telegram_bot.lock')
|
||||
|
||||
if os.path.exists(lock_path):
|
||||
try:
|
||||
with open(lock_path, 'r') as f:
|
||||
lock_pid = f.read().strip()
|
||||
self.stdout.write(f" Lock file: exists (PID: {lock_pid})")
|
||||
except:
|
||||
self.stdout.write(f" Lock file: exists (unreadable)")
|
||||
else:
|
||||
self.stdout.write(f" Lock file: not found")
|
||||
|
||||
if db_running != real_running:
|
||||
self.stdout.write(
|
||||
self.style.WARNING("⚠️ Status mismatch detected!")
|
||||
)
|
||||
|
||||
if options['sync_status']:
|
||||
status.is_running = real_running
|
||||
if not real_running:
|
||||
status.last_stopped = timezone.now()
|
||||
status.save()
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS("✅ Status synchronized")
|
||||
)
|
||||
|
||||
# Show timestamps
|
||||
if status.last_started:
|
||||
self.stdout.write(f" Last started: {status.last_started}")
|
||||
if status.last_stopped:
|
||||
self.stdout.write(f" Last stopped: {status.last_stopped}")
|
||||
if status.last_error:
|
||||
self.stdout.write(f" Last error: {status.last_error}")
|
||||
|
||||
# Auto-start if requested
|
||||
if options['auto_start']:
|
||||
if not real_running and settings.enabled and settings.bot_token:
|
||||
self.stdout.write("\nAttempting to start bot...")
|
||||
try:
|
||||
manager.start()
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS("✅ Bot started successfully")
|
||||
)
|
||||
except Exception as e:
|
||||
self.stdout.write(
|
||||
self.style.ERROR(f"❌ Failed to start bot: {e}")
|
||||
)
|
||||
elif real_running:
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS("✅ Bot is already running")
|
||||
)
|
||||
elif not settings.enabled:
|
||||
self.stdout.write(
|
||||
self.style.WARNING("⚠️ Bot is disabled in settings")
|
||||
)
|
||||
elif not settings.bot_token:
|
||||
self.stdout.write(
|
||||
self.style.ERROR("❌ Bot token not configured")
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
self.stdout.write(
|
||||
self.style.ERROR(f"❌ Error checking bot status: {e}")
|
||||
)
|
Reference in New Issue
Block a user