Step-by-Step: Sending Telegram Messages from Your Website

WebCraft Notes - Apr 23 - - Dev Community

Sending Telegram Messages from Your Website

Check this post in my web notes!

In this article, we'll explore the step-by-step process of sending messages from your Vue.js application to Telegram. Harnessing the power of real-time notifications is invaluable, especially for events like subscriptions or sales. Telegram, with its robust features, serves as an ideal platform for these notifications. Let's delve into crafting a practical example.

1. Register Our First Telegram Bot

Yes, we will register Telegram Bot which will be like an app-user, and inform us about some events. For that reason, you need to find "BotFather" (just type BotFather in the telegram search field).

BotFather is a special bot created by Telegram to help users create and manage their bots on the platform. It provides a simple interface for generating new bot tokens, setting bot names, and configuring various bot settings.

Next type "start", and you'll see the commands list and all the functionality with which BotFather can deal.

BotFather commands

Then, let's type /newbot, this command will create a new bot but also will demand from us some additional information like bot name and username. If everything is ok you'll get a new message with an access token for our sending message app.

create new bot

Yes, so easy, we have our bot and next what we gonna do is create a simple form for messages.

2. Get a Telegram Chat ID

We are planning to send messages from the bot to the user directly. There could be many users that will use our bot, but we want to send a message to some specific user, and for that reason, we need to get a channel ID or in our case user ID. We will use the simplest way, another bot "userinfobot".

Type in the telegram search field "userinfobot", open that bot, and press the start button. That bot will give you your Telegram ID.

get the personal Telegram id

That's all, we made all the preparations and on the last step, we can create some simple form and start with message.

3. Send Messages from the Web App to Telegram

I will not spend much time on form creation, I will use the example of a contact form from freefrontend service.

We need a simple html/css page with form and I chose this one:

contact form

More interesting and important is our JS code.

First of all, we will add an event listener to the form. Inside the event listener, we will get values from all the fields: name, email, and message, and use simple telegram API to send messages with all data from our form fields.

Do not forget to replace "bot_token" and "chat_id" with your data.

<script>
    const form = document.querySelector("form");
        form.addEventListener("submit", (e) => {
            e.preventDefault();
            const name = document.querySelector("#name").value;
            const email = document.querySelector("#email").value;
            const message = document.querySelector("#message").value;
            const telegram_message = `Name: ${name}\nEmail: ${email}\nMessage: ${message}`;
            fetch(`https://api.telegram.org/bot${telegram_bot_token}/sendMessage`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        chat_id: telegram_chat_id,
                        text: telegram_message
                    })
            })
                .catch(error => {
                    console.error('Error sending message:', error);
            });
        });
</script>
Enter fullscreen mode Exit fullscreen mode

Awesome! We need to test our app. Let's find our bot, in the telegram search field type the name of the bot you created before and press the start button. Then add some data to the form and press the "Send Message" button. Check your telegram.

Send telegram message

result of sending telegram message

In this guide, we've navigated through the process of integrating Telegram messaging into your application. Real-time notifications are a super simple benefit for enhancing user engagement, particularly for critical events. By harnessing the power of Telegram and following the outlined steps, you're now equipped to implement a messaging system that keeps users informed and engaged. Happy coding and enjoy the seamless communication experience with your app users on Telegram!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .