Zephyrnet Logo

Sending Telegram Messages made Easier with Telegram Bot

Date:

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.

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/[email protected]&text=test message' 
--form '[email protected]"/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!");
        }
    }    
}
spot_img

Latest Intelligence

spot_img