Skip to content

Commit 90656a3

Browse files
committed
v3.5 更新自定义脚本解决部分问题
1 parent 00a6a9a commit 90656a3

File tree

9 files changed

+970
-4
lines changed

9 files changed

+970
-4
lines changed

build.gradle.kts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ plugins {
88
}
99

1010
group = "io.github.gdpl2112"
11-
version = "3.4"
11+
version = "3.5"
1212

1313
repositories {
1414
maven("https://repo1.maven.org/maven2/")

src/main/java/io/github/gdpl2112/mirai/p1/CallApiPlugin.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package io.github.gdpl2112.mirai.p1;
22

3+
import io.github.gdpl2112.mirai.p1.services.ScriptService;
34
import io.github.kloping.initialize.FileInitializeValue;
45
import kotlin.coroutines.CoroutineContext;
56
import net.mamoe.mirai.console.MiraiConsoleImplementation;
@@ -15,7 +16,6 @@
1516
import org.jetbrains.annotations.NotNull;
1617

1718
import java.io.File;
18-
import java.util.HashMap;
1919

2020
/**
2121
* @author github.kloping
@@ -27,7 +27,7 @@ public class CallApiPlugin extends JavaPlugin {
2727
public static Conf conf = null;
2828

2929
public CallApiPlugin() {
30-
super(new JvmPluginDescriptionBuilder("io.github.Kloping.mirai.p1.CallApiPlugin", "3.4")
30+
super(new JvmPluginDescriptionBuilder("io.github.Kloping.mirai.p1.CallApiPlugin", "3.5")
3131
.info("调用自定义API插件").build());
3232
}
3333

@@ -40,6 +40,7 @@ public void onDisable() {
4040
public void onEnable() {
4141
super.onEnable();
4242
loadConf();
43+
GlobalEventChannel.INSTANCE.registerListenerHost(new ScriptService());
4344
GlobalEventChannel.INSTANCE.registerListenerHost(new SimpleListenerHost() {
4445
@Override
4546
public void handleException(@NotNull CoroutineContext context, @NotNull Throwable exception) {
Lines changed: 293 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,293 @@
1+
package io.github.gdpl2112.mirai.p1.services;
2+
3+
import com.alibaba.fastjson.JSON;
4+
import io.github.kloping.arr.ArrSerializer;
5+
import io.github.kloping.io.ReadUtils;
6+
import io.github.kloping.url.UrlUtils;
7+
import net.mamoe.mirai.Bot;
8+
import net.mamoe.mirai.contact.Contact;
9+
import net.mamoe.mirai.contact.Friend;
10+
import net.mamoe.mirai.contact.Group;
11+
import net.mamoe.mirai.message.data.*;
12+
import net.mamoe.mirai.utils.ExternalResource;
13+
14+
import java.io.ByteArrayInputStream;
15+
import java.io.File;
16+
import java.io.IOException;
17+
import java.net.URL;
18+
import java.util.*;
19+
import java.util.regex.Matcher;
20+
import java.util.regex.Pattern;
21+
22+
23+
/**
24+
* @author github.kloping
25+
*/
26+
public class DgSerializer {
27+
private static final Pattern PATTER_FACE = Pattern.compile("<face:\\d+>");
28+
private static final Pattern PATTER_PIC = Pattern.compile("<pic:[^>^]+?>");
29+
private static final Pattern PATTER_URL = Pattern.compile("<url:[^>^]+>");
30+
private static final Pattern PATTER_AT = Pattern.compile("<at:[\\d+|?]+>");
31+
private static final Pattern PATTER_MUSIC = Pattern.compile("<music:\\d+>");
32+
private static final Pattern PATTER_VOICE = Pattern.compile("<audio:.+>");
33+
private static final Pattern PATTER_MIRAI_FACE = Pattern.compile("\\[mirai:face:.*?]");
34+
private static final Pattern PATTER_MIRAI_IMAGE = Pattern.compile("\\[mirai:image:.*?]");
35+
36+
public static final Pattern[] PATTERNS = {PATTER_FACE, PATTER_PIC, PATTER_URL, PATTER_AT, PATTER_VOICE, PATTER_MUSIC, PATTER_MIRAI_FACE, PATTER_MIRAI_IMAGE};
37+
38+
private static final String BASE64 = "base64,";
39+
40+
public static final Map<Integer, MarketFace> MARKET_FACE_MAP = new HashMap<>();
41+
42+
public static MessageChain stringDeserializeToMessageChain(String str, Bot bot, Contact contact) {
43+
if (str == null || str.isEmpty() || bot == null) return null;
44+
MessageChainBuilder builder = new MessageChainBuilder();
45+
goToFormat(str, builder, bot, contact);
46+
MessageChain message = builder.build();
47+
return message;
48+
}
49+
50+
private static List<Object> goToFormat(String sb, MessageChainBuilder builder, Bot bot, Contact contact) {
51+
List<Object> allElements = getAllElements(sb);
52+
for (Object o : allElements) {
53+
String str = o.toString();
54+
boolean k = (str.startsWith("<") || str.startsWith("[")) && !str.matches("\\[.+]请使用最新版手机QQ体验新功能");
55+
if (k) {
56+
Message msg = null;
57+
String ss = str.replaceAll("[<>\\[\\]]", "");
58+
int i1 = ss.indexOf(":");
59+
String s1 = ss.substring(0, i1);
60+
String s2 = ss.substring(i1 + 1);
61+
switch (s1.toLowerCase()) {
62+
case "pic":
63+
msg = createImage(contact, bot, s2);
64+
break;
65+
case "face":
66+
msg = new Face(Integer.parseInt(s2));
67+
break;
68+
case "at":
69+
long tid = -1L;
70+
if (s2.contains("?")) tid = contact.getId();
71+
else tid = Long.parseLong(s2);
72+
msg = new At(tid);
73+
break;
74+
case "voice":
75+
case "audio":
76+
msg = createVoiceMessageInGroup(s2, bot.getId(), contact);
77+
break;
78+
case "music":
79+
msg = createMusic(bot, s2);
80+
break;
81+
case "marketface":
82+
msg = MARKET_FACE_MAP.get(Integer.parseInt(s2));
83+
break;
84+
case "mirai":
85+
String type = s2.substring(0, s2.indexOf(":"));
86+
String c0 = s2.substring(s2.indexOf(":") + 1, s2.length());
87+
if (type.equals("face"))
88+
msg = new Face(Integer.parseInt(c0));
89+
else if (type.equals("image"))
90+
msg = createImage(contact, bot, c0);
91+
break;
92+
default:
93+
msg = new PlainText(s2);
94+
break;
95+
}
96+
if (msg != null) builder.append(msg);
97+
} else {
98+
builder.append(str);
99+
}
100+
}
101+
return allElements;
102+
}
103+
104+
public static List<Object> getAllElements(String line) {
105+
List<String> list = new ArrayList<>();
106+
List<Object> olist = new ArrayList<>();
107+
algorithmFill(list, line);
108+
for (String s : list) {
109+
int i = line.indexOf(s);
110+
if (i > 0) {
111+
olist.add(line.substring(0, i));
112+
}
113+
olist.add(s);
114+
line = line.substring(i + s.length());
115+
}
116+
if (!line.isEmpty()) olist.add(line);
117+
return olist;
118+
}
119+
120+
public static void algorithmFill(List<String> list, String line) {
121+
if (list == null || line == null || line.isEmpty()) return;
122+
Map<Integer, String> nm = getNearestOne(line, PATTERNS);
123+
if (nm.isEmpty()) {
124+
list.add(line);
125+
return;
126+
}
127+
int n = nm.keySet().iterator().next();
128+
String v = nm.get(n);
129+
String[] ss = new String[2];
130+
ss[0] = line.substring(0, line.indexOf(v));
131+
ss[1] = line.substring(line.indexOf(v) + v.length(), line.length());
132+
if (!ss[0].isEmpty()) {
133+
list.add(ss[0]);
134+
line = line.substring(ss[0].length());
135+
}
136+
line = ss[1];
137+
list.add(v);
138+
algorithmFill(list, line);
139+
return;
140+
}
141+
142+
public static Map<Integer, String> getNearestOne(final String line, Pattern... patterns) {
143+
try {
144+
Map<Integer, String> map = new LinkedHashMap<>();
145+
for (Pattern pattern : patterns) {
146+
Matcher matcher = pattern.matcher(line);
147+
if (matcher.find()) {
148+
String l1 = matcher.group();
149+
int i1 = line.indexOf(l1);
150+
map.put(i1, l1);
151+
}
152+
}
153+
Map<Integer, String> result1 = new LinkedHashMap<>();
154+
map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> result1.put(x.getKey(), x.getValue()));
155+
return result1;
156+
} catch (Exception e) {
157+
e.printStackTrace();
158+
return null;
159+
}
160+
}
161+
162+
private static Message createMusic(Bot contact, String vals) {
163+
String[] ss = vals.split(",");
164+
MusicKind kind = MusicKind.valueOf(ss[0]);
165+
MusicShare share = new MusicShare(kind, ss[1], ss[2], ss[3], ss[4], ss[5]);
166+
return share;
167+
}
168+
169+
public static Message createImage(Contact contact, Bot bot, String path) {
170+
Message image = null;
171+
try {
172+
if (path.startsWith("http")) {
173+
image = Contact.uploadImage(bot.getAsFriend(), new ByteArrayInputStream(ReadUtils.readAll(new URL(path).openStream())));
174+
} else if (path.startsWith("{")) {
175+
image = Image.fromId(path);
176+
} else if (path.contains(BASE64)) {
177+
image = Contact.uploadImage(bot.getAsFriend(), new ByteArrayInputStream(getBase64Data(path)));
178+
} else if (path.startsWith("[") && path.endsWith("]")) {
179+
image = createForwardMessageByPic(contact, bot, (String[]) JSON.parseArray(path).toArray(new String[0]));
180+
} else {
181+
image = Contact.uploadImage(bot.getAsFriend(), new File(path));
182+
}
183+
} catch (Exception e) {
184+
System.err.println(path + "加载失败");
185+
e.printStackTrace();
186+
}
187+
if (image != null) return image;
188+
else return null;
189+
}
190+
191+
public static byte[] getBase64Data(String base64) {
192+
int i = base64.indexOf(BASE64);
193+
String base64Str = base64.substring(i + BASE64.length());
194+
byte[] bytes = Base64.getDecoder().decode(base64Str);
195+
return bytes;
196+
}
197+
198+
public static Message createVoiceMessageInGroup(String url, long id, Contact contact) {
199+
ExternalResource resource = null;
200+
try {
201+
byte[] bytes = UrlUtils.getBytesFromHttpUrl(url);
202+
resource = ExternalResource.create(bytes);
203+
if (contact instanceof Group) {
204+
return ((Group) contact).uploadAudio(resource);
205+
} else if (contact instanceof Friend) {
206+
return ((Friend) contact).uploadAudio(resource);
207+
} else return new PlainText(url);
208+
} catch (Exception e) {
209+
e.printStackTrace();
210+
return null;
211+
} finally {
212+
if (resource != null) {
213+
try {
214+
resource.close();
215+
} catch (IOException e) {
216+
e.printStackTrace();
217+
}
218+
}
219+
}
220+
}
221+
222+
public static Message createForwardMessageByPic(Contact contact, Bot bot, String[] picUrl) {
223+
ForwardMessageBuilder builder = new ForwardMessageBuilder(contact);
224+
for (String s : picUrl) builder.add(bot.getId(), bot.getBot().getNick(), createImage(contact, bot, s));
225+
return builder.build();
226+
}
227+
228+
public static final ArrSerializer ARR_SERIALIZER = new ArrSerializer();
229+
230+
static {
231+
ARR_SERIALIZER.add(new ArrSerializer.Rule<Image>(Image.class) {
232+
@Override
233+
public String serializer(Image o) {
234+
return String.format("<pic:%s>", o.getImageId());
235+
}
236+
});
237+
ARR_SERIALIZER.add(new ArrSerializer.Rule<At>(At.class) {
238+
@Override
239+
public String serializer(At o) {
240+
return String.format("<at:%s>", o.getTarget());
241+
}
242+
});
243+
ARR_SERIALIZER.add(new ArrSerializer.Rule<Face>(Face.class) {
244+
@Override
245+
public String serializer(Face o) {
246+
return String.format("<face:%s>", o.getId());
247+
}
248+
});
249+
ARR_SERIALIZER.add(new ArrSerializer.Rule<PlainText>(PlainText.class) {
250+
@Override
251+
public String serializer(PlainText o) {
252+
String touch = o.getContent();
253+
String regx = "<.*?>";
254+
Pattern pattern = Pattern.compile(regx);
255+
Matcher matcher = pattern.matcher(touch);
256+
while (matcher.find()) {
257+
touch = touch.replace(matcher.group(), "\\" + matcher.group());
258+
}
259+
return touch;
260+
}
261+
});
262+
ARR_SERIALIZER.add(new ArrSerializer.Rule<Audio>(Audio.class) {
263+
@Override
264+
public String serializer(Audio o) {
265+
return String.format("<audio:%s>", o.getFilename());
266+
}
267+
});
268+
ARR_SERIALIZER.add(new ArrSerializer.Rule<MusicShare>(MusicShare.class) {
269+
@Override
270+
public String serializer(MusicShare o) {
271+
return String.format("<music:%s>", o.getMusicUrl());
272+
}
273+
});
274+
ARR_SERIALIZER.add(new ArrSerializer.Rule<MarketFace>(MarketFace.class) {
275+
@Override
276+
public String serializer(MarketFace o) {
277+
MARKET_FACE_MAP.put(o.getId(), o);
278+
return String.format("<marketface:%s>", o.getId());
279+
}
280+
});
281+
// ARR_SERIALIZER.add(new ArrSerializer.Rule<QuoteReply>(QuoteReply.class) {
282+
// @Override
283+
// public String serializer(QuoteReply o) {
284+
// return String.format("<qr:%s>", AllMessage.latest(0, o.getSource().getInternalIds()));
285+
// }
286+
// });
287+
ARR_SERIALIZER.setMode(1);
288+
}
289+
290+
public static String messageChainSerializeToString(MessageChain chain) {
291+
return ARR_SERIALIZER.serializer(chain);
292+
}
293+
}

0 commit comments

Comments
 (0)