-----BEGIN PGP SIGNATURE-----

iQGzBAABCAAdFiEERI59IUZFsNkyOsDp77R9mP4IL60FAmHuKlkACgkQ77R9mP4I
 L60rCwv9H5wYNtV9b7ROSyFYjsKw+N7KXRJf1pVY0ZI3AN0xWGxxTgt933gUm0AG
 zNRoxrxAu4ioaSzxOpFVWNN94S/kXTT8gnz4ow2e6DG3f3sQz/aClxwVU0VeQp8H
 SFpE8oDe0X/1tk7cUN63ousP8kdj638gUxYpHdgK99zrRZ/JOOe+wVayGRyY42Zy
 riaJp1HkOPjPBRs9AM3ipm9USo03sRJOUh6PA4dz7uNZEjEUwf+bxY2JJYq5cPU8
 Jt4jYx8bpeZzgUPnrhS9NrL1/b8NIcJGGUrVDyOPTHghaJDMENvD2cPPW/DRNqhr
 oBCpCeM/jH9GcU74k1BCMeKKxmEy4QJCtRmQuWQkZ1xARannnBpV6xXHAkPr7dSy
 jue1+QuXiEWr87Ln2NJ5U6IDaXA5J0onm8E2S2h4Sb7pX7TcBZZKSyPJT88l2jpa
 vvDSJrZjdtddRRCbaQ9Oq9/EqVUvH5cbHkhsMIX9HOcyg8Xxz7xHlySqwvFh4KOY
 X25jIWop
 =kRxB
 -----END PGP SIGNATURE-----
gpgsig -----BEGIN PGP SIGNATURE-----
 
 iQGzBAABCAAdFiEERI59IUZFsNkyOsDp77R9mP4IL60FAmIwXnMACgkQ77R9mP4I
 L63fhQwAqPxaXQlEuuBWOgHMNv8wP+coft1Jb6efyqUmrsDYoU1pJMi6m6cVNxnQ
 ykMeO6/97unjbnqx8fX/aCKVhSVNOeIem5b1iBtF9Uc3a73KjqbBJEURMGeexUg6
 4fUXobtYlODMJNZ3dP/4rWxDKVFhL1oAucOQivKJlMxhGYKJpFekYKCruXUg1zP9
 3JaY4p+gpKiAOhjmzDYEpu9eET95D3EUbRZOIClgDA3AGCDxGSTk9ib35agBn/G7
 Xg5V4T61D4MB0HEvRdtrXjijrP4HLCe/i6rYzQLQdPFfMSaQaJ1hgO3tva6vclex
 aHVM4YofO5JKwvK+IxzGMcf+Kom1UVKUIvlt15hARvh1AsVndE7nfVDV/c8EY8yi
 o+HGfAIn0w72ZTKxAbeMXfR6nFOEqTC8Af8L8UpKKq6W8Ap0XzaeoPb8Gob39SPj
 1NSDOQRXrYoJnwHUkCCnG1KLARzLIVVhRojsOHD8Gs5Y9zhbHXfFMM0Z4CwXHNdp
 folCXKgW
 =Znu0
 -----END PGP SIGNATURE-----

[[[release 0.4.3.7]]]

## 📇功能

- 添加 /save 命令,用于进行手动的数据保存(要求可信成员权限)。
- 添加 /nbnhhsh 命令,通过调用 https://lab.magiconch.com/api/nbnhhsh/ 查询文本内的 nbnhhsh 词条,支持后接或回复消息作为参数。
- /ip 和 /whois 命令现在可以将回复的消息作为参数处理。
- 中断斜杠动作在 ".DP7" 相关群组的响应

## 🔌系统接口

- 添加程序级别的数据保存方法。
- 将大部分 util 和 telegram-api extend 移动到 untitled 项目中。
- Coeur 主类为 untitled 的 ExtraAction[hsy] 添加实例持有。
- 使用 untitled:util-telegram-api-formatter 进行 Telegram 对象的扩展 ToString

## 🔩技术修改/typo

- 为 .gitignore 添加 .vscode 目录忽略
- 将 telegram api exec 由 TelegramBot#execute() 更改为 ExtraAction#exec()[hsy] 以支持了普通的错误处理
This commit is contained in:
A.C.Sukazyo Eyre 2022-03-15 17:31:09 +08:00
commit fc3eb3983a
21 changed files with 343 additions and 246 deletions

