Chat Games Setup

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

Let's make group chat games! To distinguish each group we use the update.getMessage().getChatId() function since each chat has a unique id. So let's start off with the basics: We need an object to hold data about the progress of the current game, and each chat must have its own object. We will accomplish this with a HashMap which will link each chat ID to a game object:

// to play separate games on separate groups
private static HashMap<Long, Game> games = new HashMap<>();

Create a new file in your src directory named GameHandler.java to keep the bot class clean. We are going to create a static class Game in GameHandler.java which will hold all games being played and their progress:

private static class Game {
    // for upcoming tutorial
    // private ImageGuess guessGame = null;
}

GameHandler will have a static check function that will be called from the KodeCentralBot onUpdateReceived function. Check function:

public static void check(KodeCentralBot kodeCentralBot, Update update) {
    Game current = null;
    long chat_id = update.getMessage().getChatId();
    if (games.containsKey(chat_id))
        current = games.get(chat_id);
    // check what game, etc.. (future)
}

That's all the new code for now.


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);

            // echo bot: the bot response is the same as the incoming update message text
            log(username, Long.toString(user_id), message_text, message_text);

            // NEW:
            GameHandler.check(this, update);
            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";
    }
}


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

import java.util.HashMap;

public class GameHandler {

    private static class Game {

        // for upcoming tutorial
        //private ImageGuess guessGame = null;
    }

    // to play separate games on separate groups
    private static HashMap<Long, Game> games = new HashMap<>();

    public static void check(KodeCentralBot kodeCentralBot, Update update) {
        Game current = null;
        long chat_id = update.getMessage().getChatId();
        if (games.containsKey(chat_id))
            current = games.get(chat_id);

        // check what game, etc.. (future)
    }
}

And that's it for the setup! We will use this code for all future games!

Comments (0)

Search Here