AshciR / group-chat-digest

0 stars 0 forks source link

Add Health Check #29

Closed AshciR closed 5 months ago

AshciR commented 6 months ago

Add a health check to the app. This allows ECS to determine when the application is in a ready state.

Suggestions:

AshciR commented 5 months ago
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
import uvicorn

async def health(request):
    """
    Health check endpoint to ensure the service is up and running.
    Returns a JSON response with the health status.
    """
    return JSONResponse({'status': 'healthy'})

app = Starlette(
    debug=True,
    routes=[
        Route('/healthcheck', health, methods=["GET"]),
    ]
)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)  # Use the appropriate port for your environment
import asyncio
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
import uvicorn
from telegram.ext import Updater, CommandHandler

# Define a simple health check endpoint
async def health(request):
    return JSONResponse({'status': 'healthy'})

# Initialize the Starlette app
app = Starlette(
    debug=True,
    routes=[
        Route('/healthcheck', health, methods=["GET"]),
    ]
)

# Initialize your Telegram Bot
def start(update, context):
    """Sends a message when the command /start is issued."""
    update.message.reply_text('Hi!')

def setup_bot():
    """Set up and return the Telegram bot updater."""
    TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
    updater = Updater(TOKEN, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("start", start))
    return updater

def run_bot():
    """Start the bot."""
    updater = setup_bot()
    updater.start_polling()
    updater.idle()

# Asynchronous function to run the web server
async def run_webserver():
    config = uvicorn.Config(app=app, host="0.0.0.0", port=8000)
    server = uvicorn.Server(config)
    await server.serve()

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    bot = loop.run_in_executor(None, run_bot)
    loop.run_until_complete(run_webserver())
AshciR commented 5 months ago

Step 2: Explain the Key Components Health Check Endpoint: A simple Starlette setup to handle HTTP GET requests at /healthcheck endpoint. Bot Setup: Uses python-telegram-bot to define a simple bot with a /start command. run_bot() Function: This function sets up the bot and starts it with long polling. It is designed to run indefinitely. run_webserver() Function: An asynchronous function to start the Starlette Uvicorn server.

Step 3: Integrate and Run Asynchronously asyncio.get_event_loop(): Get the current event loop. loop.run_in_executor(): Run the bot in a separate thread managed by asyncio. This is necessary because the bot’s start_polling() method is blocking and needs to run continuously. loop.run_until_complete(): Start the web server asynchronously and block until it completes, which it won’t unless stopped or an error occurs.

Step 4: Deployment Considerations Ensure that all dependencies are correctly installed and that your server has access to the necessary network ports (e.g., port 8000 for the webserver). Configure your deployment environment to allow inbound traffic on the necessary ports and ensure proper security group settings when deployed on cloud platforms like AWS. By structuring your application in this way, you can efficiently run both the Telegram bot and the web server concurrently within the same Python application, making full use of asynchronous programming practices.