CodeGym /Java Blog /Java Marathon (Chatbot-game) /Java Marathon Class Outlines
Level 41

Java Marathon Class Outlines

Published in the Java Marathon (Chatbot-game) group
Here you will find tips and “cheatsheets” for the material covered during classes. They will be helpful for successfully completing homework assignments. Remember: you can always review the videos, read the class outlines, or ask your questions to the community and mentor in the special Telegram chat. Good luck!

Class Outline #1

In this session, we have familiarized ourselves with the structure of our project in IntelliJ IDEA, learned how to register a bot on Telegram, and how to write the first message for the user in it.

Basic Principles of Writing Commands

First Principle: In Java, it's customary to write each command on a new line. At the end of the command, a semicolon is placed:

System.out.println("Hello, future programmer");
Second Principle: A program can't just consist of commands. Java commands should be inside methods, and methods should be inside classes. The general hierarchy can be described as follows: Java programs consist of classes, classes contain methods, and methods contain commands.

Theses for the First Session

  • Launch IntelliJ IDEA and open the downloaded project.
  • 'src' in the left column is the source folder. src → main → java is the path to the code we will work with.
  • Utility methods are auxiliary methods, usually static, which belong to the class rather than an object.
  • Class inheritance is a form of relationship between classes. A subclass utilizes methods of the superclass, but not vice versa.
