sendMessages

Introduction

Welcome to the first lesson! In this lesson, we will learn how to send messages and make a simple echo bot.

In this tutorial I will use next characteristics:

  • My home macOS laptop with IntelliJ Idea pre-installed

  • Java JDK 18

Preparation

To begin with, for the purity of the code, I recommend making a separate class where we will insert all the data received from the BotFather

If you don't know what it is, go back to lesson 0

public class Bot {

    // Put your data
    public static final String TOKEN = "YOUR_TOKEN_HERE";
    public static final String USERNAME = "YOUR_USERNAME_HERE";
}

Next, let's connect all the necessary libraries that will be needed when creating a bot.

As for the maven, you should go to this repository and add maven dependency.

You can also copy from here:

Also in the future we will need methods from Java Spring, so we will also connect the library

You can also copy from here:

To add a dependency, you need to go into the project structure, then the libraries, click plus and insert the maven dependency

Process

After we have connected all the necessary dependencies, we can proceed with the code.

First, let's create the main class.

new HandlerToLessonOne() is our class, so there is no need to import the proposed library

This completes the main function, let's start creating an update handler.

After creating the class HandlerToLessonOne, we need to extend TelegramLongPollingBot and then Override methods offered by it.

You should get this code

Then we need to replace the null values with the values that we had in the Bot class

Something like this

We just need to Override the onUpdateReceived method and the echo bot will be ready.

The sent message must contain chat id and the message itself!

After that, our bot is ready to work and will return the message you wrote!

Show Work

Back to Lesson 0 of creating a bot in BotFather Go to Lesson 2 of making buttons in the keyboard field

Last updated