Realtime Status updates using a Telegram Bot

󰃭 2024-10-02

Or, How to Send Status Message from GitHub Actions to Telegram: A Guide

I occasionally find myself wanting a quick and easy way to send alerts and status message and a solution I keep coming back to is using a Telegram bot. Telegram is free to use, reliable and easy to setup. It only takes a few minutes to set up the a bot and fire of a test message using curl. From there you can start sending messages from just about anything that can make an HTTP request. (The same cannot be said for WhatsApp or Signal, which are considerably more complex to setup)

This time around I found myself wanting to get a notification when a deployment of this very blog has completed. This very site is built using Hugo and a GitHub Action Workflow builds and deploys the site when I merge to main.

So, in this post, we’ll walk through creating a GitHub Composite Action that sends status messages from your CI/CD pipeline directly to a Telegram chat. We’ll cover:

  1. Creating a Telegram bot and obtaining the TOKEN
  2. Getting the CHAT_ID of the Telegram chat so you can get messages from your bot
  3. Setting up the GitHub repository to use this action

Step 1: Creating a Telegram Bot and Getting the TOKEN

To interact with Telegram’s API, you first need a Telegram bot. When we later send message they will come from the bot.

Create a Bot:

  1. Open Telegram and search for the BotFather (Telegram’s bot management bot).
  2. Start a chat with BotFather by clicking on it and typing /start.
  3. Use the /newbot command to create a new bot. BotFather will prompt you for a name and a unique username for the bot. Follow the prompts and give your bot a meaningful name and username. (The username has to be globally unique across Telegram, it can take a while to find a name that is not already in use.)
  4. Once the bot is created, you will receive a TOKEN. This token is crucial for authenticating API requests, don’t lose it!

Example:

Use this token to access the HTTP API:
123456789:ABCDEFGHIJKLMNOpqrstuvwxyz123456789

Make sure to keep this token secure, as it grants access to your bot.

Step 2: Getting the CHAT_ID for Your Telegram Chat

Each Telegram chat has a unique CHAT_ID that allows the bot to know where to send the messages.

Add the Bot to a Group (Optional for Group Notifications)

  • If you want to receive notifications in a group, create a new Telegram group and add your bot to that group.

Find Your CHAT_ID To get the CHAT_ID, you need to send a message to the bot and access the bot’s updates via the Telegram API.

  1. Send a message to your bot (either directly or in the group if you added it there).
  2. Curl the following URL, replacing <TOKEN> with your actual bot token. (We are also piping through jq to make the JSON response easier to read)
curl https://api.telegram.org/bot<TOKEN>/getUpdates | jq
  1. The response will be a JSON object containing the recent messages sent to the bot. Look for the chat object inside the message field. The id field inside this chat object is your CHAT_ID.

Example response:

{
   "ok": true,
   "result": [
      {
         "update_id": 123456789,
         "message": {
            "message_id": 2,
            "from": { ... },
            "chat": {
               "id": 90210,
               "first_name": "John",
               "type": "private"
            },
            "date": 1615555555,
            "text": "Hello bot!"
         }
      }
   ]
}

In this case, the CHAT_ID is 90210.

Step 3: Setting Up GitHub Actions to Send Messages to Telegram

Now that you have your TELEGRAM_TOKEN and CHAT_ID, let’s integrate them into your GitHub Actions workflow.

Storing the Telegram Token in GitHub Secrets

  1. Go to your GitHub repository.
  2. Click on Settings > Secrets and variables > Actions > New repository secret.
  3. Create a new secret called TELEGRAM_TOKEN and paste the bot token from Step 1.

Defining the Chat ID in GitHub Variables

  1. Still under Settings, go to Secrets and variables > Actions > Variables.
  2. Click New repository variable and create a variable named TELEGRAM_CHAT_ID with the value of the chat ID you retrieved in Step 2.

Creating the GitHub Composite Action

Now let’s create the GitHub Composite Action that will send status messages to Telegram.

  1. In your repository, create the following directory structure:

    .github/
    └── actions/
        └── send-telegram-status/
            └── action.yml
    
  2. In the action.yml file, add the following code:

name: "Send Telegram Status"
description: "A GitHub Action to send a status message to a Telegram chat"
inputs:
  message:
    description: "The status message to send"
    required: true
  telegram_token:
    description: "The Telegram bot token"
    required: true
    # GitHub allows us to pass secrets as inputs from the workflow.
  telegram_chat_id:
    description: "The Telegram chat ID"
    required: true
runs:
  using: "composite"
  steps:
    - name: Send message to Telegram
      run: |
        curl -X POST "https://api.telegram.org/bot${{ inputs.telegram_token }}/sendMessage" \
        -d chat_id=${{ inputs.telegram_chat_id }} \
        -d text="${{ inputs.message }}"        
      shell: bash

Using the Action in a Workflow

You can now use the custom action to send messages from your workflow. Here’s an example workflow that sends a success message after the build completes:

name: CI

on:
  push:
    branches:
      - main

jobs:
  send-status:
    runs-on: ubuntu-latest
    steps:
      - name: Send status to Telegram
        uses: ./.github/actions/send-telegram-status
        with:
          message: "Build Successful!"
          telegram_token: ${{ secrets.TELEGRAM_TOKEN }}
          telegram_chat_id: ${{ vars.TELEGRAM_CHAT_ID }}

Testing the Action

To test the integration:

  1. Push your changes to the repository.
  2. Observe the workflow execution in the Actions tab of your repository.
  3. You should receive the status message in your Telegram chat.

Wrapping up

In this guide, we walked through creating a Telegram bot, retrieving the necessary TOKEN and CHAT_ID, and setting up a GitHub Composite Action to send messages to Telegram. By incorporating this into your CI/CD pipeline, you can stay informed about the status of your (no doubt) very important GitHub workflows in real-time. Never miss a flakey build again!