Logging

... by Bittle in Java Telegram Bot April 12, 2019

How about printing something instead of seeing an empty console? I got you! We need the code from the previous example to start off:


KodeCentralBot.java
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

public class KodeCentralBot extends TelegramLongPollingBot {
    @Override
    public void onUpdateReceived(Update update) {

        // We check if the update has a message and the message has text
        if (update.hasMessage() && update.getMessage().hasText()) {
            // Set variables
            String message_text = update.getMessage().getText();

            // id from sent message (will use to send back the message)
            long chat_id = update.getMessage().getChatId();

            SendMessage message = new SendMessage() // Create a message object
                    .setChatId(chat_id)
                    .setText(message_text);
            try {
                execute(message); // Sending our message object to user
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getBotUsername() {
        // Return bot username
        // If bot username is @KodeCentralBot, it must return 'KodeCentralBot'
        return "KodeCentralBot";
    }

    @Override
    public String getBotToken() {
        // Return bot token from BotFather
        return "token";
    }
}


Main.java
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

public class Main {
    public static void main(String[] args) {
        // Initialize Api Context
        ApiContextInitializer.init();

        // Instantiate Telegram Bots API
        TelegramBotsApi botsApi = new TelegramBotsApi();

        // Register our bot
        try {
            botsApi.registerBot(new KodeCentralBot());
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}


Logging

So now we want to be notified of every update and the response (if any), correct? Let's first retrieve additional variables from the update object for better logging.

String username = update.getMessage().getChat().getUserName();
long user_id = update.getMessage().getChat().getId();
String message_text = update.getMessage().getText();

Now lets create a function that will output the following:

  1. Time received
  2. Message text
  3. Sender id

The function receives the important information through parameters and outputs to the console:

private void log(String username, String chatId, String textReceived, String botResponse) {
    System.out.println("----------------------------\n");
    // print out in PM/AM time
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd h:mm a");
    Date date = new Date();
    System.out.println(dateFormat.format(date));
    System.out.println("Message from " + username + ". (id = " + chatId + ") \n Text - " + textReceived);
    System.out.println("Bot answer: \n Text - " + botResponse);
}


Call this function whenever you need nice logging! Viola!


KodeCentralBot.java
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class KodeCentralBot extends TelegramLongPollingBot {
    @Override
    public void onUpdateReceived(Update update) {

        // We check if the update has a message and the message has text
        if (update.hasMessage() && update.getMessage().hasText()) {

            // get the username, id, and the message text
            String username = update.getMessage().getChat().getUserName();
            long user_id = update.getMessage().getChat().getId();
            String message_text = update.getMessage().getText();
            long chat_id = update.getMessage().getChatId();

            SendMessage message = new SendMessage() // Create a message object object
                    .setChatId(chat_id)
                    .setText(message_text);

            // since just echo bot, the bot response is the same as the incoming update message text
            log(username, Long.toString(user_id), message_text, message_text);
            try {
                execute(message); // Sending our message object to user
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
    }

    private void log(String username, String chatId, String textReceived, String botResponse) {
        System.out.println("----------------------------\n");
        // print out in PM/AM time
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd h:mm a");
        Date date = new Date();
        System.out.println(dateFormat.format(date));
        System.out.println("Message from " + username + ". (id = " + chatId + ") \n Text - " + textReceived);
        System.out.println("Bot answer: \n Text - " + botResponse);
    }

    @Override
    public String getBotUsername() {
        // Return bot username
        // If bot username is @KodeCentralBot, it must return 'KodeCentralBot'
        return "KodeCentralBot";
    }

    @Override
    public String getBotToken() {
        // Return bot token from BotFather
        return "token";
    }
}


Output

Comments (0)

Search Here