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()
Leave a Reply