Thu. Nov 26th, 2020

Hello friends,in this post I will explain you How you can create telegram bot using java?

Get API Token

So first Go to the telegram and search Bot Father.

Bot father is used to create bot,manage existing bots,changes settings and delete bot.

You have to enter the of your bot, and it’s always unique. after creating bot you will get API Token (Do not share this with anyone).

Create a Java Maven Project.

Open your IDE and create a java Maven project.

in the pom.xml add java-telegram-bot-api dependency.

Now create a MainClass and inside main() method write following code to create an object of your MyBot class and register it and then create a MyBot.Java

MyBot class will extend TelegramLongPollingBot .

Now you have to implements methods

    @Override
    public void onUpdateReceived(Update update) {    

    }

    @Override
    public String getBotUsername() {
        return null;
    }

    @Override
    public String getBotToken() {
        return null;
    }

Add token and username

Inside getBotUserName( ) replace null with the name of your Bot and paste your token in the return statement of getBotToken( ).

Get message from the Bot

When user send message to bot ,it will receive in the onUpdateReceived( ) ,

to print the message on console you can write following code

System.out.println(update.getMessage().getText()); 

How to send Message to user ?

Create a object of SendMessage

SendMessage sendMessage = new SendMessage();
        sendMessage.setText("Hii ") 
        try {
         sendMessage.setChatId(update.getMessage().getChatId());    
         execute(sendMessage);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }

inside the setText( ), you can write your message. and set Chat ID using setChatID()

execute() will send Message to the user,don’t forget to write this code inside try-catch block ,because it may throw exception.

Array Index Out Of Bound Bot

I have created a telegram bot, which will show you live CORONA global data, bot send you coding jokes and FREE resources to learn programming languages, web development, android development, ethical hacking and much more.

You can use my Bot Click here

Source Code of this bot is available on my GitHub repo you can download it and use,just change your API TOKEN.

https://github.com/viralvaghela/Telegram-Bot-Array-Index-Out-Of-Bound

If you have any question Feel free to ask in the comment, and follow me on Instagram for daily amazing posts on coding ,app development and backend dev.

https://instagram.com/coding_boy_

Leave a Reply

Your email address will not be published. Required fields are marked *