Sunday, September 24, 2023

How To Make A telegram Blot using SpringBoot (java)

 To Make a Telegram Bot ,first you have to create a bot in telegram,type BotFather in telegram search 

type /newbot in the telegram (like there in pic)

Here, I gave bot name as (satishbot),has shown in the pic.



we will get the token,like there in above pic ,In the above pic you can see(Use this token HTTP API),there at the botton ,you will see the token.This is all you have to do with telegram App

With the use of Spring Iniatializer create a SpringBoot project


  

The above pic is the package structure of a chatbot application using Eclipse IDE.


The above pic shows classes in the package.I will give the code below of each class in the package

ChatbotApplication main class

Here we have  to register out bot class with telegram

package com.example.chatbot.chatbot;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.telegram.telegrambots.meta.TelegramBotsApi;

import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import org.telegram.telegrambots.meta.generics.BotSession;

import org.telegram.telegrambots.meta.generics.LongPollingBot;

import org.telegram.telegrambots.meta.generics.TelegramBot;

//import org.telegram.telegrambots.meta.TelegramBotsApi;

//import org.telegram.telegrambots.meta.TelegramBotsApi;

/*import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import org.telegram.telegrambots.meta.generics.BotSession;

import org.telegram.telegrambots.meta.generics.LongPollingBot;

import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;*/

import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;


import com.example.chatbot.config.TelegramBotConfig;


//import com.pengrad.telegrambot.TelegramBot;


@SpringBootApplication(scanBasePackages={ "com.example.chatbot.config"})

public class ChatbotApplication {


public static void main(String[] args) {

SpringApplication.run(ChatbotApplication.class, args);

///TelegramBot telegramBot = new TelegramBot();

//TelegramBot telegramBot = new TelegramBot();

    try {

        TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);

        botsApi.registerBot(new TelegramBotConfig());

        System.out.println("bot registered successfully");

    } catch (TelegramApiException e) {

        e.printStackTrace();

    }

}


}

TelegramBotConfig :: class code 

package com.example.chatbot.config;

import com.example.chatbot.UserState.UserStateEnum;

import com.pengrad.telegrambot.TelegramBot;

//import com.pengrad.telegrambot.request.SendMessage;


import java.util.HashMap;

import java.util.Map;


//import com.pengrad.telegrambot.TelegramBotAdapter;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.stereotype.Component;

import org.telegram.telegrambots.bots.DefaultAbsSender;

import org.telegram.telegrambots.bots.TelegramLongPollingBot;

import org.telegram.telegrambots.meta.api.methods.send.SendMessage;

import org.telegram.telegrambots.meta.api.objects.Message;

import org.telegram.telegrambots.meta.api.objects.Update;

import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard;

import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardRemove;

import org.telegram.telegrambots.meta.bots.AbsSender;

import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import static  com.example.chatbot.UserState.UserStateEnum.AWAITING_NAME;

import com.example.chatbot.KeyBoardFac.*;

import static com.example.chatbot.UserState.UserStateEnum.FOOD_DRINK_SELECTION;

import static com.example.chatbot.UserState.UserStateEnum.AWAITING_CONFIRMATION;

import static com.example.chatbot.UserState.UserStateEnum.PIZZA_TOPPINGS;


@Component

public class TelegramBotConfig extends TelegramLongPollingBot  {

private final HashMap<Long, UserStateEnum> chatStates =new HashMap<>();

 

@Override

public void onUpdateReceived(Update update) {

String userMessage=update.getMessage().getText();

Long chatId=update.getMessage().getChatId();

SendMessage message = new SendMessage();

   if(userMessage.equalsIgnoreCase("/start")) {

   replyToStart(chatId);

   

  }

  

   if(!userMessage.equalsIgnoreCase("/start")) {

  switch (chatStates.get(chatId)) { case AWAITING_NAME ->

  replyToName(chatId, update); case FOOD_DRINK_SELECTION ->

replyToFoodDrinkSelection(chatId, update);

case PIZZA_TOPPINGS -> 

  replyToPizzaToppings(chatId, update); case AWAITING_CONFIRMATION ->

  replyToOrder(chatId, update); default -> unexpectedMessage(chatId); }

   }

   }

   

@Override

public String getBotUsername() {

return "satred35bot";

}



