Skip to content
This repository has been archived by the owner on Nov 12, 2023. It is now read-only.

Commit

Permalink
feat: JDA v5.0.0-alpha.17に対応 (#293)
Browse files Browse the repository at this point in the history
* feat: JDA v5.0.0-alpha.17に対応

* fix: 対応が完全ではなかったので修正

* fix: emote -> emojiに変更
  • Loading branch information
book000 authored Jul 29, 2022
1 parent 18c17bf commit d042d05
Show file tree
Hide file tree
Showing 22 changed files with 252 additions and 187 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
<dependency>
<groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId>
<version>5.0.0-alpha.9</version>
<version>5.0.0-alpha.17</version>
<exclusions>
<exclusion>
<groupId>club.minnced</groupId>
Expand Down
12 changes: 6 additions & 6 deletions src/main/java/com/jaoafa/javajaotan2/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public class Main {
static boolean isGuildDevelopMode = false;
static long developUserId;
static long developGuildId;
static Logger logger = LoggerFactory.getLogger("Javajaotan2");
static final Logger logger = LoggerFactory.getLogger("Javajaotan2");
static JavajaotanConfig config;
static JDA jda;
static JSONArray commands;
Expand Down Expand Up @@ -110,7 +110,7 @@ public static void main(String[] args) {
try {
JDABuilder jdabuilder = JDABuilder.createDefault(config.getToken())
.enableIntents(GatewayIntent.GUILD_MEMBERS, GatewayIntent.GUILD_PRESENCES,
GatewayIntent.GUILD_MESSAGE_TYPING, GatewayIntent.DIRECT_MESSAGE_TYPING, GatewayIntent.GUILD_EMOJIS)
GatewayIntent.GUILD_MESSAGE_TYPING, GatewayIntent.DIRECT_MESSAGE_TYPING, GatewayIntent.GUILD_EMOJIS_AND_STICKERS)
.setAutoReconnect(true)
.setBulkDeleteSplittingEnabled(false)
.setContextEnabled(false);
Expand Down Expand Up @@ -316,13 +316,12 @@ static void registerCommand(JDA jda) {
commands.put(details);

getLogger().info(String.format("%s: コマンドの登録に成功しました。", commandName));
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
InvocationTargetException e) {
getLogger().warn(String.format("%s: コマンドの登録に失敗しました。", commandName));
e.printStackTrace();
}
}

System.out.println(manager.getCommands());
} catch (InterruptedException | IOException | ClassNotFoundException e) {
e.printStackTrace();
}
Expand Down Expand Up @@ -351,7 +350,8 @@ static void registerEvent(JDABuilder jdaBuilder) {
jdaBuilder.addEventListeners(instance);
getLogger().info(String.format("%s: イベントの登録に成功しました。", eventName));
}
} catch (ClassNotFoundException | IOException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
} catch (ClassNotFoundException | IOException | NoSuchMethodException | InstantiationException |
IllegalAccessException | InvocationTargetException e) {
getLogger().error("イベントの登録に失敗しました。");
e.printStackTrace();
}
Expand Down
53 changes: 27 additions & 26 deletions src/main/java/com/jaoafa/javajaotan2/command/Cmd_GameRole.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import com.jaoafa.javajaotan2.lib.*;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.emoji.RichCustomEmoji;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
Expand All @@ -37,11 +38,11 @@
import java.util.stream.Collectors;

