Code snippets

  • Python function to send a single Telegram bot message

    This is my console.log equivalent when I need a quick observability implementation.

    Usually, when you build a Telegram bot, you have to have a small server listening for updates.

    The server logic is abstracted away as a simple API using the python-telegram-bot package, but we can write a simpler implementation for a single message:

    import os
    import telegram
    
    TELEGRAM_BOT_ID = os.getenv("TELEGRAM_BOT_ID")
    TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
    
    async def send_telegra_notification(msg: str, origin: str = "AppName:main"):
        notification_msg = f"*{origin}*: {msg}"
        bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN)
        try:
            await bot.initialize()
            await bot.send_message(
                chat_id=TELEGRAM_BOT_ID,
                text=notification_msg,
                parse_mode=telegram.constants.ParseMode.MARKDOWN,
            )
        except Exception as e:
            # handle exception, e.g., logger.error(e)
            print(e)
        finally:
            await bot.shutdown()
    
  • Launch a simple HTTP Server in One Line of Python

    I always google this snippet when I need it, so I will put it here for easier access.

    python3 -m http.server 8080 -d ./public
  • Types of UUID

    • v1: mac address + time + random
    • v4: completely random
    • v5: input + seed (consistent, derived from input)
    • v7: time + random (distributed sortable ids)

    Source