Skip to content

Commit

Permalink
消息发送失败时抛出异常
Browse files Browse the repository at this point in the history
  • Loading branch information
kosaka-bun committed Jan 6, 2025
1 parent acd40fc commit aa464bc
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 63 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ public synchronized void checkIsActive() {
reboot();
}

@SuppressWarnings("resource")
@SneakyThrows
@Override
public MiraiMessage typedTransform(Long group, long qq, RobotMultipartMessage message) {
Expand Down Expand Up @@ -256,8 +257,7 @@ public void sendPrivateMsg(long qq, RobotMultipartMessage message) {
//若不存在,不予发送
if(contact == null) return;
//发送消息
MiraiMessage msgAndRes = typedTransform(null, qq, message);
sendMessage(contact, msgAndRes);
sendMessage(contact, typedTransform(null, qq, message));
}

@Override
Expand All @@ -268,46 +268,43 @@ public void sendGroupMsg(long group, RobotMultipartMessage message) {
//机器人在该群被禁言,不予发送
if(isMuted(group)) return;
//发送消息
MiraiMessage msgAndRes = typedTransform(group, 0, message);
sendMessage(groupObj, msgAndRes);
sendMessage(groupObj, typedTransform(group, 0, message));
}

@SneakyThrows
private void sendMessage(Contact contact, MiraiMessage msgAndRes) {
if(msgAndRes == null) return;
MessageChain msg = msgAndRes.getMessageChain();
List<ExternalResource> externalResources = msgAndRes.getExternalResources();
DateFormat dateFormat = TextUtils.getSimpleDateFormat();
//当消息未成功发送时多次尝试
for(int tryTimes = 0; tryTimes < 3; tryTimes++) {
//尝试发送
try {
contact.sendMessage(msg);
} catch(Exception e) {
//未发送成功,重试
//报告错误
System.err.println(dateFormat.format(new Date()));
System.err.println("消息发送失败!已尝试次数:" + (tryTimes + 1));
System.err.println("要发送的内容:\n" + msg.contentToString());
e.printStackTrace();
//是否需要重发
if(!basicProperties.getResendOnSendFailed()) break;
continue;
}
//发送成功,不再继续尝试
//若非第一次尝试发送
if(tryTimes > 0) {
System.out.println(dateFormat.format(new Date()));
System.out.println("消息重发成功:\n" + msg.contentToString());
}
break;
}
//关闭资源
for(ExternalResource res : externalResources) {
try {
res.close();
} catch(Throwable t) {
//ignore
try(msgAndRes) {
MessageChain msg = msgAndRes.getMessageChain();
DateFormat dateFormat = TextUtils.getSimpleDateFormat();
//当消息未成功发送时多次尝试
Throwable throwable = null;
for(int tryTimes = 0; tryTimes < 3; tryTimes++) {
//尝试发送
try {
contact.sendMessage(msg);
} catch(Throwable t) {
throwable = t;
//未发送成功,重试
//报告错误
System.err.println(dateFormat.format(new Date()));
System.err.println("消息发送失败!已尝试次数:" + (tryTimes + 1));
System.err.println("要发送的内容:\n" + msg.contentToString());
t.printStackTrace();
//是否需要重发
if(!basicProperties.getResendOnSendFailed()) break;
continue;
}
throwable = null;
//发送成功,不再继续尝试
//若非第一次尝试发送
if(tryTimes > 0) {
System.out.println(dateFormat.format(new Date()));
System.out.println("消息重发成功:\n" + msg.contentToString());
}
break;
}
if(throwable != null) throw throwable;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.utils.ExternalResource;

import java.io.Closeable;
import java.util.ArrayList;
import java.util.List;

@Data
@Accessors(chain = true)
public class MiraiMessage {
public class MiraiMessage implements Closeable {

private MessageChain messageChain;

Expand All @@ -19,4 +20,15 @@ public class MiraiMessage {
public MiraiMessage(MessageChain messageChain) {
this.messageChain = messageChain;
}

@Override
public void close() {
for(ExternalResource res : externalResources) {
try {
res.close();
} catch(Throwable t) {
//ignore
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import de.honoka.qqrobot.framework.config.OnebotProperties
import de.honoka.qqrobot.framework.impl.onebot.component.ContactManager
import de.honoka.qqrobot.framework.impl.onebot.model.OnebotMessage
import de.honoka.qqrobot.starter.util.GlobalThreadPools
import de.honoka.sdk.util.kotlin.basic.exception
import de.honoka.sdk.util.kotlin.basic.log
import de.honoka.sdk.util.kotlin.text.toJsonWrapper
import jakarta.annotation.PreDestroy
Expand Down Expand Up @@ -331,30 +332,35 @@ class OnebotFramework(
private fun sendMessage(group: Long?, qq: Long?, message: OnebotMessage) {
val apiName = if(qq == null) "send_group_msg" else "send_private_msg"
val url = "${onebotProperties.urlPrefix}/$apiName"
for(i in 1..3) {
try {
val res = HttpUtil.post(
url,
JSONObject().let {
it["group_id"] = group
it["user_id"] = qq
it["message"] = message.parts
it.toString()
},
HTTP_REQUEST_TIMEOUT
).let { JSONUtil.parseObj(it) }
val retcode = res.getInt("retcode")
val errMsg = res.getStr("message")
if(retcode != 0) throw Exception("retcode = $retcode,errMsg = $errMsg")
} catch(t: Throwable) {
log.error("\n消息发送失败!已尝试次数:$i\n要发送的内容:\n${message.toRawString()}", t)
if(!basicProperties.resendOnSendFailed) break
continue
message.use { m ->
var throwable: Throwable? = null
for(i in 1..3) {
try {
val res = HttpUtil.post(
url,
JSONObject().let {
it["group_id"] = group
it["user_id"] = qq
it["message"] = m.parts
it.toString()
},
HTTP_REQUEST_TIMEOUT
).let { JSONUtil.parseObj(it) }
val retcode = res.getInt("retcode")
val errMsg = res.getStr("message")
if(retcode != 0) exception("retcode = $retcode,errMsg = $errMsg")
} catch(t: Throwable) {
throwable = t
log.error("\n消息发送失败!已尝试次数:$i\n要发送的内容:\n${m.toRawString()}", t)
if(!basicProperties.resendOnSendFailed) break
continue
}
throwable = null
if(i > 1) log.info("\n消息重发成功:\n${m.toRawString()}")
break
}
if(i > 1) log.info("\n消息重发成功:\n${message.toRawString()}")
break
throwable?.let { throw it }
}
message.close()
}

override fun getGroupName(group: Long): String = contactManager.groupCache[group]?.name ?: "【未知】"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,11 @@ public RobotMultipartMessage typedTransform(TesterRobotMessage message) {

@Override
public void sendPrivateMsg(long qq, RobotMultipartMessage message) {
boolean found = false;
for(TesterServerConnection connection : testerServer.getConnections()) {
long qqOfConnection = connection.getData().getLong("qq");
if(qqOfConnection != qq) continue;
found = true;
JSONObject data = new JSONObject();
data.set("name", "Robot");
data.set("content", typedTransform(null, qq, message).toJsonArray());
Expand All @@ -144,10 +146,15 @@ public void sendPrivateMsg(long qq, RobotMultipartMessage message) {
.setData(data)
);
}
if(found) return;
throw new RuntimeException("User " + qq + " is not online.");
}

@Override
public void sendGroupMsg(long group, RobotMultipartMessage message) {
if(testerServer.getConnections().isEmpty()) {
throw new RuntimeException("No users online.");
}
for(TesterServerConnection connection : testerServer.getConnections()) {
JSONObject data = new JSONObject();
data.set("name", "Robot");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import de.honoka.qqrobot.framework.api.model.RobotMultipartMessage;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
Expand Down Expand Up @@ -44,7 +45,7 @@ public void logGroupMessage(JoinPoint joinPoint) {
);
}

@Before("execution(* de.honoka.qqrobot.framework.impl.tester.TesterFramework.sendPrivateMsg(..))")
@AfterReturning("execution(* de.honoka.qqrobot.framework.impl.tester.TesterFramework.sendPrivateMsg(..))")
public void logSendPrivateMessage(JoinPoint joinPoint) {
long qq = (long) joinPoint.getArgs()[0];
Object msg = joinPoint.getArgs()[1];
Expand All @@ -54,7 +55,7 @@ public void logSendPrivateMessage(JoinPoint joinPoint) {
);
}

@Before("execution(* de.honoka.qqrobot.framework.impl.tester.TesterFramework.sendGroupMsg(..))")
@AfterReturning("execution(* de.honoka.qqrobot.framework.impl.tester.TesterFramework.sendGroupMsg(..))")
public void logSendGroupMessage(JoinPoint joinPoint) {
Long group = (Long) joinPoint.getArgs()[0];
Object msg = joinPoint.getArgs()[1];
Expand All @@ -64,7 +65,7 @@ public void logSendGroupMessage(JoinPoint joinPoint) {
);
}

@Before("execution(* de.honoka.qqrobot.framework.impl.tester.TesterFramework.reply(..))")
@AfterReturning("execution(* de.honoka.qqrobot.framework.impl.tester.TesterFramework.reply(..))")
public void logReplyMessage(JoinPoint joinPoint) {
Long group = (Long) joinPoint.getArgs()[0];
long qq = (long) joinPoint.getArgs()[1];
Expand Down

0 comments on commit aa464bc

Please sign in to comment.