Telegram机器人仅在我发送聊天内容后才发送照片

时间:2018-11-08 11:52:39

标签: java telegram-bot

有一个机器人可以从网站上拍摄顶级电影图片并将其发送到聊天室。问题在于它仅在您输入任何消息时才发送它们,并且通过一遍又一遍地发送消息,机器人从头开始相应地开始发送消息。我试图将发送发送到一个单独的线程中,但是没有用(也许我做错了)。总体而言,我需要该机器人每30分钟发送一次阵列中的照片图像。

负责创建图像链接数组的类:

    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;

    public class NewFilms {
        private static ArrayList<String> absoluteUrls = new ArrayList<>();

        public NewFilms() throws IOException {
            createArrayOfImages();
        }

        private static void  createArrayOfImages() throws IOException {
            Document document = Jsoup.connect("http://gidonline.in/").get();
            List<Element> imageElements = document.select("img[src$=120x170.jpg]");
            for (Element element : imageElements) {
                absoluteUrls.add(element.absUrl("src"));
            }
        }

        public static ArrayList<String> getAbsoluteUrls() {
            return absoluteUrls;
        }
    }

我的机器人班:

import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendPhoto;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.PhotoSize;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardRemove;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Bot extends TelegramLongPollingBot {
    public static void main(String[] args) throws IOException {
        ApiContextInitializer.init();
        TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
        try {
            telegramBotsApi.registerBot(new Bot());
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
        System.out.println("TelegramBot successfully started!");

    }

    private void sendMsg(Message message, String text) {
        SendMessage sendMessage = new SendMessage()
                .setChatId(message.getChatId().toString())
                .setText(text);
        try {
            setButtons(sendMessage);
            execute(sendMessage);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

    private void sendPhotoMsg(Message message) {
        List<PhotoSize> photos = message.getPhoto();
        String f_ID = photos.stream()
                .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
                .findFirst()
                .orElse(null).getFileId();
        int f_WIDTH = photos.stream()
                .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
                .findFirst()
                .orElse(null).getWidth();
        int f_HEIGHT = photos.stream()
                .sorted(Comparator.comparing(PhotoSize::getHeight).reversed())
                .findFirst()
                .orElse(null).getHeight();
        // set photo caption
        String caption = "file_id " + f_ID + "\nwidth: " + f_WIDTH + "\nheight: " + f_HEIGHT;

        SendPhoto msg = new SendPhoto()
                .setChatId(message.getChatId())
                .setPhoto(f_ID)
                .setCaption(caption);
        try {
            execute(msg);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

    public void onUpdateReceived(Update update) {
        class FiveMinutes extends Thread {
            @Override
            public void run() {
                try {
                    sendEveryFiveMin();
                } catch (IOException | TelegramApiException | InterruptedException e) {
                    e.printStackTrace();
                }
            }

            private void sendEveryFiveMin() throws IOException, TelegramApiException, InterruptedException {
                new NewFilms();
                for (String imagesLink : NewFilms.getAbsoluteUrls()) {
                    SendPhoto msgs = new SendPhoto()
                            .setPhoto(imagesLink)
                            .setChatId(update.getMessage().getChatId().toString());
                    try {
                        execute(msgs);
                    } catch (TelegramApiException e) {
                        e.printStackTrace();
                    }
                    Thread.sleep(3000);
                }
            }
        }

        Model model = new Model();
        Message message = update.getMessage();

        FiveMinutes newThread = new FiveMinutes(); //вот он тот самый поток:)
        newThread.start();

        if (message != null && message.hasText()) {
            switch (message.getText()) {
                case "/help":
                    sendMsg(message, "Чем могу помочь?");
                    break;
                case "/settings":
                    sendMsg(message, "Что будем настраивать?");
                    break;
                case "/hide":
                    SendMessage sendMessage = new SendMessage()
                            .setText("Клавиатура спрячена.")
                            .setChatId(message.getChatId());
                    ReplyKeyboardRemove replyKeyboardRemove = new ReplyKeyboardRemove();
                    sendMessage.setReplyMarkup(replyKeyboardRemove);
                    try {
                        execute(sendMessage);
                    } catch (TelegramApiException e) {
                        e.printStackTrace();
                    }
                    break;
                case "/back":
                    SendMessage sendMessage1 = new SendMessage()
                            .setText("Клавиатура возвращена.")
                            .setChatId(message.getChatId());
                    ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
                    sendMessage1.setReplyMarkup(replyKeyboardMarkup);
                    try {
                        setButtons(sendMessage1);
                        execute(sendMessage1);
                    } catch (TelegramApiException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    Pattern pattern = Pattern.compile("^@.+$");
                    Matcher matcher = pattern.matcher(message.getText());
                    if (matcher.matches()) {
                        try {
                            sendMsg(message, Weather.getWeather(message.getText().substring(1, message.getText().length()), model));
                        } catch (IOException e) {
                            sendMsg(message, "Такой город не найден!");
                        }
                    } else {
                        Pattern pattern1 = Pattern.compile("^.+$");
                        Matcher matcher1 = pattern.matcher(message.getText());
                        SendMessage backMessage = new SendMessage()
                                .setChatId(message.getChatId().toString())
                                .setText(new StringBuilder(message.getText()).reverse().toString());
                        //backMessage.setReplyToMessageId(message.getMessageId());
                        try{
                            execute(backMessage);
                        } catch (TelegramApiException e) {
                            e.printStackTrace();
                        }
                    }
            }
        }
        else if (update.hasMessage() && update.getMessage().hasPhoto()) {
            assert message != null;
            sendPhotoMsg(message);
        }
    }

    public void setButtons(SendMessage sendMessage) {
        ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
        sendMessage.setReplyMarkup(replyKeyboardMarkup);
        replyKeyboardMarkup.setSelective(true);
        replyKeyboardMarkup.setResizeKeyboard(true);
        replyKeyboardMarkup.setOneTimeKeyboard(false);

        List<KeyboardRow> keyboardRowList = new ArrayList<>();

        KeyboardRow keyboardFirstRow = new KeyboardRow();
        keyboardFirstRow.add(new KeyboardButton("/help"));
        keyboardFirstRow.add(new KeyboardButton("/settings"));
        keyboardFirstRow.add(new KeyboardButton("/info"));
        keyboardRowList.add(keyboardFirstRow);

        KeyboardRow keyboardSecondRow = new KeyboardRow();
        keyboardSecondRow.add(new KeyboardButton("/pic"));
        keyboardSecondRow.add(new KeyboardButton("/hide"));
        keyboardSecondRow.add(new KeyboardButton("/back"));
        keyboardRowList.add(keyboardSecondRow);

        replyKeyboardMarkup.setKeyboard(keyboardRowList);
    }

    public String getBotUsername() {
        return "name-of-the-bot";
    }

    public String getBotToken() {
        return "bot-token";
    }
}

0 个答案:

没有答案