Sending Telegram Messages made Easier with Telegram Bot

Paul Issack 12 Jul, 2022 • 7 min read

This article was published as a part of the Data Science Blogathon.

Introduction

Handling social media are now becoming more popular for all. Most of the time in groups or channels you may have seen that you are receiving automated messages from unknown people. But you need to get to know that messages are not from peoples it is from bots. A bot is a software application that can run automated scripts or tasks on the internet, these bots can be able to perform tasks simple and repetitive even faster than the person can do.

In our reCAPTCHA article, we traced the bot activity by using Google reCAPTCHA v3. If you are interested in learning about securing unauthorized bots please visit. Bots are simply internet bots. OK now, let into the topic. This article covers configuring a bot from bot father in the telegram app. After we need to enable the bot for the needed groups or channels in a telegram that we need to send messages. Then the time to send messages and photos. We can send data via many options like text, photo, video, animation, voice and etc. Also, there are some limitations on sending data. we will discuss it all.

Why do we need bots?

Telegram is a platform that provides an API to create bots for gaming, e-commerce services, social interactions, and productivity. In addition, These bots can also provide customer support or
collect leads by connecting them to a messaging platform, CRM, or ticketing system.

4 Reasons for Businesses to Use Telegram Bot

  1. Secure – Comparing other social media platforms Telegram is quite secure in sending messages in encrypted form. So it is better to use telegram for business purposes. The bot messages seem secure to support customers.
  2. Free Platform – Telegram is a free platform without any limitations on sending messages. So that telegram bot creation
    is also free. Businesses can use this free platform to build their
    customer base by sending business messages.
  3. Availability – This is platform Independent, it is available on all major platforms such as Android, iOS,
    and Windows phones with desktop apps for Mac, Linux, and Windows. In addition, it also has a web version.
  4. Having Options – You also have an option to send audio, videos, message, media collection, documents, contact, games, location, images and etc to businesses. This increases customer engagement.

Lets Start

Here I am going to create a Bot and going to send the messages from the telegram API, then I will create the custom API by using spring boot and send messages.

Enable Bot

At the very first step go to your telegram web app or mobile app. Then search for the BotFather. BotFather is the one bot to rule them all. By using BotFather we create new bot accounts and manage your existing bots.

create bot

You may find many results for the BotFather, but choose the blue batch verified BotFather. Once you choose the BotFather, select/click “/newbot”.

messages

Once you choose the bot you have to select the new name for the bot. Here I am choosing “MinoChatBot”. Then we need to give the username for the bot, In my case “mino_chat_bot”. Once it is done you will get the token with a greeting message. Here the looking token is modified, so don’t try to use this.

telegram bot

Now the bot is ready, By using this Bot you can send messages. But before that, you need to add your bot for a particular group or channel.

Add a Bot to Telegram Group or Channel

Note: What is the difference between Group and Channel?

A Telegram channel is a medium for one-way broadcast messages, a power-charged version of the WhatsApp Broadcast list. A Telegram group is the same as another chat group where we can interact.

Add Bot to Channel

We need to add the bot to our channel as one of the administrators. So follow the steps. For this, I am using my mobile app, because telegram web does not have this feature.

  1. Go to your channel
  2. Select Administrators
  3. Choose Add Admin
  4. Search for a Bot that you created early, in my case “MinoChatBot”
  5. Once you find choose and enable needed features, here I enabled all features.
channel
telegram chat

Add Bot to Group

We need to add the bot to our group as one of the members. So
follow the steps. For this, I am using my mobile app, because telegram
web does not have this feature.

  1. Go to your group
  2. Click “Add Members”
  3. Search for a Bot that you created early, in my case “MinoChatBot”
  4. Finally, select it.
telegram chat

Make Group/Channel As Public or Private

In these steps we can modify our group as Public or Private while modifying we need to give the group name, this will be considered as chat_id on the rest API call. For my group I will keep it as a public group, you can give private also. My group Name is MinoTest1 (Chat_id). The same will be applied in Channel also.

telegram

As far as we did the configuration part. In addition, we need to create a custom API to use in our spring boot application. But for now, we can see send the message using our browser or postman. I will show you in postman.

Postman Demo 1

In this request, you need to add your token following from bot

create bot api

 

Use this curl (token, chat_id modified)

curl --location --request POST 'https://api.telegram.org/bot5532040960:AAEs1234AAl8T45Nm1234i59NwwEy6V-viM/sendMessage?chat_id=@MinoTest123&text=test message' 
--form 'photo=@"/home/mino/Pictures/Screenshot from 2022-06-10 17-53-58.png"'

Spring-boot Custom API

This step is optional, but if we need to send messages to multiple groups or channels, it is useful. So can omit this configuration.

As usual, create your spring-boot project. Then create TelegramController, TelegramService and TelegramClient. I quit the explanation of the Spring-boot application. I’ll just share the important codes. The provided credentials are modified.

Telegram Controller

package com.sample.telegramservice.controller;
import com.sample.telegramservice.service.TelegramService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/telegram")

public class TelegramController {

    @Autowired
    TelegramService telegramService;

    @PostMapping("/sendPhoto")
    public void sendPhotoToTelegramGroup(String caption, String photo) throws Exception {
        telegramService.sendPhotoToTelegramGroup(caption, photo);
    }

    @PostMapping("/sendPhoto/file")
    public void sendPhotoFileToTelegramGroup(@RequestParam("caption") String caption, @RequestPart("photo") MultipartFile photo) throws Exception {
        telegramService.sendPhotoFileToTelegramGroup(caption, photo);
    }

    @PostMapping("/sendMessage")
     public void sendMessageToTelegramGroup(@RequestParam("message") String message) throws Exception {
         telegramService.sendMessageToTelegramGroup(message);
     }
}

Telegram Service

