Search code examples
gitlabnotificationsgitlab-citelegram

How to send notification to Telegram from GitLab pipeline?


In our small startup we use GitLab for development and Telegram for internal communication between developers and PO. Since the PO would like to see the progress immediately, we have set up the GitLab Pipeline so that the preview version is deployed on the web server after each commit. Now we want to expand the pipeline. So that after the deployment a notification is sent via the Telegram group.

So the question - is that possible, and if so, how?

EDIT: since I've already implemented that, that's not a real question. I wanted to post the answer here so that others can use it as well.


Solution

  • So, we'll go through it step by step:

    1. Create a Telegram bot
    2. Add bot to Telegram group
    3. Find out Telegram group Id
    4. Send message via GitLab Pipeline

    1. Create a Telegram bot

    There are enough good instruction from Telegram itself for this:

    https://core.telegram.org/bots#6-botfather

    The instructions do not say anything explicitly, but to generate it, you have to go into the chat with the BotFather. At the end you get a bot token, something like 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw

    2. Add bot to Telegram group

    Switch to the Telegram group, and add the created bot as a member (look for the bot by name).

    3. Find out Telegram group Id

    Get the update status for the bot in browser: https://api.telegram.org/bot<YourBOTToken>/getUpdates

    Find the chat-id in the response: ... "chat": {"id": <YourGroupID>, ...

    see for more details: Telegram Bot - how to get a group chat id?

    4. Send message via GitLab Pipeline

    Send message with a curl command. For example, an existing stage in gitlab pipeline can be extended for this purpose:

    upload:
      stage: deploy
      image: alpine:latest
      script:
        - 'apk --no-cache add curl'
        - 'curl -X POST -H "Content-Type: application/json" -d "{\"chat_id\": \"<YourGroupID>\", \"text\": \"CI: new version was uploaded, see: https://preview.startup.com\"}" https://api.telegram.org/bot<YourBOTToken>/sendMessage '
      only:
        - main
    

    Remember to adapt the YourBOTToken and YourGroupID, and the text for the message.

    *) we use the alpine docker image here, so curl has to be installed - 'apk --no-cache add curl'. With other images this may have to be done in a different way.