public class Cmd_GameRole implements CommandPremise {
Path path = GameRole.getPath();
Path pathMessages = GameRole.getPathMessages();
Pattern emojiPattern = GameRole.getEmojiPattern();
long SERVER_ID = GameRole.getServerId();
long GAME_ROLE_BORDER_ID = GameRole.getGameRoleBorderId();
final Path path = GameRole.getPath();
final Path pathMessages = GameRole.getPathMessages();
final Pattern emojiPattern = GameRole.getEmojiPattern();
final long SERVER_ID = GameRole.getServerId();
final long GAME_ROLE_BORDER_ID = GameRole.getGameRoleBorderId();

@Override
public JavajaotanCommand.Detail details() {
Expand Down Expand Up @@ -301,12 +302,12 @@ private void createGameRoleMessage(@NotNull Guild guild, @NotNull MessageChannel
sb.append("所持しているゲームの絵文字をこのメッセージにリアクションすると、ゲームロールが付与されます。\n");
sb.append("ロールの剥奪(解除)は運営側では対応しません。`/gamerole take <GAMENAME>`(GAMENAMEはゲーム名)で解除できます。\n\n");
List<String> usedEmojis = GameRole.getUsedGameEmojis();
List<String> emoteIds = guild.getEmotes()
List<String> emojiIds = guild.getEmojis()
.stream()
.map(Emote::getId)
.map(RichCustomEmoji::getId)
.filter(s -> !usedEmojis.contains(s))
.collect(Collectors.toList());
List<Emote> emotes = new ArrayList<>();
.toList();
List<RichCustomEmoji> emojis = new ArrayList<>();

for (String gameId : games) {
Role role = guild.getRoleById(gameId);
Expand All @@ -315,10 +316,10 @@ private void createGameRoleMessage(@NotNull Guild guild, @NotNull MessageChannel
}
String gameName = role.getName();
String gameEmoji = GameRole.getGameEmoji(gameId);
while (gameEmoji == null || sb.toString().contains(gameEmoji) || jda.getEmoteById(gameEmoji) == null) {
gameEmoji = emoteIds.get(new Random().nextInt(emoteIds.size()));
while (gameEmoji == null || sb.toString().contains(gameEmoji) || jda.getEmojiById(gameEmoji) == null) {
gameEmoji = emojiIds.get(new Random().nextInt(emojiIds.size()));
}
Emote emoji = jda.getEmoteById(gameEmoji);
RichCustomEmoji emoji = jda.getEmojiById(gameEmoji);
if (emoji == null) {
continue;
}
Expand All @@ -327,12 +328,12 @@ private void createGameRoleMessage(@NotNull Guild guild, @NotNull MessageChannel
.append(" ")
.append(gameName)
.append("\n");
emotes.add(emoji);
emojis.add(emoji);
}

Message postMessage = channel.sendMessage(sb.toString()).complete();
for (Emote emote : emotes) {
postMessage.addReaction(emote).queue();
for (RichCustomEmoji emoji : emojis) {
postMessage.addReaction(emoji).queue();
}
addMessage(postMessage);
}
Expand Down Expand Up @@ -371,7 +372,7 @@ private void changeGameRoleEmoji(@NotNull Guild guild, @NotNull MessageChannel c
if (matcher.matches()) {
emojiId = matcher.group(1);
}
Emote emoji = jda.getEmoteById(emojiId);
RichCustomEmoji emoji = jda.getEmojiById(emojiId);
if (emoji == null) {
message.reply("指定された絵文字が見つかりませんでした。").queue();
return;
Expand Down Expand Up @@ -498,12 +499,12 @@ private void updateMessages() {
sb.append("所持しているゲームの絵文字をこのメッセージにリアクションすると、ゲームロールが付与されます。\n");
sb.append("ロールの剥奪(解除)は運営側では対応しません。`/gamerole take <GAMENAME>`(GAMENAMEはゲーム名)で解除できます。\n\n");
List<String> usedEmojis = GameRole.getUsedGameEmojis();
List<String> emoteIds = guild.getEmotes()
List<String> emojiIds = guild.getEmojis()
.stream()
.map(Emote::getId)
.map(RichCustomEmoji::getId)
.filter(s -> !usedEmojis.contains(s))
.collect(Collectors.toList());
List<Emote> emotes = new ArrayList<>();
.toList();
List<RichCustomEmoji> emojis = new ArrayList<>();

for (String gameId : gameRoles) {
Role role = guild.getRoleById(gameId);
Expand All @@ -512,10 +513,10 @@ private void updateMessages() {
}
String gameName = role.getName();
String gameEmoji = GameRole.getGameEmoji(gameId);
while (gameEmoji == null || sb.toString().contains(gameEmoji) || jda.getEmoteById(gameEmoji) == null) {
gameEmoji = emoteIds.get(new Random().nextInt(emoteIds.size()));
while (gameEmoji == null || sb.toString().contains(gameEmoji) || jda.getEmojiById(gameEmoji) == null) {
gameEmoji = emojiIds.get(new Random().nextInt(emojiIds.size()));
}
Emote emoji = jda.getEmoteById(gameEmoji);
RichCustomEmoji emoji = jda.getEmojiById(gameEmoji);
if (emoji == null) {
continue;
}
Expand All @@ -524,7 +525,7 @@ private void updateMessages() {
.append(" ")
.append(gameName)
.append("\n");
emotes.add(emoji);
emojis.add(emoji);
}
JSONArray messages = games.getJSONArray("messages");
for (int i = 0; i < messages.length(); i++) {
Expand All @@ -538,8 +539,8 @@ private void updateMessages() {
String content = sb.toString();
Message message = channel.editMessageById(messageId, content).complete();
message.clearReactions().complete();
for (Emote emote : emotes) {
message.addReaction(emote).queue();
for (RichCustomEmoji emoji : emojis) {
message.addReaction(emoji).queue();
}
}
}
Expand Down
14 changes: 8 additions & 6 deletions src/main/java/com/jaoafa/javajaotan2/command/Cmd_Search.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* jaoLicense
*
* Copyright (c) 2021 jao Minecraft Server
* Copyright (c) 2022 jao Minecraft Server
*
* The following license applies to this project: jaoLicense
*
Expand Down Expand Up @@ -95,12 +95,14 @@ SearchResult customSearch(String gcpKey, String cx, String text) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
if (body == null) {
return null;
JSONObject object;
try (Response response = client.newCall(request).execute()) {
ResponseBody body = response.body();
if (body == null) {
return null;
}
object = new JSONObject(body.string());
}
JSONObject object = new JSONObject(body.string());
if (!object.has("searchInformation") || !object.has("items")) {
return null;
}
Expand Down
14 changes: 8 additions & 6 deletions src/main/java/com/jaoafa/javajaotan2/command/Cmd_SearchImg.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* jaoLicense
*
* Copyright (c) 2021 jao Minecraft Server
* Copyright (c) 2022 jao Minecraft Server
*
* The following license applies to this project: jaoLicense
*
Expand Down Expand Up @@ -98,12 +98,14 @@ SearchResult customSearch(String gcpKey, String cx, String text) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
if (body == null) {
return null;
JSONObject object;
try (Response response = client.newCall(request).execute()) {
ResponseBody body = response.body();
if (body == null) {
return null;
}
object = new JSONObject(body.string());
}
JSONObject object = new JSONObject(body.string());
if (!object.has("searchInformation") || !object.has("items")) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
* jaoLicense
*
* Copyright (c) 2021 jao Minecraft Server
* Copyright (c) 2022 jao Minecraft Server
*
* The following license applies to this project: jaoLicense
*
Expand Down Expand Up @@ -32,7 +32,6 @@
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class Cmd_ToRandJa implements CommandPremise {
@Override
Expand Down Expand Up @@ -62,7 +61,7 @@ private void translateRandJa(@NotNull Guild guild, @NotNull MessageChannel chann
List<Translate.Language> ignoreAutoUnknown = Arrays.stream(Translate.Language.values())
.filter(l -> l != Translate.Language.AUTO)
.filter(l -> l != Translate.Language.UNKNOWN)
.collect(Collectors.toList());
.toList();
Translate.Language lang1 = ignoreAutoUnknown.get(new Random().nextInt(ignoreAutoUnknown.size()));
Translate.Language lang2 = Translate.Language.JA;

Expand Down
40 changes: 15 additions & 25 deletions src/main/java/com/jaoafa/javajaotan2/event/Event_BugReaction.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@
import com.jaoafa.javajaotan2.lib.JavajaotanLibrary;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.ThreadChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.entities.emoji.EmojiUnion;
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;
Expand All @@ -31,8 +37,8 @@
import java.util.concurrent.TimeUnit;

public class Event_BugReaction extends ListenerAdapter {
String targetReaction = "\uD83D\uDC1B"; // :bug:
String repo = "jaoafa/jao-Minecraft-Server";
final String targetReaction = "\uD83D\uDC1B"; // :bug:
final String repo = "jaoafa/jao-Minecraft-Server";

@Override
public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) {
Expand All @@ -43,19 +49,19 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) {
if (user == null) user = event.retrieveUser().complete();
if (user.isBot()) return;

MessageReaction.ReactionEmote emote = event.getReactionEmote();
EmojiUnion emoji = event.getEmoji();

if (!emote.isEmoji()) return;
if (!emote.getEmoji().equals(targetReaction)) return;
if (emoji.getType() != Emoji.Type.UNICODE) return;
if (!emoji.asUnicode().getName().equals(targetReaction)) return;

Message message = event.retrieveMessage().complete();
List<User> users = message.retrieveReactionUsers(targetReaction).complete();
List<User> users = message.retrieveReactionUsers(Emoji.fromUnicode(targetReaction)).complete();

if (users.size() != 1) {
// 1人以外 = 0もしくは2人以上 = 既に報告済み
return;
}
TextChannel channel = event.getTextChannel();
MessageChannelUnion channel = event.getChannel();

// Issueを作成する
ZonedDateTime createdAt = message.getTimeCreated().atZoneSameInstant(ZoneId.of("Asia/Tokyo"));
Expand Down Expand Up @@ -93,22 +99,6 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) {
return;
}

String mainMessage = """
## 不具合と思われるメッセージ (または報告)
%s
URL: %s
## 不具合報告者
%s
""".formatted(
createdAt.format(formatter) + " に送信された " + message.getAuthor().getAsMention() + " による " + message.getChannel().getAsMention() + " でのメッセージ",
message.getJumpUrl(),
user.getAsMention()
);

List<String> messages = new ArrayList<>();
if (responseType == JavajaotanLibrary.IssueResponseType.SUCCESS) {
messages.add("[LINKED-ISSUE:jaoafa/jao-Minecraft-Server#" + issueNumber + "]");
Expand All @@ -135,6 +125,6 @@ public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) {
.setEmbeds(embed.build())
.build()).queue();

message.addReaction(targetReaction).queue();
message.addReaction(Emoji.fromUnicode(targetReaction)).queue();
}
}
Loading

0 comments on commit d042d05

Please sign in to comment.