2024-03-19
BotFather

How to send Telegram Notifications with Google Cloud Build (GCB)

https://sylvainleroy.com/wp-admin/options-general.php?page=ad-inserter.php#tab-2

This article is a quick HOW-TO after struggling with Google Cloud Build about how to send notifications when a build has failed or is successful. Since I did not want to use Slack and the heavy client, I give a try in this post with and discover the magical chatbot world.

Updated on November 2020 with better explanations of how to connect Cloud Builds to the Pub/Sub topic.

Contents

Google Cloud Build

Cloud Build is a service that executes your builds on Google Cloud Platform infrastructure. Cloud Build can import source code from Google Cloud Storage, Cloud Source Repositories, GitHub, or Bitbucket, execute a build to your specifications, and produce artifacts.

Google Cloud Build is rather a cheap alternative to Jenkins, Travis-Ci, and Circle CI if you have private projects. While the other solutions require a quite expensive subscription, you pay GCB according to the used build time. If you do not commit frequently or the build is a short task, it is a really fair solution. And an extra bonus, the first 120 build minutes are free.

Google Cloud Build
Google Cloud Build

As you see, the Google Cloud Build interface is not as attractive as the other competitors. That’s why I wanted at the bare minimum to receive some notifications.

There is no built-in process therefore I had to build my own. GCB recommends Slack however my choice is in favor of mobile push messages with Telegram.

is a cloud-based instant messaging and voice over IP service. Users can send messages and exchange photos, videos, stickers, audio, and files of any type. Default Messages and media in Telegram are encrypted when stored on its servers.

Telegram running on an iPhone X (wikipedia)
running on an iPhone X (wikipedia)

Bots

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands, and inline requests. You control your bots using HTTPS requests to our bot API.

What can do a BOT ( extracted from website) :

  • Get customized notifications and news.
  • Integrate with other services.
  • Accept payments from Telegram users.
  • Create custom tools.
  • Build single- and multiplayer games.
  • Build social services.

How to send notifications with GCB

Here is a to explain how to implement such notification bot.

Google Cloud Telegram implementation diagram
Google Cloud Telegram implementation

The does not the implementation order. Here is the order that I followed.

Create a Job with GCB

The first step is to identify your GIT repository that you want to use as a demo project.

Then go into the Google Cloud Build section :

Google Cloud Build access
Google Cloud Build access

You have two available actions, Connect to repository and Create a Trigger once your GitHub repository has been connected.

GCB Connect Repository
GCB Connect Repository

Check the presence of the subject

You should have a topic created by GCB indicating that the build messages are sent into a dedicated queue.

 

Other information about how to connect the Queue to Cloud Build :

The documentation of Cloud Build has changed and I didn’t find the part about how to connect Cloud Builds to a Pub/Sub topic.

Some links may help :

IMPORTANT PART TO KNOW

Cloud Build publishes messages on a Google Pub/Sub topic when your build’s state changes, such as when your build is created, when your build transitions to a working state, and when your build completes.

The Pub/Sub topic to which Cloud Build publishes these build update messages is called cloud-builds. Each message contains a base64 JSON string representation of your Build resource in the message.data attribute. The build’s unique ID and the build’s status can be found in the message.attributes field.

You can use a push or pull model for your Pub/Sub subscriptions.

 

Create the Telegram BOT

Now it is time for the fun part of the tutorial.

You will have to install first the Telegram application on your mobile phone and to follow this tutorial to create your BOT. Just talk to BotFather

BotFather
BotFather

After the creation of the BOT, store in your password manager, the Telegram TOKEN.

Create the Cloud Function

In this step, we will finally create our Telegram notification chatbot. The program will be coded in Node.js and deployed as a Cloud Function in Google Cloud.

Why a Cloud Function? Because we do not want to allocate a full-time virtual machine to process only during a few seconds the Google Build messages.

The code is available there and the explanation is pretty straightforward: https://github.com/sleroy/gcb-telegram-build

Deploying the Cloud Function

To deploy the Cloud function, you need to use gcloud.

The cloud function is only publishing in a  single GROUP_ID.

To obtain a Telegram GROUP Id, you need to add the Telegram bot by inviting it into a group. Then you need to query a special endpoint to get the list of all subscriptions for this bot.

Here is the Q/A about it : https://stackoverflow.com/questions/32423837/telegram-bot-how-to-get-a-group-chat-id

The deployment instruction to push the cloud function. If everything is OK, the cloud function will be deployed.

gcloud functions deploy subscribeTelegram --trigger-topic cloud-builds --runtime nodejs10 --set-env-vars "TELEGRAM_TOKEN=token1,GROUP_ID=groupID"

Result

What you should obtain, is an output similar to that :

Deploying function (may take a while - up to 2 minutes)...done. 
availableMemoryMb: 256
entryPoint: subscribeTelegram
environmentVariables:
GROUP_ID: 'xxxxxxxxxx'
TELEGRAM_TOKEN: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
eventTrigger:
eventType: google.pubsub.topic.publish
failurePolicy: {}
resource: projects/xxxxxxxx/topics/cloud-builds
service: pubsub.googleapis.com
labels:
deployment-tool: cli-gcloud
name: projects/xxxxxxxxx/locations/us-central1/functions/subscribeTelegram
runtime: nodejs10
serviceAccountEmail: xxxxxxxxxx@appspot.gserviceaccount.com
sourceUploadUrl: https://storage.googleapis.com/gcf-upload-us-central1-
status: ACTIVE
timeout: 60s
updateTime: '2019-12-10T21:44:59Z'
versionId: '14'


The Telegram notification program

Conclusion and further improvements

This bot is really simple and easy to do but it lacks the main feature, to answer commands. Here is a list of interesting commands I would like to add :

  • get the list of nth last commits
  • to trigger a build
  • display the build logs (or the last nth lines)

For this, you need to implement a bot server (in node.js for example). There are plenty of examples on the Internet and it will be probably the subject of another article.

 

 

 

 

Sylvain Leroy

Senior Software Quality Manager and Solution Architect in Switzerland, I have previously created my own company, Tocea, in Software Quality Assurance. Now I am offering my knowledge and services in a small IT Consulting company : Byoskill and a website www.byoskill.com Currently living in Lausanne (CH)

View all posts by Sylvain Leroy →