为事件系统添加错误抛出支持,完成默认的api请求错误抛出

This commit is contained in:
A.C.Sukazyo Eyre 2022-01-10 02:24:08 +08:00
parent 82d557df51
commit 19b7c65559
Signed by: Eyre_S
GPG Key ID: EFB47D98FE082FAD
14 changed files with 134 additions and 35 deletions

View File

@ -1,6 +1,6 @@
## Core
VERSION = 0.4.3.2
VERSION = 0.4.3.3
# dependencies

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.3.2";
public static final long COMPILE_TIMESTAMP = 1641531965975L;
public static final String VERSION = "0.4.3.3";
public static final long COMPILE_TIMESTAMP = 1641752627626L;
}

View File

@ -1,5 +1,6 @@
package cc.sukazyo.cono.morny.bot.api;
import com.google.gson.GsonBuilder;
import com.pengrad.telegrambot.model.Update;
import javax.annotation.Nonnull;
@ -27,10 +28,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

@ -0,0 +1,35 @@
package cc.sukazyo.cono.morny.bot.api;
import com.pengrad.telegrambot.response.BaseResponse;
public class EventRuntimeException extends RuntimeException {
public EventRuntimeException () {
super();
}
public EventRuntimeException (String message) {
super(message);
}
public static class ActionFailed extends EventRuntimeException {
private final BaseResponse response;
public ActionFailed (BaseResponse response) {
super();
this.response = response;
}
public ActionFailed (String message, BaseResponse response) {
super(message);
this.response = response;
}
public BaseResponse getResponse() {
return response;
}
}
}

View File

@ -0,0 +1,32 @@
package cc.sukazyo.cono.morny.bot.api;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.request.BaseRequest;
import com.pengrad.telegrambot.response.BaseResponse;
public class Executor {
private final TelegramBot client;
public Executor (TelegramBot bot) {
client = bot;
}
public static Executor as (TelegramBot bot) {
return new Executor(bot);
}
public <T extends BaseRequest<T, R>, R extends BaseResponse> R exec (T req) {
return exec(req, "");
}
public <T extends BaseRequest<T, R>, R extends BaseResponse> R exec (T req, String errorMessage) {
final R resp = client.execute(req);
if (!resp.isOk()) throw new EventRuntimeException.ActionFailed(
(errorMessage.equals("") ? String.valueOf(resp.errorCode()) : errorMessage),
resp
);
return resp;
}
}

View File

