diff --git a/.gitignore b/.gitignore index 037aacb..8520bdf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # IDE .idea/ +.vscode/ .gradle/ .settings/ /src/test/* diff --git a/build.gradle b/build.gradle index 2b36477..1720565 100644 --- a/build.gradle +++ b/build.gradle @@ -17,10 +17,19 @@ repositories { maven { name '-ws'; url 'https://mvn.sukazyo.cc' } } +String untitled (String lib, String upd = null) { + int majorCode = Integer.parseInt(project.libUntitledVersionMajor) + return "cc.sukazyo.untitled:$lib:[$majorCode${upd==null?"":".$upd"}, ${majorCode+1}[" +} dependencies { compileOnlyApi "com.github.spotbugs:spotbugs-annotations:${libSpotbugsVersion}" + implementation untitled("util-command-parser","1.0") + implementation untitled("util-string-commons", "1.0") + implementation untitled("util-telegram-api", "2.1") + implementation untitled("util-telegram-api-formatter", "3.3") + implementation untitled("util-telegram-commons", "1.0") api "cc.sukazyo:messiva:${libMessivaVersion}" implementation "com.github.pengrad:java-telegram-bot-api:${libJavaTelegramBotApiVersion}" diff --git a/gradle.properties b/gradle.properties index f697b89..78cc80d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,13 +1,15 @@ ## Core -VERSION = 0.4.2.11 +VERSION = 0.4.3.7 # dependencies -libSpotbugsVersion = 4.5.2 +libSpotbugsVersion = 4.5.3 + +libUntitledVersionMajor = 1 libMessivaVersion = 0.1.0.1 -libJavaTelegramBotApiVersion = 5.5.0 +libJavaTelegramBotApiVersion = 5.6.0 libJunitVersion = 5.8.2 diff --git a/src/main/java/cc/sukazyo/cono/morny/GradleProjectConfigures.java b/src/main/java/cc/sukazyo/cono/morny/GradleProjectConfigures.java index 4760921..91f2abf 100644 --- a/src/main/java/cc/sukazyo/cono/morny/GradleProjectConfigures.java +++ b/src/main/java/cc/sukazyo/cono/morny/GradleProjectConfigures.java @@ -4,6 +4,6 @@ package cc.sukazyo.cono.morny; * the final field that will be updated by gradle automatically. */ public class GradleProjectConfigures { - public static final String VERSION = "0.4.2.11"; - public static final long COMPILE_TIMESTAMP = 1640595623685L; + public static final String VERSION = "0.4.3.7"; + public static final long COMPILE_TIMESTAMP = 1642998030356L; } diff --git a/src/main/java/cc/sukazyo/cono/morny/MornyCoeur.java b/src/main/java/cc/sukazyo/cono/morny/MornyCoeur.java index 06d7944..b745d2d 100644 --- a/src/main/java/cc/sukazyo/cono/morny/MornyCoeur.java +++ b/src/main/java/cc/sukazyo/cono/morny/MornyCoeur.java @@ -3,6 +3,8 @@ package cc.sukazyo.cono.morny; import cc.sukazyo.cono.morny.bot.api.OnUpdate; import cc.sukazyo.cono.morny.bot.event.EventListeners; import cc.sukazyo.cono.morny.data.tracker.TrackerDataManager; +import cc.sukazyo.untitled.telegram.api.extra.ExtraAction; + import com.pengrad.telegrambot.TelegramBot; import com.pengrad.telegrambot.request.GetMe; @@ -25,6 +27,7 @@ public class MornyCoeur { /** morny 的 bot 账户 */ private final TelegramBot account; + private final ExtraAction extraActionInstance; /** * morny 的 bot 账户的用户名
*
@@ -95,6 +98,8 @@ public class MornyCoeur { throw ex; } + this.extraActionInstance = ExtraAction.as(account); + logger.info("Bot login succeed."); } @@ -122,6 +127,14 @@ public class MornyCoeur { logger.error("System already started coeur!!!"); } + /** + * 向所有的数据管理器发起保存数据的指令 + * @since 0.4.3.0 + */ + public void saveDataAll () { + TrackerDataManager.save(); + } + /** * 用于退出时进行缓存的任务处理等进行安全退出 */ @@ -167,6 +180,15 @@ public class MornyCoeur { throw new RuntimeException("Login failed.."); } + /** + * @see #saveDataAll() + * @since 0.4.3.0 + */ + public static void callSaveData () { + INSTANCE.saveDataAll(); + logger.info("done all save action."); + } + /** * 获取登录成功后的 telegram bot 对象 * @@ -207,4 +229,9 @@ public class MornyCoeur { return INSTANCE.trusted; } + @Nonnull + public static ExtraAction extra () { + return INSTANCE.extraActionInstance; + } + } diff --git a/src/main/java/cc/sukazyo/cono/morny/MornyTrusted.java b/src/main/java/cc/sukazyo/cono/morny/MornyTrusted.java index f892b9d..eb9305e 100644 --- a/src/main/java/cc/sukazyo/cono/morny/MornyTrusted.java +++ b/src/main/java/cc/sukazyo/cono/morny/MornyTrusted.java @@ -1,7 +1,6 @@ package cc.sukazyo.cono.morny; -import com.pengrad.telegrambot.model.ChatMember; -import com.pengrad.telegrambot.request.GetChatMember; +import com.pengrad.telegrambot.model.ChatMember.Status; /** * 对用户进行身份权限验证的管理类 @@ -37,13 +36,7 @@ public class MornyTrusted { */ public boolean isTrusted (long userId) { if (userId == MASTER) return true; - final ChatMember chatMember = MornyCoeur.getAccount().execute(new GetChatMember(TRUSTED_CHAT_ID, userId)).chatMember(); - return ( - chatMember != null && ( - chatMember.status() == ChatMember.Status.administrator || - chatMember.status() == ChatMember.Status.creator - ) - ); + return MornyCoeur.extra().isUserInGroup(userId, TRUSTED_CHAT_ID, Status.administrator); } } diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/api/EventListenerManager.java b/src/main/java/cc/sukazyo/cono/morny/bot/api/EventListenerManager.java index 343de29..f38d94a 100644 --- a/src/main/java/cc/sukazyo/cono/morny/bot/api/EventListenerManager.java +++ b/src/main/java/cc/sukazyo/cono/morny/bot/api/EventListenerManager.java @@ -1,7 +1,10 @@ package cc.sukazyo.cono.morny.bot.api; +import com.google.gson.GsonBuilder; import com.pengrad.telegrambot.model.Update; +import cc.sukazyo.untitled.telegram.api.event.EventRuntimeException; + import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Arrays; @@ -27,10 +30,31 @@ public class EventListenerManager { public void run () { for (EventListener x : listeners) { try { + if (exec.apply(x)) return; + + } catch (EventRuntimeException e) { + + final StringBuilder errorMessage = new StringBuilder(); + errorMessage.append("Event runtime breaks: " + e.getMessage()).append('\n'); + errorMessage.append("at " + e.getStackTrace()[0].toString()).append('\n'); + errorMessage.append("at " + e.getStackTrace()[1].toString()).append('\n'); + errorMessage.append("at " + e.getStackTrace()[2].toString()).append('\n'); + errorMessage.append("at " + e.getStackTrace()[3].toString()).append('\n'); + if (e instanceof EventRuntimeException.ActionFailed) { + errorMessage.append(( + "\"telegram request track\": " + + new GsonBuilder().setPrettyPrinting().create().toJson(((EventRuntimeException.ActionFailed)e).getResponse()) + ).indent(4)).append('\n'); + } + + logger.error(errorMessage.toString()); + } catch (Exception e) { + logger.error("Event Error!"); e.printStackTrace(System.out); + } } } diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/api/InputCommand.java b/src/main/java/cc/sukazyo/cono/morny/bot/api/InputCommand.java deleted file mode 100644 index 743d0da..0000000 --- a/src/main/java/cc/sukazyo/cono/morny/bot/api/InputCommand.java +++ /dev/null @@ -1,65 +0,0 @@ -package cc.sukazyo.cono.morny.bot.api; - -import cc.sukazyo.cono.morny.util.StringUtils; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.Arrays; - -public class InputCommand { - - private final String target; - private final String command; - private final String[] args; - - private InputCommand (@Nullable String target, @Nonnull String command, @Nonnull String[] args) { - this.target = target; - this.command = command; - this.args = args; - } - - public InputCommand (@Nonnull String[] inputArray) { - this(parseInputArray(inputArray)); - } - - public InputCommand (@Nonnull String input) { - this(StringUtils.formatCommand(input)); - } - - public InputCommand (@Nonnull InputCommand source) { - this(source.target, source.command, source.args); - } - - public static InputCommand parseInputArray (@Nonnull String[] inputArray) { - final String[] cx = inputArray[0].split("@", 2); - final String[] args = new String[inputArray.length-1]; - System.arraycopy(inputArray, 1, args, 0, inputArray.length - 1); - return new InputCommand(cx.length == 1 ? null : cx[1], cx[0], args); - } - - @Nullable - public String getTarget () { - return target; - } - - @Nonnull - public String getCommand () { - return command; - } - - @Nonnull - public String[] getArgs () { - return args; - } - - public boolean hasArgs () { - return args.length != 0; - } - - @Override - @Nonnull - public String toString() { - return String.format("{{%s}@{%s}#{%s}}", command, target, Arrays.toString(args)); - } - -} diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/event/OnCallMe.java b/src/main/java/cc/sukazyo/cono/morny/bot/event/OnCallMe.java index f105b9e..ef4e85b 100644 --- a/src/main/java/cc/sukazyo/cono/morny/bot/event/OnCallMe.java +++ b/src/main/java/cc/sukazyo/cono/morny/bot/event/OnCallMe.java @@ -4,6 +4,7 @@ import cc.sukazyo.cono.morny.MornyCoeur; import cc.sukazyo.cono.morny.MornyTrusted; import cc.sukazyo.cono.morny.bot.api.EventListener; import cc.sukazyo.cono.morny.data.TelegramStickers; +import cc.sukazyo.untitled.telegram.api.formatting.TGToString; import com.pengrad.telegrambot.model.Chat; import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.request.ParseMode; @@ -13,8 +14,6 @@ import com.pengrad.telegrambot.request.SendSticker; import javax.annotation.Nonnull; -import static cc.sukazyo.cono.morny.util.StringUtils.escapeHtmlTelegram; - /** * 通过 bot 呼叫主人的事件监听管理类 * @since 0.4.2.1 @@ -55,7 +54,7 @@ public class OnCallMe extends EventListener { return false; } } - MornyCoeur.getAccount().execute(new SendSticker( + MornyCoeur.extra().exec(new SendSticker( update.message().chat().id(), TelegramStickers.ID_SENT ).replyToMessageId(update.message().messageId()) @@ -70,15 +69,12 @@ public class OnCallMe extends EventListener { * @param event 执行呼叫的tg事件 */ private static void requestSteamJoin (Update event) { - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( ME, String.format( """ request STEAM LIBRARY - from %s""", - event.message().from().id(), - escapeHtmlTelegram( - event.message().from().firstName() + " " + event.message().from().lastName() - ) + from %s""", + TGToString.as(event.message().from()).fullnameRefHtml() ) ).parseMode(ParseMode.HTML)); } @@ -90,15 +86,12 @@ public class OnCallMe extends EventListener { * @param event 执行呼叫的tg事件 */ private static void requestHanaParesuJoin (Update event) { - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( ME, String.format( """ request Hana Paresu - from %s""", - event.message().from().id(), - escapeHtmlTelegram( - event.message().from().firstName() + " " + event.message().from().lastName() - ) + from %s""", + TGToString.as(event.message().from()).fullnameRefHtml() ) ).parseMode(ParseMode.HTML)); } @@ -118,18 +111,15 @@ public class OnCallMe extends EventListener { * @since 0.4.2.2 */ private static void requestCustomCall (Update event) { - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( ME, String.format( """ request [???] - from %s""", - event.message().from().id(), - escapeHtmlTelegram( - event.message().from().firstName() + " " + event.message().from().lastName() - ) + from %s""", + TGToString.as(event.message().from()).fullnameRefHtml() ) ).parseMode(ParseMode.HTML)); - MornyCoeur.getAccount().execute(new ForwardMessage( + MornyCoeur.extra().exec(new ForwardMessage( ME, event.message().chat().id(), event.message().messageId() diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/event/OnCommandExecute.java b/src/main/java/cc/sukazyo/cono/morny/bot/event/OnCommandExecute.java index a49d884..6196de1 100644 --- a/src/main/java/cc/sukazyo/cono/morny/bot/event/OnCommandExecute.java +++ b/src/main/java/cc/sukazyo/cono/morny/bot/event/OnCommandExecute.java @@ -4,12 +4,15 @@ import cc.sukazyo.cono.morny.GradleProjectConfigures; import cc.sukazyo.cono.morny.MornyCoeur; import cc.sukazyo.cono.morny.MornySystem; import cc.sukazyo.cono.morny.bot.api.EventListener; -import cc.sukazyo.cono.morny.bot.api.InputCommand; import cc.sukazyo.cono.morny.bot.event.on_commands.EventHack; import cc.sukazyo.cono.morny.bot.event.on_commands.GetUsernameAndId; import cc.sukazyo.cono.morny.bot.event.on_commands.Ip186Query; +import cc.sukazyo.cono.morny.bot.event.on_commands.Nbnhhsh; import cc.sukazyo.cono.morny.data.MornyJrrp; import cc.sukazyo.cono.morny.data.TelegramStickers; +import cc.sukazyo.untitled.telegram.api.formatting.TGToString; +import cc.sukazyo.untitled.util.telegram.object.InputCommand; + import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.request.ParseMode; import com.pengrad.telegrambot.request.SendMessage; @@ -20,7 +23,7 @@ import javax.annotation.Nonnull; import static cc.sukazyo.cono.morny.Log.logger; import static cc.sukazyo.cono.morny.util.CommonFormatUtils.formatDate; import static cc.sukazyo.cono.morny.util.CommonFormatUtils.formatDuration; -import static cc.sukazyo.cono.morny.util.StringUtils.escapeHtmlTelegram; +import static cc.sukazyo.untitled.util.telegram.formatting.MsgEscape.escapeHtml; public class OnCommandExecute extends EventListener { @@ -56,6 +59,9 @@ public class OnCommandExecute extends EventListener { case "/runtime": onCommandRuntimeExec(event); break; + case "/save": + onSaveDataExec(event); + break; case "/jrrp": onCommandJrrpExec(event); break; @@ -63,6 +69,9 @@ public class OnCommandExecute extends EventListener { case "/whois": Ip186Query.exec(event, command); break; + case "/nbnhhsh": + Nbnhhsh.exec(event, command); + break; default: return nonCommandExecutable(event, command); } @@ -72,7 +81,7 @@ public class OnCommandExecute extends EventListener { private boolean nonCommandExecutable (Update event, InputCommand command) { if (command.getTarget() == null) return false; // 无法解析的命令,转交事件链后代处理 else { // 无法解析的显式命令格式,报错找不到命令 - MornyCoeur.getAccount().execute(new SendSticker( + MornyCoeur.extra().exec(new SendSticker( event.message().chat().id(), TelegramStickers.ID_404 ).replyToMessageId(event.message().messageId()) @@ -82,7 +91,7 @@ public class OnCommandExecute extends EventListener { } private void onCommandOnExec (@Nonnull Update event) { - MornyCoeur.getAccount().execute(new SendSticker( + MornyCoeur.extra().exec(new SendSticker( event.message().chat().id(), TelegramStickers.ID_ONLINE_STATUS_RETURN ).replyToMessageId(event.message().messageId()) @@ -90,7 +99,7 @@ public class OnCommandExecute extends EventListener { } private void onCommandHelloExec (@Nonnull Update event) { - MornyCoeur.getAccount().execute(new SendSticker( + MornyCoeur.extra().exec(new SendSticker( event.message().chat().id(), TelegramStickers.ID_HELLO ).replyToMessageId(event.message().messageId()) @@ -99,25 +108,25 @@ public class OnCommandExecute extends EventListener { private void onCommandExitExec (@Nonnull Update event) { if (MornyCoeur.trustedInstance().isTrusted(event.message().from().id())) { - MornyCoeur.getAccount().execute(new SendSticker( + MornyCoeur.extra().exec(new SendSticker( event.message().chat().id(), TelegramStickers.ID_EXIT ).replyToMessageId(event.message().messageId()) ); - logger.info("Morny exited by user @" + event.message().from().username()); + logger.info("Morny exited by user " + TGToString.as(event.message().from()).toStringLogTag()); System.exit(0); } else { - MornyCoeur.getAccount().execute(new SendSticker( + MornyCoeur.extra().exec(new SendSticker( event.message().chat().id(), TelegramStickers.ID_403 ).replyToMessageId(event.message().messageId()) ); - logger.info("403 exited tag from user @" + event.message().from().username()); + logger.info("403 exited tag from user " + TGToString.as(event.message().from()).toStringLogTag()); } } private void onCommandVersionExec (@Nonnull Update event) { - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( event.message().chat().id(), String.format( """ @@ -128,10 +137,10 @@ public class OnCommandExecute extends EventListener { compile timestamp: - %d - %s [UTC]""", - escapeHtmlTelegram(MornySystem.VERSION), - escapeHtmlTelegram(MornySystem.getJarMd5()), + escapeHtml(MornySystem.VERSION), + escapeHtml(MornySystem.getJarMd5()), GradleProjectConfigures.COMPILE_TIMESTAMP, - escapeHtmlTelegram(formatDate(GradleProjectConfigures.COMPILE_TIMESTAMP, 0)) + escapeHtml(formatDate(GradleProjectConfigures.COMPILE_TIMESTAMP, 0)) ) ).replyToMessageId(event.message().messageId()).parseMode(ParseMode.HTML)); } @@ -140,7 +149,7 @@ public class OnCommandExecute extends EventListener { * @since 0.4.1.2 */ private void onCommandRuntimeExec (@Nonnull Update event) { - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( event.message().chat().id(), String.format(""" system: @@ -163,24 +172,24 @@ public class OnCommandExecute extends EventListener { - %s [UTC] - [%d]""", // system - escapeHtmlTelegram(System.getProperty("os.name")), - escapeHtmlTelegram(System.getProperty("os.version")), + escapeHtml(System.getProperty("os.name")), + escapeHtml(System.getProperty("os.version")), Runtime.getRuntime().availableProcessors(), // java - escapeHtmlTelegram(System.getProperty("java.vm.name")), - escapeHtmlTelegram(System.getProperty("java.version")), + escapeHtml(System.getProperty("java.vm.name")), + escapeHtml(System.getProperty("java.version")), // memory Runtime.getRuntime().totalMemory() / 1024 / 1024, Runtime.getRuntime().maxMemory() / 1024 / 1024, // version - escapeHtmlTelegram(MornySystem.VERSION), - escapeHtmlTelegram(MornySystem.getJarMd5()), - escapeHtmlTelegram(formatDate(GradleProjectConfigures.COMPILE_TIMESTAMP, 0)), + escapeHtml(MornySystem.VERSION), + escapeHtml(MornySystem.getJarMd5()), + escapeHtml(formatDate(GradleProjectConfigures.COMPILE_TIMESTAMP, 0)), GradleProjectConfigures.COMPILE_TIMESTAMP, // continuous - escapeHtmlTelegram(formatDuration(System.currentTimeMillis() - MornyCoeur.coeurStartTimestamp)), + escapeHtml(formatDuration(System.currentTimeMillis() - MornyCoeur.coeurStartTimestamp)), System.currentTimeMillis() - MornyCoeur.coeurStartTimestamp, - escapeHtmlTelegram(formatDate(MornyCoeur.coeurStartTimestamp, 0)), + escapeHtml(formatDate(MornyCoeur.coeurStartTimestamp, 0)), MornyCoeur.coeurStartTimestamp ) ).replyToMessageId(event.message().messageId()).parseMode(ParseMode.HTML)); @@ -189,15 +198,36 @@ public class OnCommandExecute extends EventListener { private void onCommandJrrpExec (Update event) { final double jrrp = MornyJrrp.getJrrpFromTelegramUser(event.message().from(), System.currentTimeMillis()); final String endChar = jrrp>70 ? "!" : jrrp>30 ? ";" : "..."; - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( event.message().chat().id(), String.format( - "%s 在(utc的)今天的运气指数是———— %.2f%% %s", - event.message().from().id(), - escapeHtmlTelegram(event.message().from().firstName()), - jrrp, escapeHtmlTelegram(endChar) + "%s 在(utc的)今天的运气指数是———— %.2f%% %s", + TGToString.as(event.message().from()).fullnameRefHtml(), + jrrp, escapeHtml(endChar) ) ).replyToMessageId(event.message().messageId()).parseMode(ParseMode.HTML)); } + /** + * @since 0.4.3.0 + */ + private void onSaveDataExec (Update event) { + if (MornyCoeur.trustedInstance().isTrusted(event.message().from().id())) { + logger.info("called save from command by " + TGToString.as(event.message().from()).toStringLogTag()); + MornyCoeur.callSaveData(); + MornyCoeur.extra().exec(new SendSticker( + event.message().chat().id(), + TelegramStickers.ID_SAVED + ).replyToMessageId(event.message().messageId()) + ); + } else { + MornyCoeur.extra().exec(new SendSticker( + event.message().chat().id(), + TelegramStickers.ID_403 + ).replyToMessageId(event.message().messageId()) + ); + logger.info("403 call save tag from user " + TGToString.as(event.message().from()).toStringLogTag()); + } + } + } diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/event/OnEventHackHandle.java b/src/main/java/cc/sukazyo/cono/morny/bot/event/OnEventHackHandle.java index a4275a4..a85a980 100644 --- a/src/main/java/cc/sukazyo/cono/morny/bot/event/OnEventHackHandle.java +++ b/src/main/java/cc/sukazyo/cono/morny/bot/event/OnEventHackHandle.java @@ -2,7 +2,8 @@ package cc.sukazyo.cono.morny.bot.event; import cc.sukazyo.cono.morny.MornyCoeur; import cc.sukazyo.cono.morny.bot.api.EventListener; -import cc.sukazyo.cono.morny.util.StringUtils; +import cc.sukazyo.untitled.util.telegram.formatting.MsgEscape; + import com.google.gson.GsonBuilder; import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.request.ParseMode; @@ -57,16 +58,16 @@ public class OnEventHackHandle extends EventListener { } private boolean onEventHacked (Update update, long chatId, long fromUser) { - logger.debug(String.format("try hack {{%d}}((%d))", chatId, fromUser)); + logger.debug(String.format("got event signed {{%d}}((%d))", chatId, fromUser)); Hacker x; x = hackers.remove(String.format("((%d))", fromUser)); if (x == null) x = hackers.remove(String.format("{{%d}}", chatId)); if (x == null) x = hackers.remove("[[]]"); if (x == null) return false; logger.debug("hacked event by " + x); - MornyCoeur.getAccount().execute(new SendMessage(x.fromChatId, String.format( + MornyCoeur.extra().exec(new SendMessage(x.fromChatId, String.format( "%s", - StringUtils.escapeHtmlTelegram(new GsonBuilder().setPrettyPrinting().create().toJson(update)) + MsgEscape.escapeHtml(new GsonBuilder().setPrettyPrinting().create().toJson(update)) )).parseMode(ParseMode.HTML).replyToMessageId((int)x.fromMessageId)); return true; } diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/event/OnInlineQuery.java b/src/main/java/cc/sukazyo/cono/morny/bot/event/OnInlineQuery.java index 1867887..5a64be5 100644 --- a/src/main/java/cc/sukazyo/cono/morny/bot/event/OnInlineQuery.java +++ b/src/main/java/cc/sukazyo/cono/morny/bot/event/OnInlineQuery.java @@ -24,7 +24,7 @@ public class OnInlineQuery extends EventListener { */ @Override public boolean onInlineQuery (@Nonnull Update update) { - MornyCoeur.getAccount().execute(new AnswerInlineQuery(update.inlineQuery().id(), new InlineQueryResultArticle[]{ + MornyCoeur.extra().exec(new AnswerInlineQuery(update.inlineQuery().id(), new InlineQueryResultArticle[]{ new InlineQueryResultArticle( EncryptUtils.encryptByMD5(update.inlineQuery().query()), "Raw Input", diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/event/OnUserSlashAction.java b/src/main/java/cc/sukazyo/cono/morny/bot/event/OnUserSlashAction.java index 67dff8a..5c4cf79 100644 --- a/src/main/java/cc/sukazyo/cono/morny/bot/event/OnUserSlashAction.java +++ b/src/main/java/cc/sukazyo/cono/morny/bot/event/OnUserSlashAction.java @@ -2,7 +2,10 @@ package cc.sukazyo.cono.morny.bot.event; import cc.sukazyo.cono.morny.MornyCoeur; import cc.sukazyo.cono.morny.bot.api.EventListener; -import cc.sukazyo.cono.morny.util.StringUtils; +import cc.sukazyo.untitled.telegram.api.formatting.TGToString; +import cc.sukazyo.untitled.util.command.CommonCommand; +import cc.sukazyo.untitled.util.string.StringArrays; + import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.User; import com.pengrad.telegrambot.model.request.ParseMode; @@ -10,7 +13,8 @@ import com.pengrad.telegrambot.request.SendMessage; import javax.annotation.Nonnull; -import static cc.sukazyo.cono.morny.util.StringUtils.escapeHtmlTelegram; +import static cc.sukazyo.cono.morny.Log.logger; +import static cc.sukazyo.untitled.util.telegram.formatting.MsgEscape.escapeHtml; public class OnUserSlashAction extends EventListener { @@ -20,6 +24,20 @@ public class OnUserSlashAction extends EventListener { if (text == null) return false; if (text.startsWith("/")) { + + /// Due to @Lapis_Apple, we stopped slash action function at .DP7 groups. + /// It may be enabled after some updates when the function will not be conflicted to other bots. + // if (event.message().chat().id() == ) return false; + if (event.message().chat().title() != null && event.message().chat().title().contains(".DP7")) { + logger.info(String.format(""" + Chat slash action ignored due to the following keyword. + - %s + - ".DP7\"""", + TGToString.as(event.message().chat()).toStringFullNameId() + )); + return false; + } + int prefixLength = 1; boolean useVerbSuffix = true; boolean useObjectPrefix = true; @@ -35,10 +53,10 @@ public class OnUserSlashAction extends EventListener { prefixLength = 2; } - final String[] action = StringUtils.formatCommand(text.substring(prefixLength)); + final String[] action = CommonCommand.format(text.substring(prefixLength)); final String verb = action[0]; final boolean hasObject = action.length != 1; - final String object = StringUtils.connectStringArray(action, " ", 1, action.length-1); + final String object = StringArrays.connectStringArray(action, " ", 1, action.length-1); final User origin = event.message().from(); final User target = (event.message().replyToMessage() == null ? ( origin @@ -46,15 +64,17 @@ public class OnUserSlashAction extends EventListener { event.message().replyToMessage().from() )); - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( event.message().chat().id(), String.format( - "%s %s%s %s%s%s", - origin.id(), escapeHtmlTelegram(origin.firstName()), - verb, escapeHtmlTelegram((useVerbSuffix?"了":"")), - target.id(), escapeHtmlTelegram((origin==target ? "自己" : target.firstName())), - escapeHtmlTelegram((hasObject ? (useObjectPrefix ?" 的": " ") : "")), - escapeHtmlTelegram((hasObject ? object : "")) + "%s %s%s %s%s%s", + TGToString.as(origin).firstnameRefHtml(), + verb, escapeHtml((useVerbSuffix?"了":"")), + origin==target ? + "自己" : + TGToString.as(target).firstnameRefHtml(), + escapeHtml((hasObject ? (useObjectPrefix ?" 的": " ") : "")), + escapeHtml((hasObject ? object : "")) ) ).parseMode(ParseMode.HTML)); diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/EventHack.java b/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/EventHack.java index 2146535..36e2571 100644 --- a/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/EventHack.java +++ b/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/EventHack.java @@ -2,9 +2,10 @@ package cc.sukazyo.cono.morny.bot.event.on_commands; import cc.sukazyo.cono.morny.MornyCoeur; import cc.sukazyo.cono.morny.MornyTrusted; -import cc.sukazyo.cono.morny.bot.api.InputCommand; import cc.sukazyo.cono.morny.bot.event.OnEventHackHandle; import cc.sukazyo.cono.morny.data.TelegramStickers; +import cc.sukazyo.untitled.util.telegram.object.InputCommand; + import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.request.SendSticker; @@ -64,13 +65,13 @@ public class EventHack { } if (isOk) { - MornyCoeur.getAccount().execute(new SendSticker( + MornyCoeur.extra().exec(new SendSticker( event.message().chat().id(), TelegramStickers.ID_WAITING ).replyToMessageId(event.message().messageId()) ); } else { - MornyCoeur.getAccount().execute(new SendSticker( + MornyCoeur.extra().exec(new SendSticker( event.message().chat().id(), TelegramStickers.ID_403 ).replyToMessageId(event.message().messageId()) diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/GetUsernameAndId.java b/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/GetUsernameAndId.java index b5cd025..24fb3df 100644 --- a/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/GetUsernameAndId.java +++ b/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/GetUsernameAndId.java @@ -1,6 +1,7 @@ package cc.sukazyo.cono.morny.bot.event.on_commands; import cc.sukazyo.cono.morny.MornyCoeur; + import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.User; import com.pengrad.telegrambot.model.request.ParseMode; @@ -10,13 +11,13 @@ import com.pengrad.telegrambot.response.GetChatMemberResponse; import javax.annotation.Nonnull; -import static cc.sukazyo.cono.morny.util.StringUtils.escapeHtmlTelegram; +import static cc.sukazyo.untitled.util.telegram.formatting.MsgEscape.escapeHtml; public class GetUsernameAndId { public static void exec (@Nonnull String[] args, @Nonnull Update event) { - if (args.length > 1) { MornyCoeur.getAccount().execute(new SendMessage( + if (args.length > 1) { MornyCoeur.extra().exec(new SendMessage( event.message().chat().id(), "[Unavailable] Too much arguments." ).replyToMessageId(event.message().messageId())); return; } @@ -30,7 +31,7 @@ public class GetUsernameAndId { try { userId = Long.parseLong(args[0]); } catch (NumberFormatException e) { - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( event.message().chat().id(), "[Unavailable] " + e.getMessage() ).replyToMessageId(event.message().messageId())); @@ -38,12 +39,12 @@ public class GetUsernameAndId { } } - final GetChatMemberResponse response = MornyCoeur.getAccount().execute( + final GetChatMemberResponse response = MornyCoeur.extra().exec( new GetChatMember(event.message().chat().id(), userId) ); if (response.chatMember() == null) { - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( event.message().chat().id(), "[Unavailable] user not found." ).replyToMessageId(event.message().messageId())); @@ -67,7 +68,7 @@ public class GetUsernameAndId { username : - %s""", - escapeHtmlTelegram(user.username()) + escapeHtml(user.username()) )); } if (user.firstName() == null) { @@ -78,7 +79,7 @@ public class GetUsernameAndId { firstname : - %s""", - escapeHtmlTelegram(user.firstName()) + escapeHtml(user.firstName()) )); } if (user.lastName() == null) { @@ -89,7 +90,7 @@ public class GetUsernameAndId { lastname : - %s""", - escapeHtmlTelegram(user.lastName()) + escapeHtml(user.lastName()) )); } if (user.languageCode() != null) { @@ -98,11 +99,11 @@ public class GetUsernameAndId { language-code : - %s""", - escapeHtmlTelegram(user.languageCode()) + escapeHtml(user.languageCode()) )); } - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( event.message().chat().id(), userInformation.toString() ).replyToMessageId(event.message().messageId()).parseMode(ParseMode.HTML)); diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/Ip186Query.java b/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/Ip186Query.java index 3c73c8a..48c7f86 100644 --- a/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/Ip186Query.java +++ b/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/Ip186Query.java @@ -1,8 +1,8 @@ package cc.sukazyo.cono.morny.bot.event.on_commands; import cc.sukazyo.cono.morny.MornyCoeur; -import cc.sukazyo.cono.morny.bot.api.InputCommand; import cc.sukazyo.cono.morny.data.ip186.IP186QueryResponse; +import cc.sukazyo.untitled.util.telegram.object.InputCommand; import cc.sukazyo.cono.morny.data.ip186.IP186QueryHandler; import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.model.request.ParseMode; @@ -10,7 +10,7 @@ import com.pengrad.telegrambot.request.SendMessage; import javax.annotation.Nonnull; -import static cc.sukazyo.cono.morny.util.StringUtils.escapeHtmlTelegram; +import static cc.sukazyo.untitled.util.telegram.formatting.MsgEscape.escapeHtml; /** * {@value IP186QueryHandler#SITE_URL} 查询的 telegram 命令前端 @@ -20,30 +20,42 @@ public class Ip186Query { public static void exec (@Nonnull Update event, @Nonnull InputCommand command) { - if (!command.hasArgs()) { MornyCoeur.getAccount().execute(new SendMessage( - event.message().chat().id(), - "[Unavailable] No ip defined." - ).replyToMessageId(event.message().messageId())); return; } - - if (command.getArgs().length > 1) { MornyCoeur.getAccount().execute(new SendMessage( - event.message().chat().id(), - "[Unavailable] Too much arguments." - ).replyToMessageId(event.message().messageId())); return; } + String arg = null; + if (!command.hasArgs()) { + if (event.message().replyToMessage() != null) { + arg = event.message().replyToMessage().text(); + } + } else if (command.getArgs().length > 1) { + MornyCoeur.extra().exec(new SendMessage( + event.message().chat().id(), + "[Unavailable] Too much arguments." + ).replyToMessageId(event.message().messageId())); + return; + } else { + arg = command.getArgs()[0]; + } + if (arg == null) { + MornyCoeur.extra().exec(new SendMessage( + event.message().chat().id(), + "[Unavailable] No ip defined." + ).replyToMessageId(event.message().messageId())); + return; + } try { IP186QueryResponse response = switch (command.getCommand()) { - case "/ip" -> IP186QueryHandler.queryIp(command.getArgs()[0]); - case "/whois" -> IP186QueryHandler.queryWhois(command.getArgs()[0]); + case "/ip" -> IP186QueryHandler.queryIp(arg); + case "/whois" -> IP186QueryHandler.queryWhois(arg); default -> throw new IllegalArgumentException("Unknown 186-IP query method " + command.getCommand()); }; - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( event.message().chat().id(), - escapeHtmlTelegram(response.url()) + "\n" + escapeHtmlTelegram(response.body()) + "" + escapeHtml(response.url()) + "\n" + escapeHtml(response.body()) + "" ).parseMode(ParseMode.HTML).replyToMessageId(event.message().messageId())); } catch (Exception e) { - MornyCoeur.getAccount().execute(new SendMessage( + MornyCoeur.extra().exec(new SendMessage( event.message().chat().id(), - "[Exception] in query:\n" + escapeHtmlTelegram(e.getMessage()) + "" + "[Exception] in query:\n" + escapeHtml(e.getMessage()) + "" ).parseMode(ParseMode.HTML).replyToMessageId(event.message().messageId())); } diff --git a/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/Nbnhhsh.java b/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/Nbnhhsh.java new file mode 100644 index 0000000..7dd130e --- /dev/null +++ b/src/main/java/cc/sukazyo/cono/morny/bot/event/on_commands/Nbnhhsh.java @@ -0,0 +1,61 @@ +package cc.sukazyo.cono.morny.bot.event.on_commands; + +import com.pengrad.telegrambot.model.Update; +import com.pengrad.telegrambot.model.request.ParseMode; +import com.pengrad.telegrambot.request.SendMessage; + +import cc.sukazyo.cono.morny.MornyCoeur; +import cc.sukazyo.cono.morny.data.NbnhhshQuery; +import cc.sukazyo.untitled.util.string.StringArrays; +import cc.sukazyo.untitled.util.telegram.object.InputCommand; + +import static cc.sukazyo.untitled.util.telegram.formatting.MsgEscape.escapeHtml; + +public class Nbnhhsh { + + public static void exec (Update event, InputCommand command) { + + try { + + String queryTarget = ""; + if (event.message().replyToMessage() != null && event.message().replyToMessage().text() != null) + queryTarget = event.message().replyToMessage().text(); + if (command.hasArgs()) + queryTarget = StringArrays.connectStringArray(command.getArgs(), " ", 0, command.getArgs().length-1); + + NbnhhshQuery.GuessResult response = NbnhhshQuery.sendGuess(queryTarget); + + StringBuilder message = new StringBuilder("## Result of nbnhhsh query :"); + + for (NbnhhshQuery.Word word : response.words) { + if (word.trans != null && word.trans.length == 0) word.trans = null; + if (word.inputting != null && word.inputting.length == 0) word.inputting = null; + if (word.trans == null && word.inputting == null) continue; + message.append("\n\n[[ ").append(escapeHtml(word.name)).append(" ]]"); + if (word.trans != null) for (String trans : word.trans) { + message.append("\n* ").append(escapeHtml(trans)).append(""); + } + if (word.inputting != null) { + if (word.trans != null) message.append("\n"); + message.append(" maybe:"); + for (String trans : word.inputting) { + message.append("\n` ").append(escapeHtml(trans)).append(""); + } + } + } + + MornyCoeur.extra().exec(new SendMessage( + event.message().chat().id(), + message.toString() + ).parseMode(ParseMode.HTML).replyToMessageId(event.message().messageId())); + + } catch (Exception e) { + MornyCoeur.extra().exec(new SendMessage( + event.message().chat().id(), + "[Exception] in query:\n" + escapeHtml(e.getMessage()) + "" + ).parseMode(ParseMode.HTML).replyToMessageId(event.message().messageId())); + } + + } + +} diff --git a/src/main/java/cc/sukazyo/cono/morny/data/NbnhhshQuery.java b/src/main/java/cc/sukazyo/cono/morny/data/NbnhhshQuery.java new file mode 100644 index 0000000..90119aa --- /dev/null +++ b/src/main/java/cc/sukazyo/cono/morny/data/NbnhhshQuery.java @@ -0,0 +1,54 @@ +package cc.sukazyo.cono.morny.data; + +import java.io.IOException; + +import com.google.gson.Gson; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class NbnhhshQuery { + + public static class Word { + public String name; + public String[] trans; + public String[] inputting; + } + + public static class GuessResult { + public Word[] words; + } + + public static record GuessReq (String text) { + } + + public static final String API_URL = "https://lab.magiconch.com/api/nbnhhsh/"; + public static final String API_GUESS_METHOD = "guess/"; + public static final String API_GUESS_DATA_TEMPLATE = "{ \"text\": \"%s\" }"; + + private static final OkHttpClient httpClient = new OkHttpClient(); + public static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); + + public static GuessResult sendGuess (String text) throws IOException { + final String reqJsonText = new Gson().toJson(new GuessReq(text)); + Request request = new Request.Builder() + .url(API_URL + API_GUESS_METHOD) + .post(RequestBody.create(JSON, reqJsonText)) + .build(); + try (Response response = httpClient.newCall(request).execute()) { + final ResponseBody body = response.body(); + if (body == null) throw new IOException("Null body."); + final String x = "{ \"words\": " + body.string() + " }"; + return new Gson().fromJson(x, GuessResult.class); + } + } + + public static void main(String[] args) { + System.out.println(new Gson().toJson(new GuessReq("8h28oey8 qe89 aoHO*)I'[ IK\"@+ )EOI)D\"{AIR\")Q @}"))); + } + +} diff --git a/src/main/java/cc/sukazyo/cono/morny/data/TelegramStickers.java b/src/main/java/cc/sukazyo/cono/morny/data/TelegramStickers.java index d478e05..c53024c 100644 --- a/src/main/java/cc/sukazyo/cono/morny/data/TelegramStickers.java +++ b/src/main/java/cc/sukazyo/cono/morny/data/TelegramStickers.java @@ -13,5 +13,6 @@ public class TelegramStickers { public static final String ID_404 = "CAACAgEAAx0CSQh32gABA966YbRJpbmi2lCHINBDuo1DknSTsbsAAqUoAAJ4_MYFUa8SIaZriAojBA"; public static final String ID_WAITING = "CAACAgEAAx0CSQh32gABA-8DYbh7W2VhJ490ucfZMUMrgMR2FW4AAm4nAAJ4_MYFjx6zpxJPWsQjBA"; public static final String ID_SENT = "CAACAgEAAx0CSQh32gABA--zYbiyU_wOijEitp-0tSl_k7W6l3gAAgMmAAJ4_MYF4GrompjXPx4jBA"; + public static final String ID_SAVED = "CAACAgEAAx0CSQh32gABBExuYdB_G0srfhQldRWkBYxWzCOv4-IAApooAAJ4_MYFcjuNZszfQcQjBA"; } diff --git a/src/main/java/cc/sukazyo/cono/morny/data/tracker/TrackerDataManager.java b/src/main/java/cc/sukazyo/cono/morny/data/tracker/TrackerDataManager.java index 753944d..06945ab 100644 --- a/src/main/java/cc/sukazyo/cono/morny/data/tracker/TrackerDataManager.java +++ b/src/main/java/cc/sukazyo/cono/morny/data/tracker/TrackerDataManager.java @@ -43,9 +43,7 @@ public class TrackerDataManager { logger.info("CALLED TO EXIT! writing cache."); } if (record.size() != 0) { - logger.info("start writing tracker data."); save(reset()); - logger.info("done writing tracker data."); } else logger.info("nothing to do yet"); } while (!postProcess); @@ -68,6 +66,12 @@ public class TrackerDataManager { DAEMON.start(); } + public static void save () { + logger.info("start writing tracker data."); + save(reset()); + logger.info("done writing tracker data."); + } + private static HashMap>> reset () { recordLock.lock(); HashMap>> recordOld = record; diff --git a/src/main/java/cc/sukazyo/cono/morny/util/StringUtils.java b/src/main/java/cc/sukazyo/cono/morny/util/StringUtils.java deleted file mode 100644 index ced5080..0000000 --- a/src/main/java/cc/sukazyo/cono/morny/util/StringUtils.java +++ /dev/null @@ -1,69 +0,0 @@ -package cc.sukazyo.cono.morny.util; - -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import java.util.ArrayList; - -public class StringUtils { - - @Nonnull - public static String[] formatCommand (@Nonnull String com) { - - final ArrayList arr = new ArrayList<>(); - - final StringBuilder tmp = new StringBuilder(); - final char[] coma = com.toCharArray(); - for (int i = 0; i < coma.length; i++) { - if (coma[i] == ' ') { - if (!tmp.toString().equals("")) { arr.add(tmp.toString()); } - tmp.setLength(0); - } else if (coma[i] == '"') { - while (true) { - i++; - if (coma[i] == '"') { - break; - } else if (coma[i] == '\\' && (coma[i+1] == '"' || coma[i+1] == '\\')) { - i++; - tmp.append(coma[i]); - } else { - tmp.append(coma[i]); - } - } - } else if (coma[i] == '\\' && (coma[i+1] == ' ' || coma[i+1] == '"' || coma[i+1] == '\\')) { - i++; - tmp.append(coma[i]); - } else { - tmp.append(coma[i]); - } - } - if (!tmp.toString().equals("")) { arr.add(tmp.toString()); } - tmp.setLength(0); - - final String[] out = new String[arr.size()]; - arr.toArray(out); - return out; - - } - - @Nonnull - public static String connectStringArray ( - @Nonnull String[] array, @Nonnull String connector, @Nonnegative int startIndex, @Nonnegative int stopIndex - ) { - final StringBuilder builder = new StringBuilder(); - for (int i = startIndex; i < stopIndex; i++) { - builder.append(array[i]); - builder.append(connector); - } - builder.append(array[stopIndex]); - return builder.toString(); - } - - @Nonnull - public static String escapeHtmlTelegram (String raw) { - raw = raw.replaceAll("&", "&"); - raw = raw.replaceAll("<", "<"); - raw = raw.replaceAll(">", ">"); - return raw; - } - -}