1
.gitignore vendored
View File

@ -1,6 +1,7 @@
# IDE
.idea/
.vscode/
.gradle/
.settings/
/src/test/*

View File

@ -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}"

View File

@ -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

View File

@ -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;
}

View File

@ -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 账户的用户名<br>
* <br>
@ -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;
}
}

View File

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

View File

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

View File

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

View File

@ -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 <b>STEAM LIBRARY</b>
from <a href="tg://user?id=%d">%s</a>""",
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 <b>Hana Paresu</b>
from <a href="tg://user?id=%d">%s</a>""",
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 <u>[???]</u>
from <a href="tg://user?id=%d">%s</a>""",
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()

View File

@ -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:
- <code>%d</code>
- <code>%s [UTC]</code>""",
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 {
- <code>%s [UTC]</code>
- [<code>%d</code>]""",
// 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(
"<a href='tg://user?id=%d'>%s</a> 在(utc的)今天的运气指数是———— <code>%.2f%%</code> %s",
event.message().from().id(),
escapeHtmlTelegram(event.message().from().firstName()),
jrrp, escapeHtmlTelegram(endChar)
"%s 在(utc的)今天的运气指数是———— <code>%.2f%%</code> %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());
}
}
}

View File

@ -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(
"<code>%s</code>",
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;
}

View File

@ -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",

View File

@ -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(
"<a href='tg://user?id=%d'>%s</a> %s%s <a href='tg://user?id=%d'>%s</a>%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 ?
"<a href='tg://user?id="+target.id()+"'>自己</a>" :
TGToString.as(target).firstnameRefHtml(),
escapeHtml((hasObject ? (useObjectPrefix ?"": " ") : "")),
escapeHtml((hasObject ? object : ""))
)
).parseMode(ParseMode.HTML));

View File

@ -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())

View File

@ -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 :
- <code>%s</code>""",
escapeHtmlTelegram(user.username())
escapeHtml(user.username())
));
}
if (user.firstName() == null) {
@ -78,7 +79,7 @@ public class GetUsernameAndId {
firstname :
- <code>%s</code>""",
escapeHtmlTelegram(user.firstName())
escapeHtml(user.firstName())
));
}
if (user.lastName() == null) {
@ -89,7 +90,7 @@ public class GetUsernameAndId {
lastname :
- <code>%s</code>""",
escapeHtmlTelegram(user.lastName())
escapeHtml(user.lastName())
));
}
if (user.languageCode() != null) {
@ -98,11 +99,11 @@ public class GetUsernameAndId {
language-code :
- <code>%s</code>""",
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));

View File

@ -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(
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; }
).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<code>" + escapeHtmlTelegram(response.body()) + "</code>"
escapeHtml(response.url()) + "\n<code>" + escapeHtml(response.body()) + "</code>"
).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<code>" + escapeHtmlTelegram(e.getMessage()) + "</code>"
"[Exception] in query:\n<code>" + escapeHtml(e.getMessage()) + "</code>"
).parseMode(ParseMode.HTML).replyToMessageId(event.message().messageId()));
}

View File

@ -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("<a href=\"https://lab.magiconch.com/nbnhhsh/\">## Result of nbnhhsh query :</a>");
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<b>[[ ").append(escapeHtml(word.name)).append(" ]]</b>");
if (word.trans != null) for (String trans : word.trans) {
message.append("\n* <i>").append(escapeHtml(trans)).append("</i>");
}
if (word.inputting != null) {
if (word.trans != null) message.append("\n");
message.append(" maybe:");
for (String trans : word.inputting) {
message.append("\n` <i>").append(escapeHtml(trans)).append("</i>");
}
}
}
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<code>" + escapeHtml(e.getMessage()) + "</code>"
).parseMode(ParseMode.HTML).replyToMessageId(event.message().messageId()));
}
}
}

View File

@ -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 @}")));
}
}

View File

@ -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";
}

View File

@ -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<Long, HashMap<Long, TreeSet<Long>>> reset () {
recordLock.lock();
HashMap<Long, HashMap<Long, TreeSet<Long>>> recordOld = record;

View File

@ -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<String> 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("&", "&amp;");
raw = raw.replaceAll("<", "&lt;");
raw = raw.replaceAll(">", "&gt;");
return raw;
}
}