From 5e9bda8899a078a907ea5095d50061b3eec478c8 Mon Sep 17 00:00:00 2001 From: Kosugi_kun <33971692+kosugikun@users.noreply.github.com> Date: Fri, 1 Apr 2022 19:55:03 +0900 Subject: [PATCH] =?UTF-8?q?Admin=E3=82=B3=E3=83=9E=E3=83=B3=E3=83=89?= =?UTF-8?q?=E3=81=AE=E4=B8=8D=E5=85=B7=E5=90=88=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 14 +-- .../java/com/jagrosh/jmusicbot/BotConfig.java | 10 ++- .../java/com/jagrosh/jmusicbot/JMusicBot.java | 64 +------------- .../jagrosh/jmusicbot/audio/AudioHandler.java | 9 +- .../jmusicbot/audio/NowplayingHandler.java | 4 +- .../jmusicbot/audio/PlayerManager.java | 2 +- .../jagrosh/jmusicbot/audio/QueuedTrack.java | 2 +- .../jagrosh/jmusicbot/entities/Prompt.java | 2 +- .../jagrosh/jmusicbot/utils/OtherUtil.java | 3 +- .../slashcommands/general/HelpCmd.java | 9 +- .../slashcommands/music/PlayCmd.java | 87 +------------------ .../slashcommands/music/QueueCmd.java | 2 +- .../slashcommands/music/SearchCmd.java | 70 +++++++-------- .../slashcommands/music/SkipCmd.java | 2 +- .../slashcommands/owner/DebugCmd.java | 7 +- .../slashcommands/owner/EvalCmd.java | 2 +- .../slashcommands/owner/SetgameCmd.java | 4 +- .../JMusicBot/util/LastSendTextChannel.java | 2 +- .../dev/cosgy/agent/GensokyoInfoAgent.java | 42 ++++----- .../dev/cosgy/niconicoSearchAPI/HTTPUtil.java | 4 +- .../niconicoSearchAPI/nicoSearchAPI.java | 6 +- 21 files changed, 101 insertions(+), 246 deletions(-) diff --git a/pom.xml b/pom.xml index 5fe5508fb..b400d662f 100644 --- a/pom.xml +++ b/pom.xml @@ -38,7 +38,7 @@ net.dv8tion JDA - 4.4.0_350 + 4.4.0_352 com.github.Cosgy-Dev @@ -70,7 +70,7 @@ pw.chew jda-chewtils - 1.23.0 + 1.24.1 compile pom @@ -222,15 +222,19 @@ testCompile - 88 + + + 11 + 11 + UTF-8 - 1.8 - 1.8 + 11 + 11 1.6.10 diff --git a/src/main/java/com/jagrosh/jmusicbot/BotConfig.java b/src/main/java/com/jagrosh/jmusicbot/BotConfig.java index 7e712708a..239f199bd 100644 --- a/src/main/java/com/jagrosh/jmusicbot/BotConfig.java +++ b/src/main/java/com/jagrosh/jmusicbot/BotConfig.java @@ -138,7 +138,7 @@ public void load() { + "\nhttps://github.com/jagrosh/MusicBot/wiki/Getting-a-Bot-Token." + "\nBOTトークン: "); if (token == null) { - prompt.alert(Prompt.Level.WARNING, CONTEXT, "トークンが入力されていません!終了します。\n\n設定ファイルの場所: " + path.toAbsolutePath().toString()); + prompt.alert(Prompt.Level.WARNING, CONTEXT, "トークンが入力されていません!終了します。\n\n設定ファイルの場所: " + path.toAbsolutePath()); return; } else { write = true; @@ -157,7 +157,7 @@ public void load() { owner = 0; } if (owner <= 0) { - prompt.alert(Prompt.Level.ERROR, CONTEXT, "無効なユーザーIDです!終了します。\n\n設定ファイルの場所: " + path.toAbsolutePath().toString()); + prompt.alert(Prompt.Level.ERROR, CONTEXT, "無効なユーザーIDです!終了します。\n\n設定ファイルの場所: " + path.toAbsolutePath()); System.exit(0); } else { write = true; @@ -182,7 +182,7 @@ public void load() { // if we get through the whole config, it's good to go valid = true; } catch (ConfigException | IOException ex) { - prompt.alert(Prompt.Level.ERROR, CONTEXT, ex + ": " + ex.getMessage() + "\n\n設定ファイルの場所: " + path.toAbsolutePath().toString()); + prompt.alert(Prompt.Level.ERROR, CONTEXT, ex + ": " + ex.getMessage() + "\n\n設定ファイルの場所: " + path.toAbsolutePath()); } } @@ -358,5 +358,7 @@ public boolean isOfficialInvite() { return officialInvite; } - public boolean isUseInviteCommand(){return useinvitecommand; } + public boolean isUseInviteCommand() { + return useinvitecommand; + } } diff --git a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java index 492f39861..14cd7e670 100644 --- a/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java +++ b/src/main/java/com/jagrosh/jmusicbot/JMusicBot.java @@ -139,73 +139,15 @@ public static void main(String[] args) { } List commandList = new ArrayList() {{ - //その他 - add(new HelpCmd(bot)); - add(aboutCommand); - if(config.isUseInviteCommand()){ - add(new InviteCommand()); - } - add(new PingCommand()); - add(new SettingsCmd(bot)); - if (config.getCosgyDevHost()) add(new InfoCommand(bot)); - // General - add(new ServerInfo()); - //add(new UserInfo()); - add(new CashCmd(bot)); - // Music - add(new LyricsCmd(bot)); - add(new NowplayingCmd(bot)); add(new PlayCmd(bot)); - add(new PlaylistsCmd(bot)); - add(new MylistCmd(bot)); - //add(new QueueCmd(bot)); - add(new QueueCmd(bot)); - add(new RemoveCmd(bot)); - add(new SearchCmd(bot)); - add(new SCSearchCmd(bot)); - add(new NicoSearchCmd(bot)); - add(new ShuffleCmd(bot)); - add(new SkipCmd(bot)); - add(new VolumeCmd(bot)); - // DJ - add(new ForceRemoveCmd(bot)); - add(new ForceskipCmd(bot)); - add(new NextCmd(bot)); - add(new MoveTrackCmd(bot)); - add(new PauseCmd(bot)); - add(new PlaynextCmd(bot)); - //add(new RepeatCmd(bot)); - add(new RepeatCmd(bot)); - add(new SkipToCmd(bot)); - add(new PlaylistCmd(bot)); - add(new StopCmd(bot)); - //add(new VolumeCmd(bot)); - // Admin - add(new PrefixCmd(bot)); - add(new SetdjCmd(bot)); - add(new SkipratioCmd(bot)); - add(new SettcCmd(bot)); - add(new SetvcCmd(bot)); - add(new AutoplaylistCmd(bot)); - add(new ServerListCmd(bot)); - // Owner - add(new DebugCmd(bot)); - add(new SetavatarCmd(bot)); - add(new SetgameCmd(bot)); - add(new SetnameCmd(bot)); - add(new SetstatusCmd(bot)); - add(new PublistCmd(bot)); - add(new ShutdownCmd(bot)); - //add(new LeaveCmd(bot)); }}; - cb.addCommands(commandList.toArray(new Command[0])); // スラッシュコマンドの実装 List slashCommandList = new ArrayList() {{ add(new HelpCmd(bot)); add(aboutCommand); - if(config.isUseInviteCommand()){ + if (config.isUseInviteCommand()) { add(new InviteCommand()); } add(new PingCommand()); @@ -244,6 +186,7 @@ public static void main(String[] args) { add(new StopCmd(bot)); //add(new VolumeCmd(bot)); // Admin + //add(new ActivateCmd(bot)); add(new PrefixCmd(bot)); add(new SetdjCmd(bot)); add(new SkipratioCmd(bot)); @@ -270,7 +213,7 @@ public static void main(String[] args) { if (config.getStatus() != OnlineStatus.UNKNOWN) cb.setStatus(config.getStatus()); if (config.getGame() == null) - cb.setActivity(Activity.playing(config.getPrefix() + config.getHelp() + "でヘルプを確認")); + cb.setActivity(Activity.playing("/" + config.getHelp() + "でヘルプを確認")); else if (config.getGame().getName().toLowerCase().matches("(none|なし)")) { cb.setActivity(null); nogame = true; @@ -303,6 +246,7 @@ else if (config.getGame().getName().toLowerCase().matches("(none|なし)")) { .setBulkDeleteSplittingEnabled(true) .build(); bot.setJDA(jda); + } catch (LoginException ex) { prompt.alert(Prompt.Level.ERROR, "JMusicBot", ex + "\n" + "正しい設定ファイルを編集していることを確認してください。Botトークンでのログインに失敗しました。" + diff --git a/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java b/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java index 023688113..36c5fd8d8 100644 --- a/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java +++ b/src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java @@ -42,7 +42,6 @@ import java.awt.*; import java.nio.ByteBuffer; -import java.text.MessageFormat; import java.util.HashSet; import java.util.LinkedList; import java.util.List; @@ -206,7 +205,7 @@ public Message getNowPlaying(JDA jda) { EmbedBuilder eb = new EmbedBuilder(); eb.setColor(guild.getSelfMember().getColor()); RequestMetadata rm = getRequestMetadata(); - if(!track.getInfo().uri.contains("https://stream.gensokyoradio.net/")) { + if (!track.getInfo().uri.contains("https://stream.gensokyoradio.net/")) { if (rm.getOwner() != 0L) { User u = guild.getJDA().getUserById(rm.user.id); if (u == null) @@ -233,9 +232,7 @@ public Message getNowPlaying(JDA jda) { + " `[" + FormatUtil.formatTime(track.getPosition()) + "/" + FormatUtil.formatTime(track.getDuration()) + "]` " + FormatUtil.volumeIcon(audioPlayer.getVolume())); - } - else - { + } else { JSONObject data = XML.toJSONObject(GensokyoInfoAgent.getInfo()).getJSONObject("GENSOKYORADIODATA"); String titleUrl = data.getJSONObject("MISC").getString("CIRCLELINK").equals("") ? @@ -291,7 +288,7 @@ public String getTopicFormat(JDA jda) { AudioTrack track = audioPlayer.getPlayingTrack(); // 幻想郷ラジオを再生しているか確認 - if(track.getInfo().uri.contains("https://stream.gensokyoradio.net/")) { + if (track.getInfo().uri.contains("https://stream.gensokyoradio.net/")) { return "**幻想郷ラジオ** [" + (userid == 0 ? "自動再生" : "<@" + userid + ">") + "]" + "\n" + (audioPlayer.isPaused() ? JMusicBot.PAUSE_EMOJI : JMusicBot.PLAY_EMOJI) + " " + "[LIVE] " diff --git a/src/main/java/com/jagrosh/jmusicbot/audio/NowplayingHandler.java b/src/main/java/com/jagrosh/jmusicbot/audio/NowplayingHandler.java index d4e6683c2..81d707ed0 100644 --- a/src/main/java/com/jagrosh/jmusicbot/audio/NowplayingHandler.java +++ b/src/main/java/com/jagrosh/jmusicbot/audio/NowplayingHandler.java @@ -119,9 +119,9 @@ public void onTrackUpdate(long guildId, AudioTrack track, AudioHandler handler) if (bot.getConfig().getSongInStatus()) { if (track != null && bot.getJDA().getGuilds().stream().filter(g -> Objects.requireNonNull(g.getSelfMember().getVoiceState()).inVoiceChannel()).count() <= 1) - if(track.getInfo().uri.contains("https://stream.gensokyoradio.net/")){ + if (track.getInfo().uri.contains("https://stream.gensokyoradio.net/")) { bot.getJDA().getPresence().setActivity(Activity.listening("幻想郷ラジオ")); - }else { + } else { bot.getJDA().getPresence().setActivity(Activity.listening(track.getInfo().title)); } else diff --git a/src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java b/src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java index 4683b111d..f2310356e 100644 --- a/src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java +++ b/src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java @@ -46,7 +46,7 @@ public void init() { ); } - TransformativeAudioSourceManager.createTransforms(bot.getConfig().getTransforms()).forEach(t -> registerSourceManager(t)); + TransformativeAudioSourceManager.createTransforms(bot.getConfig().getTransforms()).forEach(this::registerSourceManager); AudioSourceManagers.registerRemoteSources(this); AudioSourceManagers.registerLocalSource(this); source(YoutubeAudioSourceManager.class).setPlaylistPageCount(10); diff --git a/src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java b/src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java index a046f8a77..75dba7588 100644 --- a/src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java +++ b/src/main/java/com/jagrosh/jmusicbot/audio/QueuedTrack.java @@ -50,7 +50,7 @@ public AudioTrack getTrack() { @Override public String toString() { - if(track.getInfo().uri.contains("https://stream.gensokyoradio.net/")){ + if (track.getInfo().uri.contains("https://stream.gensokyoradio.net/")) { JSONObject data = XML.toJSONObject(GensokyoInfoAgent.getInfo()).getJSONObject("GENSOKYORADIODATA"); String title = data.getJSONObject("SONGINFO").getString("TITLE"); String titleUrl = data.getJSONObject("MISC").getString("CIRCLELINK").equals("") ? diff --git a/src/main/java/com/jagrosh/jmusicbot/entities/Prompt.java b/src/main/java/com/jagrosh/jmusicbot/entities/Prompt.java index 524eba1ae..63ec0faa4 100644 --- a/src/main/java/com/jagrosh/jmusicbot/entities/Prompt.java +++ b/src/main/java/com/jagrosh/jmusicbot/entities/Prompt.java @@ -29,7 +29,7 @@ public class Prompt { private final String noguiMessage; private boolean nogui; - private boolean noprompt; + private final boolean noprompt; private Scanner scanner; public Prompt(String title) { diff --git a/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java b/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java index 6b3b1b301..de8c546f4 100644 --- a/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java +++ b/src/main/java/com/jagrosh/jmusicbot/utils/OtherUtil.java @@ -31,6 +31,7 @@ import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; @@ -87,7 +88,7 @@ public static String readString(InputStream inputStream) throws IOException { into.write(buf, 0, n); } into.close(); - return into.toString("utf-8"); + return into.toString(StandardCharsets.UTF_8); } /** diff --git a/src/main/java/dev/cosgy/JMusicBot/slashcommands/general/HelpCmd.java b/src/main/java/dev/cosgy/JMusicBot/slashcommands/general/HelpCmd.java index 3a7535838..64ef7a61f 100644 --- a/src/main/java/dev/cosgy/JMusicBot/slashcommands/general/HelpCmd.java +++ b/src/main/java/dev/cosgy/JMusicBot/slashcommands/general/HelpCmd.java @@ -28,7 +28,8 @@ public class HelpCmd extends SlashCommand { public Bot bot; - public HelpCmd(Bot bot){ + + public HelpCmd(Bot bot) { this.bot = bot; this.name = "help"; this.help = "コマンド一覧を表示します。"; @@ -40,7 +41,7 @@ protected void execute(SlashCommandEvent event) { Category category = null; List commands = client.getCommands(); for (Command command : commands) { - if (!command.isHidden() && (!command.isOwnerCommand() ||event.getMember().isOwner())) { + if (!command.isHidden() && (!command.isOwnerCommand() || event.getMember().isOwner())) { if (!Objects.equals(category, command.getCategory())) { category = command.getCategory(); builder.append("\n\n __").append(category == null ? "カテゴリなし" : category.getName()).append("__:\n"); @@ -81,13 +82,13 @@ public void execute(CommandEvent event) { if (event.getClient().getServerInvite() != null) builder.append("\n\nさらにヘルプが必要な場合は、公式サーバーに参加することもできます: ").append(event.getClient().getServerInvite()); - if(bot.getConfig().getHelpToDm()){ + if (bot.getConfig().getHelpToDm()) { event.replyInDm(builder.toString(), unused -> { if (event.isFromType(ChannelType.TEXT)) event.reactSuccess(); }, t -> event.replyWarning("ダイレクトメッセージをブロックしているため、ヘルプを送信できません。")); - }else{ + } else { event.reply(builder.toString()); } } diff --git a/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/PlayCmd.java b/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/PlayCmd.java index 193424eff..e3bcc7c63 100644 --- a/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/PlayCmd.java +++ b/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/PlayCmd.java @@ -78,90 +78,7 @@ public PlayCmd(Bot bot) { @Override public void doCommand(CommandEvent event) { - if (event.getArgs().isEmpty() && event.getMessage().getAttachments().isEmpty()) { - AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler(); - if (handler.getPlayer().getPlayingTrack() != null && handler.getPlayer().isPaused()) { - if (DJCommand.checkDJPermission(event)) { - handler.getPlayer().setPaused(false); - event.replySuccess("**" + handler.getPlayer().getPlayingTrack().getInfo().title + "**の再生を再開しました。"); - - Bot.updatePlayStatus(event.getGuild(), event.getGuild().getSelfMember(), PlayStatus.PLAYING); - } else - event.replyError("再生を再開できるのはDJのみです!"); - return; - } - - // キャッシュの読み込み機構 - if (bot.getCacheLoader().cacheExists(event.getGuild().getId())) { - List data = bot.getCacheLoader().GetCache(event.getGuild().getId()); - - AtomicInteger count = new AtomicInteger(); - CacheLoader.CacheResult cache = bot.getCacheLoader().ConvertCache(data); - event.getChannel().sendMessage(":calling: キャッシュファイルを読み込んでいます... (" + cache.getItems().size() + "曲)").queue(m -> { - cache.loadTracks(bot.getPlayerManager(), (at) -> { - handler.addTrack(new QueuedTrack(at, User.fromId(data.get(count.get()).getUserId()))); - count.getAndIncrement(); - }, () -> { - StringBuilder builder = new StringBuilder(cache.getTracks().isEmpty() - ? event.getClient().getWarning() + " 楽曲がロードされていません。" - : event.getClient().getSuccess() + " キャッシュファイルから、" + "**" + cache.getTracks().size() + "**曲読み込みました。"); - if (!cache.getErrors().isEmpty()) - builder.append("\n以下の楽曲をロードできませんでした:"); - cache.getErrors().forEach(err -> builder.append("\n`[").append(err.getIndex() + 1).append("]` **").append(err.getItem()).append("**: ").append(err.getReason())); - String str = builder.toString(); - if (str.length() > 2000) - str = str.substring(0, 1994) + " (以下略)"; - m.editMessage(FormatUtil.filter(str)).queue(); - }); - }); - try { - bot.getCacheLoader().deleteCache(event.getGuild().getId()); - } catch (IOException e) { - e.printStackTrace(); - } - return; - } - - if (handler.playFromDefault()) { - Settings settings = event.getClient().getSettingsFor(event.getGuild()); - handler.stopAndClear(); - Playlist playlist = bot.getPlaylistLoader().getPlaylist(event.getGuild().getId(), settings.getDefaultPlaylist()); - if (playlist == null) { - event.replyError("プレイリストフォルダに`" + event.getArgs() + ".txt`が見つかりませんでした。"); - return; - } - event.getChannel().sendMessage(loadingEmoji + " プレイリストを読み込んでいます**" + settings.getDefaultPlaylist() + " ** ...( " + playlist.getItems().size() + "曲)").queue(m -> - { - - playlist.loadTracks(bot.getPlayerManager(), (at) -> handler.addTrack(new QueuedTrack(at, event.getAuthor())), () -> { - StringBuilder builder = new StringBuilder(playlist.getTracks().isEmpty() - ? event.getClient().getWarning() + " 曲がロードされていません!" - : event.getClient().getSuccess() + " ** " + playlist.getTracks().size() + " **曲をロードしました!"); - if (!playlist.getErrors().isEmpty()) - builder.append("\n次の曲を読み込めませんでした。:"); - playlist.getErrors().forEach(err -> builder.append("\n`[").append(err.getIndex() + 1).append("]` **").append(err.getItem()).append("**: ").append(err.getReason())); - String str = builder.toString(); - if (str.length() > 2000) - str = str.substring(0, 1994) + " (...)"; - m.editMessage(FormatUtil.filter(str)).queue(); - }); - }); - return; - - } - - StringBuilder builder = new StringBuilder(event.getClient().getWarning() + " Play コマンド:\n"); - builder.append("\n`").append(event.getClient().getPrefix()).append(name).append(" <曲名>` - YouTubeから最初の結果を再生"); - builder.append("\n`").append(event.getClient().getPrefix()).append(name).append(" ` - 指定された曲、再生リスト、またはストリームを再生します"); - for (Command cmd : children) - builder.append("\n`").append(event.getClient().getPrefix()).append(name).append(" ").append(cmd.getName()).append(" ").append(cmd.getArguments()).append("` - ").append(cmd.getHelp()); - event.reply(builder.toString()); - return; - } - String args = event.getArgs().startsWith("<") && event.getArgs().endsWith(">") - ? event.getArgs().substring(1, event.getArgs().length() - 1) - : event.getArgs().isEmpty() ? event.getMessage().getAttachments().get(0).getUrl() : event.getArgs(); - event.reply(loadingEmoji + "`[" + args + "]`を読み込み中です…", m -> bot.getPlayerManager().loadItemOrdered(event.getGuild(), args, new ResultHandler(m, event, false))); + event.getTextChannel().sendMessage("`/play`コマンドなどのスラッシュコマンドのみのサポートとなりました。").queue(); } @Override @@ -287,7 +204,7 @@ public class RequestCmd extends MusicCommand { private final static String CANCEL = "\uD83D\uDEAB"; // 🚫 private final String loadingEmoji; - private JDA jda; + private final JDA jda; public RequestCmd(Bot bot) { super(bot); diff --git a/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/QueueCmd.java b/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/QueueCmd.java index 292cbf40c..4398a0b68 100644 --- a/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/QueueCmd.java +++ b/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/QueueCmd.java @@ -144,7 +144,7 @@ private String getQueueTitle(AudioHandler ah, String success, int songslength, l sb.append(ah.getPlayer().isPaused() ? JMusicBot.PAUSE_EMOJI : JMusicBot.PLAY_EMOJI).append(" **") .append( ah.getPlayer().getPlayingTrack().getInfo().uri.contains("https://stream.gensokyoradio.net/") ? "幻想郷ラジオ" : - ah.getPlayer().getPlayingTrack().getInfo().title).append("**\n"); + ah.getPlayer().getPlayingTrack().getInfo().title).append("**\n"); } return FormatUtil.filter(sb.append(success).append(" 再生待ち楽曲一覧 | ").append(songslength) .append(" エントリー | `").append(FormatUtil.formatTime(total)).append("` ") diff --git a/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/SearchCmd.java b/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/SearchCmd.java index 85252e9e6..50ef44954 100644 --- a/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/SearchCmd.java +++ b/src/main/java/dev/cosgy/JMusicBot/slashcommands/music/SearchCmd.java @@ -153,78 +153,70 @@ public void loadFailed(FriendlyException throwable) { } } - private class ResultHandler implements AudioLoadResultHandler - { + private class ResultHandler implements AudioLoadResultHandler { private final Message m; private final CommandEvent event; - private ResultHandler(Message m, CommandEvent event) - { + private ResultHandler(Message m, CommandEvent event) { this.m = m; this.event = event; } @Override - public void trackLoaded(AudioTrack track) - { - if(bot.getConfig().isTooLong(track)) - { - m.editMessage(FormatUtil.filter(event.getClient().getWarning()+" この曲 (**"+track.getInfo().title+"**) は許可されている最大長よりも長いです。 `" - +FormatUtil.formatTime(track.getDuration())+"` > `"+bot.getConfig().getMaxTime()+"`")).queue(); + public void trackLoaded(AudioTrack track) { + if (bot.getConfig().isTooLong(track)) { + m.editMessage(FormatUtil.filter(event.getClient().getWarning() + " この曲 (**" + track.getInfo().title + "**) は許可されている最大長よりも長いです。 `" + + FormatUtil.formatTime(track.getDuration()) + "` > `" + bot.getConfig().getMaxTime() + "`")).queue(); return; } - AudioHandler handler = (AudioHandler)event.getGuild().getAudioManager().getSendingHandler(); - int pos = handler.addTrack(new QueuedTrack(track, event.getAuthor()))+1; - m.editMessage(FormatUtil.filter(event.getClient().getSuccess()+" **"+track.getInfo().title - +"** (`"+FormatUtil.formatTime(track.getDuration())+"`) "+(pos==0 ? "の再生を開始します。" + AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler(); + int pos = handler.addTrack(new QueuedTrack(track, event.getAuthor())) + 1; + m.editMessage(FormatUtil.filter(event.getClient().getSuccess() + " **" + track.getInfo().title + + "** (`" + FormatUtil.formatTime(track.getDuration()) + "`) " + (pos == 0 ? "の再生を開始します。" : "を" + pos + "番目の再生待ちに追加しました。"))).queue(); } @Override - public void playlistLoaded(AudioPlaylist playlist) - { + public void playlistLoaded(AudioPlaylist playlist) { builder.setColor(event.getSelfMember().getColor()) - .setText(FormatUtil.filter(event.getClient().getSuccess()+" `"+event.getArgs()+"`の検索結果:")) - .setChoices(new String[0]) - .setSelection((msg,i) -> + .setText(FormatUtil.filter(event.getClient().getSuccess() + " `" + event.getArgs() + "`の検索結果:")) + .setChoices() + .setSelection((msg, i) -> { - AudioTrack track = playlist.getTracks().get(i-1); - if(bot.getConfig().isTooLong(track)) - { - event.replyWarning("この曲 (**"+track.getInfo().title+"**) は、許容される最大長より長いです。: `" - +FormatUtil.formatTime(track.getDuration())+"` > `"+bot.getConfig().getMaxTime()+"`"); + AudioTrack track = playlist.getTracks().get(i - 1); + if (bot.getConfig().isTooLong(track)) { + event.replyWarning("この曲 (**" + track.getInfo().title + "**) は、許容される最大長より長いです。: `" + + FormatUtil.formatTime(track.getDuration()) + "` > `" + bot.getConfig().getMaxTime() + "`"); return; } - AudioHandler handler = (AudioHandler)event.getGuild().getAudioManager().getSendingHandler(); - int pos = handler.addTrack(new QueuedTrack(track, event.getAuthor()))+1; + AudioHandler handler = (AudioHandler) event.getGuild().getAudioManager().getSendingHandler(); + int pos = handler.addTrack(new QueuedTrack(track, event.getAuthor())) + 1; event.replySuccess("**" + FormatUtil.filter(track.getInfo().title) - + "** (`" + FormatUtil.formatTime(track.getDuration()) + "`) " + (pos==0 ? "の再生を開始します。" + + "** (`" + FormatUtil.formatTime(track.getDuration()) + "`) " + (pos == 0 ? "の再生を開始します。" : "を" + pos + "番目の再生待ちに追加しました。")); }) - .setCancel((msg) -> {}) + .setCancel((msg) -> { + }) .setUsers(event.getAuthor()) ; - for(int i=0; i<4 && i textChannel = new HashMap<>(); + private static final HashMap textChannel = new HashMap<>(); public static void SetLastTextId(CommandEvent event) { textChannel.put(event.getGuild().getIdLong(), event.getTextChannel().getIdLong()); diff --git a/src/main/java/dev/cosgy/agent/GensokyoInfoAgent.java b/src/main/java/dev/cosgy/agent/GensokyoInfoAgent.java index 4ebd1bfc2..56796e0da 100644 --- a/src/main/java/dev/cosgy/agent/GensokyoInfoAgent.java +++ b/src/main/java/dev/cosgy/agent/GensokyoInfoAgent.java @@ -34,27 +34,6 @@ public GensokyoInfoAgent() { setName("GensokyoInfoAgent"); } - @Override - public void run() { - log.info("GensokyoInfoAgentを開始しました"); - - //noinspection InfiniteLoopStatement - while (true) { - try { - fetch(); - sleep(INTERVAL_MILLIS); - } catch (Exception e) { - log.error("情報を取得中に例外が発生しました!", e); - try { - sleep(1000); - } catch (InterruptedException e1) { - log.error("エージェントの例外後にスリープ中に中断されました", e); - break; - } - } - } - } - @SuppressWarnings("UnusedReturnValue") private static String fetch() { try { @@ -79,4 +58,25 @@ private static String fetch() { public static String getInfo() { return info == null ? fetch() : info; } + + @Override + public void run() { + log.info("GensokyoInfoAgentを開始しました"); + + //noinspection InfiniteLoopStatement + while (true) { + try { + fetch(); + sleep(INTERVAL_MILLIS); + } catch (Exception e) { + log.error("情報を取得中に例外が発生しました!", e); + try { + sleep(1000); + } catch (InterruptedException e1) { + log.error("エージェントの例外後にスリープ中に中断されました", e); + break; + } + } + } + } } diff --git a/src/main/java/dev/cosgy/niconicoSearchAPI/HTTPUtil.java b/src/main/java/dev/cosgy/niconicoSearchAPI/HTTPUtil.java index 2e41396ec..2c64dd38d 100644 --- a/src/main/java/dev/cosgy/niconicoSearchAPI/HTTPUtil.java +++ b/src/main/java/dev/cosgy/niconicoSearchAPI/HTTPUtil.java @@ -166,7 +166,7 @@ public String request() { response.close(); } - System.out.println("エラー: " + responseCode + "\n" + sb.toString()); + System.out.println("エラー: " + responseCode + "\n" + sb); } } catch (MalformedURLException e) { throw new NullPointerException("URLが不正です: " + e.getLocalizedMessage()); @@ -188,7 +188,7 @@ public String request() { } catch (Exception ignored) { } - System.out.println("エラーが発生しました: " + e.getLocalizedMessage() + "\n" + sb.toString()); + System.out.println("エラーが発生しました: " + e.getLocalizedMessage() + "\n" + sb); } finally { if (connection != null) connection.disconnect(); } diff --git a/src/main/java/dev/cosgy/niconicoSearchAPI/nicoSearchAPI.java b/src/main/java/dev/cosgy/niconicoSearchAPI/nicoSearchAPI.java index 97dd7dd70..33bc80dc8 100644 --- a/src/main/java/dev/cosgy/niconicoSearchAPI/nicoSearchAPI.java +++ b/src/main/java/dev/cosgy/niconicoSearchAPI/nicoSearchAPI.java @@ -4,6 +4,7 @@ import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; @@ -32,10 +33,7 @@ public LinkedList searchVideo(String query, int resultLim hu.setTargetAddress("https://api.search.nicovideo.jp/api/v2/video/contents/search"); hu.setMethod("GET"); Map queryMap = new HashMap<>(); - try { - queryMap.put("q", URLEncoder.encode(query, "UTF-8")); - } catch (UnsupportedEncodingException ignored) { - } + queryMap.put("q", URLEncoder.encode(query, StandardCharsets.UTF_8)); queryMap.put("_sort", "-viewCounter"); queryMap.put("targets", "title"); queryMap.put("fields", "contentId,title,description,tags,categoryTags,viewCounter,mylistCounter,commentCounter,startTime,lastCommentTime,lengthSeconds,thumbnailUrl");