Publishing messages to a telegram channel with AWS lambda

Alternative Text
by Dmitry Elisov
Oqtacore CTO
675

Table of content

alt

Telegram is a great thing with all its bots, groups, and channels. Let’s learn to post channel messages with an AWS Lambda

For many of us developers, telegram became not only a single point of communication with real people but also with our infrastructure. For example, we at OQTACORE often use telegram bots for alerts and simple configuration commands. In some cases, in the early stages of development, we even use telegram bots to monitor and reboot application servers on the weekends. A simple telegram bot is much easier to use than accessing SSH or an AWS console.

But today we want to describe one of the most classical snippets we use – that is an AWS lambda that sends messages to a given channel. This can be used for the simplest alert mechanism.

Create a new bot

First, you would need a telegram bot. If you haven’t already, open your Telegram client and message to @botfather

Creating a new telegram botAfter a series of simple commands, you will be granted a token (pointed at by the red arrow).

Add the bot to your alerts channel

Create a new telegram channel and your bot there. Telegram will let you know that the bot can only be added with admin rights, and it should be fine.

Creating a new telegram channel

Get the channel ID

 Before writing the lambda, you will need to know the channel’s ID. This is not hard. First, write some messages to the channel. Then you can use CURL:

curl ‘https://api.telegram.org/bot{token}/getUpdates’

 

Don’t forget to replace {token} with your bot token that you obtained from @botfather!

You will receive json with all messages from the channel, so let’s say I wrote ‘hey’:

{

  “ok”: true,

  “result”: [

{

   “update_id”: 54351351,

   “channel_post”: {

     “message_id”: 8,

     “sender_chat”: {

       “id”: -351351351321,

       “title”: “FsBet Alerts”,

       “type”: “channel”

     },

     “chat”: {

       “id”: -351351354351,

       “title”: “FsBet Alerts”,

       “type”: “channel”

     },

     “date”: 1660047498,

     “text”: “hey”

   }

}

  ]

}

 

From this JSON, you need result.channel_post.chat.id. Just copy it manually, you don’t need to write any code here 🙂

Finally, the AWS lambda

This lambda is written in a such way that it can be immediately used with an API Gateway Proxy. It returns correct HTTP response codes. But you still can use it directly.

const https = require(‘https’);

const chatId = %MY_CHAT_ID%;

const botToken = ‘%MY_BOT_TOKEN%’;

exports.handler = async (event) => {

const response = await sendMessage(JSON.parse(event.body).message);

return response;

};

async function sendMessage(message) {

const response = {

     statusCode: 200,

     headers: {

         ‘Content-Type’: ‘application/json’,

     }

};

return new Promise((resolve, reject) => {

     const data = JSON.stringify({

         chat_id: chatId,

         text: message,

         parse_mode: ‘HTML’

     });

     const options = {

         hostname: ‘api.telegram.org’,

         port: 443,

         path: `/bot${botToken}/sendMessage`,

         method: ‘POST’,

         headers: {

             ‘Content-Type’: ‘application/json’,

             ‘Content-Length’: data.length,

         }

     }

     const req = https.request(options, res => {

         res.on(‘data’, d => {

             response.body = JSON.stringify(data);

             response.statusCode = 200;

             resolve(response);

         });

     });

     req.on(‘error’, error => {

         response.body = JSON.stringify(error)

         response.statusCode = 503;

         reject(error);

     });

     req.write(data);

     req.end();

})

}

To call this lambda, you can use such a test lambda event:

{

  “body”: “{\”message\”: \”test\”}”

}

Or, if you add this lambda to an API Gateway Proxy, this would be the way to call it:

curl –request POST ‘https://mysecretdomain.execute-api.eu-west-2.amazonaws.com/qa/telegram-bot/send-alert’ \

–header ‘Content-Type: application/json’ \

–data-raw ‘{

  “message”: “test”

}’

Conclusion

That’s it! Now you have a AWS lambda that you can call internally via AWS SDK or externally via API Gateway to send alerts to your telegram channel. We start most of our projects with this lambda, as setting up alerts is essential to ensure that everything works correctly… Especially on the weekends! 🙂

Frequently Asked Questions:
How do I start working with OQTACORE?

We have a call and discuss details of the project

You make an initial payment for the project

Our CTO and your assigned Project Manager write the specification documents for the project

We discuss and approve the specs with you

We compile the specs into a development schedule

We implement the specs with releases every two weeks

How much does MVP cost?

It depends on the package you choose. Feel free to explore each package with prices and examples on our landing page or use our calculator.

How much time is take to build an MVP?

Prototype – 10 days

MVP for one platform (Android/iOS/Web) – 1-3 months

MVP for three platform (Android/iOS/Web) – 3-6 months

Do you sign an NDA?

We sign an NDA with each customer. All the source code and intellectual property will belong to you.

Who will I communicate with during the project?

You will have 24/7 access to PM Saveliy Leniivin and CTO Dmitry Elisov, who will guide your project from start to finish.

What are the team’s working hours?

We work on weekdays Pacific Standard Time (PST), UTC -8. 8am – 11pm. This schedule allows us to communicate with you and to do the work as efficiently as possible, regardless of the time zone difference.

How can I control the project?

You will have access to Jira (it is a project management software used by many companies in the world), where we will manage your entire project. There, you will see each task and its due date.

Is it possible to add/remove features after the project has started and specification and implementation plan have been approved?

Yes, it is possible. We will create an additional specification, in which we will write down the additional features you want to introduce, and we will add them to the UI design and development plan.

What will I get as the end result?

A ready-to-use application that can be downloaded from the App Store, Google Play or used as a web app + all copyright for the code + documentation.

Can I come and visit your office?

You can visit us any time!

Are you a team of just 7?

Our core MVP team consists of seven people: CTO, IT PM, Designer, Backend software developer, Frontend software developer, QA tester. This is an example of our team that will interact with you during the creation of your MVP. As the app develops and expands, other members will join the team.

Apart from developing MVPs from scratch, we have a team that is engaged in maintaining current projects and scaling them. For one of our customers, we have assembled and manage a team of 23 programmers who are continuing to develop our customer’s successful startup right now.

Rate this article
Please wait...