commit 04240d553c53a7b646f82d5aa5914e8d6a80fc5b Author: Alexey Zinchenko Date: Sat Feb 16 11:43:05 2019 +0300 Implemented basic version. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..879cf66 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +gradlew* +.gradle/* +gradle/* +.idea/* +out/* \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..3a200ba --- /dev/null +++ b/build.gradle @@ -0,0 +1,19 @@ +plugins { + id 'java' +} + +group 'com.github.prominence' +version '1.0-SNAPSHOT' + +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + +dependencies { + compile "org.telegram:telegrambots:4.1.2" + compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.11.2' + compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.11.2' + compile group: 'com.alibaba', name: 'fastjson', version: '1.2.44' +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..8ad7441 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'randomkitties-telegram-bot' + diff --git a/src/main/java/com/github/prominence/randomkitties/bot/Main.java b/src/main/java/com/github/prominence/randomkitties/bot/Main.java new file mode 100644 index 0000000..d98b039 --- /dev/null +++ b/src/main/java/com/github/prominence/randomkitties/bot/Main.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2019 Alexey Zinchenko + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.github.prominence.randomkitties.bot; + +import com.github.prominence.randomkitties.bot.handlers.RandomKittiesBot; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.telegram.telegrambots.ApiContextInitializer; +import org.telegram.telegrambots.meta.TelegramBotsApi; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; + +public class Main { + + public static final Logger log = LogManager.getLogger(Main.class); + + public static void main(String[] args) { + ApiContextInitializer.init(); + log.info("API context was initialized."); + + TelegramBotsApi telegramBotsApi = new TelegramBotsApi(); + try { + telegramBotsApi.registerBot(new RandomKittiesBot()); + } catch (TelegramApiException ex) { + ex.printStackTrace(); + } + } +} diff --git a/src/main/java/com/github/prominence/randomkitties/bot/handlers/RandomKittiesBot.java b/src/main/java/com/github/prominence/randomkitties/bot/handlers/RandomKittiesBot.java new file mode 100644 index 0000000..225cb57 --- /dev/null +++ b/src/main/java/com/github/prominence/randomkitties/bot/handlers/RandomKittiesBot.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2019 Alexey Zinchenko + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.github.prominence.randomkitties.bot.handlers; + +import com.github.prominence.randomkitties.bot.model.Kitty; +import com.github.prominence.randomkitties.bot.util.CatUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.telegram.telegrambots.bots.TelegramLongPollingBot; +import org.telegram.telegrambots.meta.api.methods.send.SendMediaGroup; +import org.telegram.telegrambots.meta.api.methods.send.SendMessage; +import org.telegram.telegrambots.meta.api.objects.Message; +import org.telegram.telegrambots.meta.api.objects.Update; +import org.telegram.telegrambots.meta.api.objects.media.InputMedia; +import org.telegram.telegrambots.meta.api.objects.media.InputMediaPhoto; +import org.telegram.telegrambots.meta.exceptions.TelegramApiException; + +import java.util.ArrayList; +import java.util.List; + +public class RandomKittiesBot extends TelegramLongPollingBot { + + private static final Logger log = LogManager.getLogger(RandomKittiesBot.class); + + @Override + public void onUpdateReceived(Update update) { + if (update.hasMessage()) { + final Message message = update.getMessage(); + if (message.hasText()) { + + final String requestText = message.getText(); + final String sender = message.getFrom().toString(); + + final Long chatId = message.getChatId(); + + logCommunication(sender, requestText); + + try { + switch (requestText) { + case "/kitty": + case "/kitty@RandomKittiesBot": + sendPhotosResponse(chatId, 1); + break; + case "/more_kitties": + case "/more_kitties@RandomKittiesBot": + sendPhotosResponse(chatId, 3); + break; + case "/moooooore_kitties": + case "/moooooore_kitties@RandomKittiesBot": + sendPhotosResponse(chatId, 5); + break; + case "/help": + case "/help@RandomKittiesBot": + default: + sendHelp(chatId); + break; + } + } catch (TelegramApiException ex) { + ex.printStackTrace(); + log.error(ex); + } + } + } + } + + @Override + public String getBotUsername() { + return "RandomKittiesBot"; + } + + @Override + public String getBotToken() { + return ""; + } + + private void sendHelp(Long chatId) throws TelegramApiException { + execute(new SendMessage(chatId, "Please, use on of the next commands: /kitty, /more_kitties, /moooooore_kitties")); + } + + private void sendPhotosResponse(Long chatId, int amount) throws TelegramApiException { + SendMediaGroup mediaGroup = new SendMediaGroup().setChatId(chatId); + List mediaList = new ArrayList<>(amount); + + final List kittiesList = CatUtils.getRandomCatsList(amount); + + kittiesList.forEach(kitty -> mediaList.add(new InputMediaPhoto(kitty.getUrl(), null))); + + mediaGroup.setMedia(mediaList); + + execute(mediaGroup); + } + + private void logCommunication(String sender, String requestText) { + StringBuilder builder = new StringBuilder(); + builder.append("\n=========== REQUEST ===========\n"); + builder.append("Sender : "); + builder.append(sender); + builder.append('\n'); + builder.append("Request text: "); + builder.append(requestText); + builder.append('\n'); + + log.debug(builder.toString()); + } + +} diff --git a/src/main/java/com/github/prominence/randomkitties/bot/model/Kitty.java b/src/main/java/com/github/prominence/randomkitties/bot/model/Kitty.java new file mode 100644 index 0000000..bbeaccc --- /dev/null +++ b/src/main/java/com/github/prominence/randomkitties/bot/model/Kitty.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2019 Alexey Zinchenko + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.github.prominence.randomkitties.bot.model; + +public class Kitty { + + private String id; + private String url; + + public Kitty() { + } + + public Kitty(String id, String url) { + this.id = id; + this.url = url; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } +} diff --git a/src/main/java/com/github/prominence/randomkitties/bot/util/CatUtils.java b/src/main/java/com/github/prominence/randomkitties/bot/util/CatUtils.java new file mode 100644 index 0000000..8b1ab73 --- /dev/null +++ b/src/main/java/com/github/prominence/randomkitties/bot/util/CatUtils.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2019 Alexey Zinchenko + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.github.prominence.randomkitties.bot.util; + +import com.github.prominence.randomkitties.bot.model.Kitty; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; + +public class CatUtils { + + public static final Logger log = LogManager.getLogger(CatUtils.class); + + private static final String API_URL = "https://api.thecatapi.com/v1/images/search?api_key="; + + public static List getRandomCatsList() { + return getRandomCatsList(1); + } + + public static List getRandomCatsList(int amount) { + try { + final String spec = API_URL + "&limit=" + amount; + + log.debug("Making request: " + spec); + + HttpURLConnection connection = (HttpURLConnection) new URL(spec).openConnection(); + connection.setRequestMethod("GET"); + final int responseCode = connection.getResponseCode(); + if (responseCode != HttpURLConnection.HTTP_OK) { + throw new RuntimeException("Bad response."); + } + + final InputStream inputStream = connection.getInputStream(); + return JSONUtils.parseJSON(inputStream); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/com/github/prominence/randomkitties/bot/util/JSONUtils.java b/src/main/java/com/github/prominence/randomkitties/bot/util/JSONUtils.java new file mode 100644 index 0000000..d393bbe --- /dev/null +++ b/src/main/java/com/github/prominence/randomkitties/bot/util/JSONUtils.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2019 Alexey Zinchenko + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.github.prominence.randomkitties.bot.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.TypeReference; +import com.github.prominence.randomkitties.bot.model.Kitty; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.List; + +public final class JSONUtils { + + private JSONUtils() {} + + public static List parseJSON(InputStream inputStream) throws IOException { + TypeReference> typeRef = new TypeReference>() {}; + return JSON.parseObject(getStringFromStream(inputStream), typeRef); + } + + private static String getStringFromStream(InputStream inputStream) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + + StringBuilder result = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + result.append(line); + } + + reader.close(); + + return result.toString(); + } +} diff --git a/src/main/resources/log4j2.properties b/src/main/resources/log4j2.properties new file mode 100644 index 0000000..41a4db4 --- /dev/null +++ b/src/main/resources/log4j2.properties @@ -0,0 +1,18 @@ +status = error +name = PropertiesConfig + +filters = threshold + +filter.threshold.type = ThresholdFilter +filter.threshold.level = debug + +appenders = console + +appender.console.type = Console +appender.console.name = STDOUT +appender.console.layout.type = PatternLayout +appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n + +rootLogger.level = debug +rootLogger.appenderRefs = stdout +rootLogger.appenderRef.stdout.ref = STDOUT \ No newline at end of file