  @Override public String getBotToken() { return "6467366090:AAE-1eCSTPVhbeu0O0VlqYjODeaOu8_jHWE"; }

 


public void replyToStart(Long chatId) {

try {

SendMessage message=    new SendMessage();

message.setChatId(chatId.toString());

message.setText("Welcome to satishbot ,please enter your name");

execute(message);

chatStates.put(chatId,AWAITING_NAME ); 

}catch (TelegramApiException e) {

        e.printStackTrace();

    }

    

}

private void unexpectedMessage(Long chatId) {

    SendMessage sendMessage = new SendMessage();

    sendMessage.setChatId(chatId.toString());

    sendMessage.setText("I did not expect that.");

    try {

execute(sendMessage);

} catch (TelegramApiException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

private void replyToName(Long chatId, Update message) {

    promptWithKeyboardForState(chatId, "Hello " + message.getMessage().getText() + ". What would you like to have?",

      KeyboardFactory.getPizzaOrDrinkKeyboard(),

     FOOD_DRINK_SELECTION);

}

private void promptWithKeyboardForState(Long chatId, String text, ReplyKeyboard YesOrNo, UserStateEnum awaitingReorder) {

    SendMessage sendMessage = new SendMessage();

    sendMessage.setChatId(chatId.toString());

    sendMessage.setText(text);

    sendMessage.setReplyMarkup(YesOrNo);

   try {

execute(sendMessage);

} catch (TelegramApiException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


  chatStates.put(chatId, awaitingReorder);

 }

private void replyToPizzaToppings(Long chatId, Update message) {

    if ("margherita".equalsIgnoreCase(message.getMessage().getText())) {

        promptWithKeyboardForState(chatId, "You selected Margherita Pizza.\nWe will deliver it soon. Thank you!\nOrder again?",

                KeyboardFactory.getYesOrNo(), AWAITING_CONFIRMATION);

    } else if ("pepperoni".equalsIgnoreCase(message.getMessage().getText())) {

        promptWithKeyboardForState(chatId, "We finished the Pepperoni Pizza.\nSelect another Topping",

                KeyboardFactory.getPizzaToppingsKeyboard(), PIZZA_TOPPINGS);

    } else {

        SendMessage sendMessage = new SendMessage();

        sendMessage.setChatId(chatId.toString());

        sendMessage.setText("We don't sell " + message.getMessage().getText() + " Pizza.\nSelect the toppings!");

        sendMessage.setReplyMarkup(KeyboardFactory.getPizzaToppingsKeyboard());

        try {

execute(sendMessage);

} catch (TelegramApiException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    }

}

private void replyToFoodDrinkSelection(Long chatId, Update message) {

    SendMessage sendMessage = new SendMessage();

    sendMessage.setChatId(chatId.toString());

    if ("drink".equalsIgnoreCase(message.getMessage().getText())) {

        sendMessage.setText("We don't sell drinks.\nBring your own drink!! :)");

        sendMessage.setReplyMarkup(KeyboardFactory.getPizzaOrDrinkKeyboard());

       try {

execute(sendMessage);

} catch (TelegramApiException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    } else if ("pizza".equalsIgnoreCase(message.getMessage().getText())) {

        sendMessage.setText("We love Pizza in here.\nSelect the toppings!");

        sendMessage.setReplyMarkup(KeyboardFactory.getPizzaToppingsKeyboard());

        try {

execute(sendMessage);

} catch (TelegramApiException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

chatStates.put(chatId, PIZZA_TOPPINGS); 

    } else {

        sendMessage.setText("We don't sell " + message.getMessage().getText() + ". Please select from the options below.");

        sendMessage.setReplyMarkup(KeyboardFactory.getPizzaOrDrinkKeyboard());

       try {

execute(sendMessage);

} catch (TelegramApiException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    }

}

private void replyToOrder(Long chatId, Update message) {

    SendMessage sendMessage = new SendMessage();

    sendMessage.setChatId(chatId.toString());

    if ("yes".equalsIgnoreCase(message.getMessage().getText())) {

        sendMessage.setText("We will deliver it soon. Thank you!\nOrder another?");

        sendMessage.setReplyMarkup(KeyboardFactory.getPizzaOrDrinkKeyboard());

       try {

execute(sendMessage);

} catch (TelegramApiException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

chatStates.put(chatId, FOOD_DRINK_SELECTION); 

    } else if ("no".equalsIgnoreCase(message.getMessage().getText())) {

        stopChat(chatId);

    } else {

        sendMessage.setText("Please select yes or no");

        sendMessage.setReplyMarkup(KeyboardFactory.getYesOrNo());

       try {

execute(sendMessage);

} catch (TelegramApiException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    }

}

private void stopChat(Long chatId) {

    SendMessage sendMessage = new SendMessage();

    sendMessage.setChatId(chatId.toString());

    sendMessage.setText("Thank you for your order. See you soon!\nPress /start to order again");

chatStates.remove(chatId); 

    sendMessage.setReplyMarkup(new ReplyKeyboardRemove(true));

   try {

execute(sendMessage);

} catch (TelegramApiException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}



}


class KeyboardFactory code::::


package com.example.chatbot.KeyBoardFac;


import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboard;

import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;

import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;


import java.util.List;


public class KeyboardFactory {

public static ReplyKeyboard getPizzaToppingsKeyboard() {

KeyboardRow row = new KeyboardRow();

row.add("Margherita");

row.add("Pepperoni");

return new ReplyKeyboardMarkup(List.of(row));

}


public static ReplyKeyboard getPizzaOrDrinkKeyboard(){

KeyboardRow row = new KeyboardRow();

row.add("Pizza");

row.add("Drink");

return new ReplyKeyboardMarkup(List.of(row));

}


public static ReplyKeyboard getYesOrNo() {

KeyboardRow row = new KeyboardRow();

row.add("Yes");

row.add("No");

return new ReplyKeyboardMarkup(List.of(row));

}

}




Enum UserStateEnum





package com.example.chatbot.UserState;


public enum UserStateEnum {

AWAITING_NAME, FOOD_DRINK_SELECTION, PIZZA_TOPPINGS, AWAITING_CONFIRMATION

}





OUTPUT WILL BE LIKE 






No comments:

Post a Comment