@ -3,6 +3,7 @@ package cc.sukazyo.cono.morny.bot.event;
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.bot.api.Executor;
import cc.sukazyo.cono.morny.data.TelegramStickers;
import com.pengrad.telegrambot.model.Chat;
import com.pengrad.telegrambot.model.Update;
@ -55,7 +56,7 @@ public class OnCallMe extends EventListener {
return false;
}
}
MornyCoeur.getAccount().execute(new SendSticker(
Executor.as(MornyCoeur.getAccount()).exec(new SendSticker(
update.message().chat().id(),
TelegramStickers.ID_SENT
).replyToMessageId(update.message().messageId())
@ -70,7 +71,7 @@ public class OnCallMe extends EventListener {
* @param event 执行呼叫的tg事件
*/
private static void requestSteamJoin (Update event) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
ME, String.format(
"""
request <b>STEAM LIBRARY</b>
@ -90,7 +91,7 @@ public class OnCallMe extends EventListener {
* @param event 执行呼叫的tg事件
*/
private static void requestHanaParesuJoin (Update event) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
ME, String.format(
"""
request <b>Hana Paresu</b>
@ -118,7 +119,7 @@ public class OnCallMe extends EventListener {
* @since 0.4.2.2
*/
private static void requestCustomCall (Update event) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
ME, String.format(
"""
request <u>[???]</u>
@ -129,7 +130,7 @@ public class OnCallMe extends EventListener {
)
)
).parseMode(ParseMode.HTML));
MornyCoeur.getAccount().execute(new ForwardMessage(
Executor.as(MornyCoeur.getAccount()).exec(new ForwardMessage(
ME,
event.message().chat().id(),
event.message().messageId()

View File

@ -4,6 +4,7 @@ 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.Executor;
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;
@ -80,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(
Executor.as(MornyCoeur.getAccount()).exec(new SendSticker(
event.message().chat().id(),
TelegramStickers.ID_404
).replyToMessageId(event.message().messageId())
@ -90,7 +91,7 @@ public class OnCommandExecute extends EventListener {
}
private void onCommandOnExec (@Nonnull Update event) {
MornyCoeur.getAccount().execute(new SendSticker(
Executor.as(MornyCoeur.getAccount()).exec(new SendSticker(
event.message().chat().id(),
TelegramStickers.ID_ONLINE_STATUS_RETURN
).replyToMessageId(event.message().messageId())
@ -98,7 +99,7 @@ public class OnCommandExecute extends EventListener {
}
private void onCommandHelloExec (@Nonnull Update event) {
MornyCoeur.getAccount().execute(new SendSticker(
Executor.as(MornyCoeur.getAccount()).exec(new SendSticker(
event.message().chat().id(),
TelegramStickers.ID_HELLO
).replyToMessageId(event.message().messageId())
@ -107,7 +108,7 @@ public class OnCommandExecute extends EventListener {
private void onCommandExitExec (@Nonnull Update event) {
if (MornyCoeur.trustedInstance().isTrusted(event.message().from().id())) {
MornyCoeur.getAccount().execute(new SendSticker(
Executor.as(MornyCoeur.getAccount()).exec(new SendSticker(
event.message().chat().id(),
TelegramStickers.ID_EXIT
).replyToMessageId(event.message().messageId())
@ -115,7 +116,7 @@ public class OnCommandExecute extends EventListener {
logger.info("Morny exited by user @" + event.message().from().username());
System.exit(0);
} else {
MornyCoeur.getAccount().execute(new SendSticker(
Executor.as(MornyCoeur.getAccount()).exec(new SendSticker(
event.message().chat().id(),
TelegramStickers.ID_403
).replyToMessageId(event.message().messageId())
@ -125,7 +126,7 @@ public class OnCommandExecute extends EventListener {
}
private void onCommandVersionExec (@Nonnull Update event) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
String.format(
"""
@ -133,7 +134,7 @@ public class OnCommandExecute extends EventListener {
- <code>%s</code>
core md5_hash:
- <code>%s</code>
compile timestamp:
compile time<<sta?>mp:
- <code>%d</code>
- <code>%s [UTC]</code>""",
escapeHtml(MornySystem.VERSION),
@ -148,7 +149,7 @@ public class OnCommandExecute extends EventListener {
* @since 0.4.1.2
*/
private void onCommandRuntimeExec (@Nonnull Update event) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
String.format("""
system:
@ -197,7 +198,7 @@ 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(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
String.format(
"<a href='tg://user?id=%d'>%s</a> 在(utc的)今天的运气指数是———— <code>%.2f%%</code> %s",
@ -215,13 +216,13 @@ public class OnCommandExecute extends EventListener {
if (MornyCoeur.trustedInstance().isTrusted(event.message().from().id())) {
logger.info(String.format("called save from command by @%s.", event.message().from().username()));
MornyCoeur.callSaveData();
MornyCoeur.getAccount().execute(new SendSticker(
Executor.as(MornyCoeur.getAccount()).exec(new SendSticker(
event.message().chat().id(),
TelegramStickers.ID_SAVED
).replyToMessageId(event.message().messageId())
);
} else {
MornyCoeur.getAccount().execute(new SendSticker(
Executor.as(MornyCoeur.getAccount()).exec(new SendSticker(
event.message().chat().id(),
TelegramStickers.ID_403
).replyToMessageId(event.message().messageId())

View File

@ -2,6 +2,7 @@ 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.bot.api.Executor;
import cc.sukazyo.untitled.util.telegram.formatting.MsgEscape;
import com.google.gson.GsonBuilder;
@ -65,7 +66,7 @@ public class OnEventHackHandle extends EventListener {
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(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(x.fromChatId, String.format(
"<code>%s</code>",
MsgEscape.escapeHtml(new GsonBuilder().setPrettyPrinting().create().toJson(update))
)).parseMode(ParseMode.HTML).replyToMessageId((int)x.fromMessageId));

View File

@ -2,6 +2,7 @@ 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.bot.api.Executor;
import cc.sukazyo.cono.morny.util.EncryptUtils;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.InlineQueryResultArticle;
@ -24,7 +25,7 @@ public class OnInlineQuery extends EventListener {
*/
@Override
public boolean onInlineQuery (@Nonnull Update update) {
MornyCoeur.getAccount().execute(new AnswerInlineQuery(update.inlineQuery().id(), new InlineQueryResultArticle[]{
Executor.as(MornyCoeur.getAccount()).exec(new AnswerInlineQuery(update.inlineQuery().id(), new InlineQueryResultArticle[]{
new InlineQueryResultArticle(
EncryptUtils.encryptByMD5(update.inlineQuery().query()),
"Raw Input",

View File

@ -2,6 +2,7 @@ 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.bot.api.Executor;
import cc.sukazyo.untitled.util.command.CommonCommand;
import cc.sukazyo.untitled.util.string.StringArrays;
@ -48,7 +49,7 @@ public class OnUserSlashAction extends EventListener {
event.message().replyToMessage().from()
));
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).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",

View File

@ -2,6 +2,7 @@ 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.Executor;
import cc.sukazyo.cono.morny.bot.event.OnEventHackHandle;
import cc.sukazyo.cono.morny.data.TelegramStickers;
import cc.sukazyo.untitled.util.telegram.object.InputCommand;
@ -65,13 +66,13 @@ public class EventHack {
}
if (isOk) {
MornyCoeur.getAccount().execute(new SendSticker(
Executor.as(MornyCoeur.getAccount()).exec(new SendSticker(
event.message().chat().id(),
TelegramStickers.ID_WAITING
).replyToMessageId(event.message().messageId())
);
} else {
MornyCoeur.getAccount().execute(new SendSticker(
Executor.as(MornyCoeur.getAccount()).exec(new SendSticker(
event.message().chat().id(),
TelegramStickers.ID_403
).replyToMessageId(event.message().messageId())

View File

@ -1,6 +1,8 @@
package cc.sukazyo.cono.morny.bot.event.on_commands;
import cc.sukazyo.cono.morny.MornyCoeur;
import cc.sukazyo.cono.morny.bot.api.Executor;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.User;
import com.pengrad.telegrambot.model.request.ParseMode;
@ -16,7 +18,7 @@ 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) { Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
"[Unavailable] Too much arguments."
).replyToMessageId(event.message().messageId())); return; }
@ -30,7 +32,7 @@ public class GetUsernameAndId {
try {
userId = Long.parseLong(args[0]);
} catch (NumberFormatException e) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
"[Unavailable] " + e.getMessage()
).replyToMessageId(event.message().messageId()));
@ -38,12 +40,12 @@ public class GetUsernameAndId {
}
}
final GetChatMemberResponse response = MornyCoeur.getAccount().execute(
final GetChatMemberResponse response = Executor.as(MornyCoeur.getAccount()).exec(
new GetChatMember(event.message().chat().id(), userId)
);
if (response.chatMember() == null) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
"[Unavailable] user not found."
).replyToMessageId(event.message().messageId()));
@ -102,7 +104,7 @@ public class GetUsernameAndId {
));
}
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
userInformation.toString()
).replyToMessageId(event.message().messageId()).parseMode(ParseMode.HTML));

View File

@ -1,6 +1,7 @@
package cc.sukazyo.cono.morny.bot.event.on_commands;
import cc.sukazyo.cono.morny.MornyCoeur;
import cc.sukazyo.cono.morny.bot.api.Executor;
import cc.sukazyo.cono.morny.data.ip186.IP186QueryResponse;
import cc.sukazyo.untitled.util.telegram.object.InputCommand;
import cc.sukazyo.cono.morny.data.ip186.IP186QueryHandler;
@ -26,7 +27,7 @@ public class Ip186Query {
arg = event.message().replyToMessage().text();
}
} else if (command.getArgs().length > 1) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
"[Unavailable] Too much arguments."
).replyToMessageId(event.message().messageId()));
@ -35,7 +36,7 @@ public class Ip186Query {
arg = command.getArgs()[0];
}
if (arg == null) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
"[Unavailable] No ip defined."
).replyToMessageId(event.message().messageId()));
@ -48,12 +49,12 @@ public class Ip186Query {
case "/whois" -> IP186QueryHandler.queryWhois(arg);
default -> throw new IllegalArgumentException("Unknown 186-IP query method " + command.getCommand());
};
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
escapeHtml(response.url()) + "\n<code>" + escapeHtml(response.body()) + "</code>"
).parseMode(ParseMode.HTML).replyToMessageId(event.message().messageId()));
} catch (Exception e) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).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

@ -5,6 +5,7 @@ import com.pengrad.telegrambot.model.request.ParseMode;
import com.pengrad.telegrambot.request.SendMessage;
import cc.sukazyo.cono.morny.MornyCoeur;
import cc.sukazyo.cono.morny.bot.api.Executor;
import cc.sukazyo.cono.morny.data.NbnhhshQuery;
import cc.sukazyo.untitled.util.string.StringArrays;
import cc.sukazyo.untitled.util.telegram.object.InputCommand;
@ -35,13 +36,13 @@ public class Nbnhhsh {
}
}
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
message.toString()
).parseMode(ParseMode.HTML).replyToMessageId(event.message().messageId()));
} catch (Exception e) {
MornyCoeur.getAccount().execute(new SendMessage(
Executor.as(MornyCoeur.getAccount()).exec(new SendMessage(
event.message().chat().id(),
"[Exception] in query:\n<code>" + escapeHtml(e.getMessage()) + "</code>"
).parseMode(ParseMode.HTML).replyToMessageId(event.message().messageId()));