|
|
from fastapi import FastAPI, BackgroundTasks |
|
|
from fastapi.responses import JSONResponse |
|
|
import uvicorn |
|
|
from typing import Optional |
|
|
from telegram_bot import WeBookBot |
|
|
import os |
|
|
from dotenv import load_dotenv |
|
|
|
|
|
|
|
|
load_dotenv() |
|
|
|
|
|
|
|
|
app = FastAPI(title="WeBook Bot API", description="API for controlling the WeBook Telegram Bot") |
|
|
|
|
|
|
|
|
bot: Optional[WeBookBot] = None |
|
|
|
|
|
@app.on_event("startup") |
|
|
async def startup_event(): |
|
|
"""Initialize bot on startup""" |
|
|
global bot |
|
|
token = os.getenv('TELEGRAM_BOT_TOKEN') |
|
|
if not token: |
|
|
raise ValueError("TELEGRAM_BOT_TOKEN not found in environment variables") |
|
|
bot = WeBookBot(token) |
|
|
|
|
|
@app.on_event("shutdown") |
|
|
async def shutdown_event(): |
|
|
"""Cleanup on shutdown""" |
|
|
global bot |
|
|
if bot and bot.is_running: |
|
|
await bot.stop_bot() |
|
|
|
|
|
@app.post("/startbot") |
|
|
async def start_bot(background_tasks: BackgroundTasks): |
|
|
"""Start the Telegram bot""" |
|
|
global bot |
|
|
if not bot: |
|
|
return JSONResponse( |
|
|
status_code=500, |
|
|
content={"status": "error", "message": "Bot not initialized"} |
|
|
) |
|
|
|
|
|
if bot.is_running: |
|
|
return JSONResponse( |
|
|
status_code=200, |
|
|
content={"status": "success", "message": "Bot is already running"} |
|
|
) |
|
|
|
|
|
|
|
|
background_tasks.add_task(bot.start_bot) |
|
|
|
|
|
return JSONResponse( |
|
|
status_code=200, |
|
|
content={"status": "success", "message": "Bot starting in background"} |
|
|
) |
|
|
|
|
|
@app.post("/stopbot") |
|
|
async def stop_bot(): |
|
|
"""Stop the Telegram bot""" |
|
|
global bot |
|
|
if not bot: |
|
|
return JSONResponse( |
|
|
status_code=500, |
|
|
content={"status": "error", "message": "Bot not initialized"} |
|
|
) |
|
|
|
|
|
success, message = await bot.stop_bot() |
|
|
|
|
|
return JSONResponse( |
|
|
status_code=200 if success else 500, |
|
|
content={"status": "success" if success else "error", "message": message} |
|
|
) |
|
|
|
|
|
@app.get("/botstatus") |
|
|
async def get_bot_status(): |
|
|
"""Get the current status of the bot""" |
|
|
global bot |
|
|
if not bot: |
|
|
return JSONResponse( |
|
|
status_code=500, |
|
|
content={"status": "error", "message": "Bot not initialized"} |
|
|
) |
|
|
|
|
|
return JSONResponse( |
|
|
status_code=200, |
|
|
content={ |
|
|
"status": "success", |
|
|
"is_running": bot.is_running, |
|
|
"message": "Bot is running" if bot.is_running else "Bot is stopped" |
|
|
} |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
uvicorn.run( |
|
|
"api:app", |
|
|
host="0.0.0.0", |
|
|
port=7860, |
|
|
reload=True |
|
|
) |