package com.sample.telegramservice.service;
import com.sample.telegramservice.client.TelegramClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;

@Service
public class TelegramService {

    @Autowired
    TelegramClient telegramClient;

    public void sendPhotoToTelegramGroup(String caption, String photo) throws Exception {
        List chatIdList = new ArrayList();
        chatIdList.add("@MinoTest1");
        chatIdList.add("@minoTestChannel");
        
        for(String chatId: chatIdList){
            telegramClient.sendPhoto(chatId,caption, photo);
        }
   }

    public void sendPhotoFileToTelegramGroup(String caption, MultipartFile photo) throws Exception {
        List chatIdList = new ArrayList();
        chatIdList.add("@MinoTest1");
        chatIdList.add("@minoTestChannel");
        for(String chatId: chatIdList){
            telegramClient.sendPhotoFile(chatId,caption, photo);
        }
   }
 
    public void sendMessageToTelegramGroup(String message) throws Exception {
        List chatIdList = new ArrayList();
        chatIdList.add("@MinoTest1");
        chatIdList.add("@minoTestChannel");
        for(String chatId: chatIdList){
            telegramClient.sendMessage(message, chatId);
        }
    }    
}

TelegramClient

package com.sample.telegramservice.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;

@Service
public class TelegramClient {

    private String token = "5123456960:AAEs0C6f12345ABcdeFSCki52Mwery6V-viM";
    private String telegramBaseUrl = "https://api.telegram.org/bot";
    private String apiUrl = telegramBaseUrl+token;
    
    private final RestTemplate restTemplate;
    private static final Logger logger = LoggerFactory.getLogger(GoogleRecaptchaClient.class);

    @Autowired
    public TelegramClient(RestTemplate restTemplate) {
        this.restTemplate  = restTemplate;
    }
 
public void sendMessage(String message, String chatID) throws Exception {
    try {
        RestTemplate restTemplate = new RestTemplate();
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl+"/sendMessage")
                .queryParam("chat_id", chatID)
                .queryParam("text", message);
        ResponseEntity exchange = restTemplate.exchange(builder.toUriString().replaceAll("%20", " "), HttpMethod.GET, null, String.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        logger.error("Error response : State code: {}, response: {} ", e.getStatusCode(), e.getResponseBodyAsString());
        throw e;
    } catch (Exception err) {
        logger.error("Error: {} ", err.getMessage());
        throw new Exception("This service is not available at the moment!");
    }
}

public void sendPhotoFile(String chatID, String caption, MultipartFile photo) throws Exception {
    try {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap body = new LinkedMultiValueMap();
        ByteArrayResource fileAsResource = new ByteArrayResource(photo.getBytes()){
            @Override
            public String getFilename(){
                return photo.getOriginalFilename();
            }
        };
        body.add("Content-Type", "image/png");
        body.add("photo", fileAsResource);
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity(body, headers);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl+"/sendPhoto")
                .queryParam("chat_id", chatID)
                .queryParam("caption", caption);
        System.out.println(requestEntity);
        String exchange = restTemplate.postForObject(
                builder.toUriString().replaceAll("%20", " "),
                requestEntity,
                String.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        logger.error("Error response : State code: {}, response: {} ", e.getStatusCode(), e.getResponseBodyAsString());
        throw e;
    } catch (Exception err) {
        logger.error("Error: {} ", err.getMessage());
        throw new Exception("This service is not available at the moment!");
    }
}

public void sendPhoto(String chatID, String caption, String photo) throws Exception {
        try {
            RestTemplate restTemplate = new RestTemplate();
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl+"/sendPhoto")
                    .queryParam("chat_id", chatID)
                    .queryParam("photo", photo)
                    .queryParam("caption", caption);
            String exchange = restTemplate.postForObject(
                    builder.toUriString().replaceAll("%20", " "),
                    null,
                    String.class);
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            logger.error("Error response : State code: {}, response: {} ", e.getStatusCode(), e.getResponseBodyAsString());
            throw e;
        } catch (Exception err) {
            logger.error("Error: {} ", err.getMessage());
            throw new Exception("This service is not available at the moment!");
        }
    }    
}

Postman Demo 2

This demo is used to call our custom API. Use my following curl requests.

sendMessage

curl --location --request POST 'localhost:8080/telegram/sendMessage?message=message From custom API For Multiple groups' 
--data-raw ''

sendPhoto

curl --location --request POST 'localhost:8080/telegram/sendPhoto?message=message From custom API For Multiple groups&photo=url'

sendPhotoFile

curl --location --request POST 'localhost:8080/telegram/sendPhoto/file?caption=File Caption' 
--form 'photo=@"/home/mino/Pictures/Screenshot from 2022-03-11 09-54-02.png"'

Telegram API List

Use this link to find more APIs that can use by telegram bots.

Conclusion

Sounds cool right? Now you got to know how the messages are coming to our groups and channels in telegram. These Telegram bots are providing many services like supporting customers, selling goods and services, handling payment services and etc. In this article, we followed the basic building block of the bot of initial configurations.

Also, For enterprise-level applications, it is better to configure all APIs in some modules. To achieve this I just demonstrate with the Spring-boot application. You can use any kind of framework to call telegram API. The Future business moving with these Bots. So learning about bots is adding more value to you and your business. As I said before, here I only covered sending messages from the telegram bot. In coming articles, we can see how to send Photos, Files, Documents, Games, Videos, and Payment Invoices.

Key takeaways

  1. We Learned, What are bots and why we need that.
  2. Configuring bots in our telegram groups and channels.
  3. Also, you can send messages to Groups and channels via telegram API.
  4. Found a better approach to handle telegram APIs by using spring-boot custom APIs.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Paul Issack 12 Jul 2022

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

  • [tta_listen_btn class="listen"]