In our case, we utilize class inheritance from the TelegramLongPollingBot class. It provides a set of methods necessary to connect and work with the Telegram bot we will create together. To enable the program to interact with our bot, we need to specify:
  • getBotUsername (bot's name)
  • getBotToken (bot's token)

Getting the Bot's Name and Token, Bot Registration

Open Telegram and search for BotFather. In the dialogue with BotFather, type: /newbot — a command to create a new bot. After creation, choose a unique username for the bot — it must end with _bot.

Utility Methods We Will Use

Just a reminder, utility methods are ready-made methods written by other programmers that help us write our program code. onUpdateReceived: This method will handle all messages entered by users of our bot. We will receive them and write the logic according to our needs. createMessage: This method is for creating a message. The first parameter it takes is the chatId — the identifier of the chat initiated by the user. The second parameter takes the value of the message that will be displayed to the user. In our case, it's 'Hello, future programmer!'. sendApiMethodAsync: This method is for sending a message asynchronously.

Assignment #1

  1. Download the project in IntelliJ IDEA.
  2. Create and register our bot on Telegram.
  3. Write the first message in the bot for the user.

Hints for Completing Assignment #1

Checking the correctness of the code and updating changes in the project

To see the changes you make directly in the Telegram bot's operation, don't forget after you write your code, apply all changes (restart the project) in IntelliJ IDEA. To do this, in the bottom horizontal panel, click on the green circular arrow. Java Marathon Class Outlines - 1

Important Principles of Code Formatting

  • Don't forget to put a semicolon ';' at the end of each command you create.
  • Each opening parenthesis '(' or brace '{', or quotation mark '"', should have a corresponding closing parenthesis ')', brace '}', or quotation mark '"'.
  • If your code is highlighted in red, it means there's an error — take a closer look.
  • Use automatic prompts and auto-completion — it will help you write code correctly.
  • Remember that your variable, method, and class names should be readable, meaning it should be clear from the name what they do or what they're intended for.

Class Outline #2

During this session, we learned how to format the text of the bot's response and started working on expanding the functionality to handle additional messages. This will help us analyze user requests and provide appropriate responses.

Text Formatting

To emphasize text in italics, you need to add underscores at the beginning and end of the desired fragment: _text_ To highlight text in bold, you need to add asterisks at the beginning and end of the desired fragment: *text*

Methods and Operators We Will Use

  • if: Conditional operator in Java.
  • update.hasMessage(): Method used to check if we have a new message at all.
  • equals: Method that compares the content of a message with specific text. For the condition to be true, the content must be completely identical (what is passed to the equals method must match word for word in the query/message).
  • contains: Method that checks if a message contains a certain word/phrase. In our case, "hello".

The Conditional if Statement

The if statement is the primary selection statement in Java, allowing for selectively altering the flow of program execution. It begins with the keyword if. The if keyword is followed by a Boolean (logical) expression within parentheses. The simplest form looks like this:

if (condition) statement;  // if condition is true, execute statement
The if statement is followed by a block of statements enclosed in curly braces {}{block of statements}. Important: In our case, we are using two conditional operators: don't forget about the && operator — AND, our additional condition with fame points counting.

Assignment #2

Complete the dialogue. After the message 'hello, what's your name?' if the user sends a message: 'my name is [your name]' (i.e., a message containing the phrase 'my name is'). In response, we should send the user: 'Nice to meet you, I'm Cat', where Cat is in bold.

Hints for Completing Assignment #2

Each opening parenthesis '(' or brace '{', or quotation mark '"', should have a corresponding closing parenthesis ')', brace '}', or quotation mark '"'. Pay attention and don't mix up these pairs of symbols when writing the code to handle messages in the bot: Java Marathon Class Outlines - 2

Class Outline #3

During this session, we learned how to send messages using buttons. After this, you will be able to independently add dialogue with the Cat in your chatbot game.

Adding Buttons to the Bot

The text with hints that should be written on the buttons in your chatbot game is already prepared. You can find it in the project folder — in the file buttons.txt: Java Marathon Class Outlines - 3
  • getCallbackQuery: The method we use to check if any of the buttons have been pressed.
  • Map.of(): A map with the values of buttons displayed to the user along with a specific message.
  • k (key): The value of the button.
  • v (value): The identifier of the button (for convenience (readability), we use the step number we are currently at in the chatbot game).

Testing All Changes in the Program

Make all changes step by step. Edit one part of the code — apply these changes (green arrow in the bottom horizontal panel), and make sure your program works: check how everything looks in the Telegram bot after your actions in the code editor.

Assignment #3

  1. Complete the dialogue with the Cat using the text for steps from the TelegramBotContent class.
  2. Use the button texts contained in the buttons.txt file.

Hint for Completing Assignment #3

Note: Starting from the second step, we check not only if a button was pressed, but also the AMOUNT OF FAME the Cat has at that moment. Initially, it is 0. With each step, the Cat receives an additional amount of fame (+20, 30…). The amount of fame is an important condition that helps us create the correct sequence of actions in the chatbot game — without repeating steps. Important! On the last step, it's also necessary to add addGlories, otherwise, we can press the last button 'Go to the yard' endlessly, and the message in the chatbot game will be duplicated.

Class Outline #4

In the final stage, we will be adding images to our responses for the user, making it more engaging. Additionally, we will engage in code refactoring!

Adding Images to Messages in the Bot

All the images you need are located in the images folder: Java Marathon Class Outlines - 4createPhotoMessage: The method we need for adding images. It takes 2 parameters:
  • chatId (user identifier)
  • name: the name of the image we want to use
executeAsync: method for sending the object (image) to the user.

Code Refactoring of Your Program

Refactoring is the process of changing the internal structure of a program without altering its external behavior. Essentially, it's simplifying and improving existing code to make it more compact and understandable, increase performance, and avoid future errors in the code. Your task is to write a universal method sendMessage(), which will send messages to the user. Since our messages have constant components, it will be convenient to have such a template. Some important definitions from the lesson:
  • private: indicates a private method, used only in our class
  • void: indicates that the method doesn't return anything
sendMessage(): the name of your method, which sends messages to the user. In the parentheses (), you need to specify all the parameters we need to implement the correct logic for the user.

Saving the Result to a Variable

Here's a brief explanation of how to save the result to a variable, as the mentor demonstrated in the class: Java Marathon Class Outlines - 5Here are two ways to do it:
  • After typing the command, for example, createMessage(chatId, text, buttons), press ctrl+alt+v (Windows).
  • After typing the command, for example, createMessage(chatId, text, buttons), type ".var" (without quotes) and press Enter.
  • Then you will be prompted to enter the name of the variable to which you want to save the result of the command.

Assignment #4

Refactor the code using the private method sendMessage for all steps of the bot game:
  • Repeat the code refactoring from the lesson.
  • Independently refactor the code for steps 6-8.