├── thumbnails ├── check.png ├── cmd.png ├── cross.png ├── info.png ├── meme.png ├── pause.png ├── play.png ├── skip.png ├── stop.png ├── vote.png ├── shuffle.png ├── volume.png └── swizzles │ ├── 0.png │ ├── 1.png │ ├── 2.png │ ├── 3.png │ ├── 4.png │ ├── 5.png │ ├── 6.png │ ├── 7.png │ ├── 8.png │ ├── 9.png │ ├── 10.png │ ├── 11.png │ ├── 12.png │ ├── 13.png │ ├── 14.png │ ├── 15.png │ ├── 16.png │ ├── 17.png │ ├── 18.png │ ├── 19.png │ ├── 20.png │ ├── 21.png │ ├── 22.png │ ├── 23.png │ ├── 24.png │ ├── 25.png │ ├── 26.png │ ├── 27.png │ └── 28.png ├── data └── templates │ ├── thumbnail.blend │ ├── exampleplugin.zip │ ├── outfittemplate.blend │ └── shiptemplate.blend ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── james.properties ├── Dockerfile ├── .gitignore ├── settings.gradle ├── src └── main │ └── java │ └── me │ └── mcofficer │ └── james │ ├── commands │ ├── misc │ │ ├── Dog.java │ │ ├── Birb.java │ │ ├── Cat.java │ │ ├── Translate.java │ │ └── UnixTime.java │ ├── audio │ │ ├── Pause.java │ │ ├── Shuffle.java │ │ ├── Unpause.java │ │ ├── Stop.java │ │ ├── Current.java │ │ ├── Skip.java │ │ ├── Remove.java │ │ ├── Queue.java │ │ ├── Play.java │ │ ├── Loop.java │ │ └── Playlist.java │ ├── info │ │ ├── Ping.java │ │ ├── Info.java │ │ └── Help.java │ ├── lookup │ │ ├── Showdata.java │ │ ├── Commit.java │ │ ├── Showimage.java │ │ ├── Issue.java │ │ ├── Show.java │ │ ├── Lookup.java │ │ ├── ShowCommand.java │ │ └── Swizzle.java │ ├── moderation │ │ ├── Optout.java │ │ ├── Optin.java │ │ ├── Timeout.java │ │ ├── Purge.java │ │ ├── Activity.java │ │ └── Move.java │ ├── Eval.java │ └── creatortools │ │ ├── Template.java │ │ ├── SwizzleImage.java │ │ └── CRConvert.java │ ├── audio │ ├── AudioPlayerSendHandler.java │ ├── TrackScheduler.java │ ├── Playlists.java │ └── Audio.java │ ├── tools │ ├── Translator.java │ ├── ImageSwizzler.java │ └── Lookups.java │ ├── James.java │ └── Util.java ├── .github └── workflows │ ├── docker-image.yml │ └── codeql-analysis.yml ├── .travis.yml ├── README.md ├── gradlew.bat ├── gradlew └── LICENSE /thumbnails/check.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/check.png -------------------------------------------------------------------------------- /thumbnails/cmd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/cmd.png -------------------------------------------------------------------------------- /thumbnails/cross.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/cross.png -------------------------------------------------------------------------------- /thumbnails/info.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/info.png -------------------------------------------------------------------------------- /thumbnails/meme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/meme.png -------------------------------------------------------------------------------- /thumbnails/pause.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/pause.png -------------------------------------------------------------------------------- /thumbnails/play.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/play.png -------------------------------------------------------------------------------- /thumbnails/skip.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/skip.png -------------------------------------------------------------------------------- /thumbnails/stop.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/stop.png -------------------------------------------------------------------------------- /thumbnails/vote.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/vote.png -------------------------------------------------------------------------------- /thumbnails/shuffle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/shuffle.png -------------------------------------------------------------------------------- /thumbnails/volume.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/volume.png -------------------------------------------------------------------------------- /thumbnails/swizzles/0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/0.png -------------------------------------------------------------------------------- /thumbnails/swizzles/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/1.png -------------------------------------------------------------------------------- /thumbnails/swizzles/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/2.png -------------------------------------------------------------------------------- /thumbnails/swizzles/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/3.png -------------------------------------------------------------------------------- /thumbnails/swizzles/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/4.png -------------------------------------------------------------------------------- /thumbnails/swizzles/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/5.png -------------------------------------------------------------------------------- /thumbnails/swizzles/6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/6.png -------------------------------------------------------------------------------- /thumbnails/swizzles/7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/7.png -------------------------------------------------------------------------------- /thumbnails/swizzles/8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/8.png -------------------------------------------------------------------------------- /thumbnails/swizzles/9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/9.png -------------------------------------------------------------------------------- /thumbnails/swizzles/10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/10.png -------------------------------------------------------------------------------- /thumbnails/swizzles/11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/11.png -------------------------------------------------------------------------------- /thumbnails/swizzles/12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/12.png -------------------------------------------------------------------------------- /thumbnails/swizzles/13.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/13.png -------------------------------------------------------------------------------- /thumbnails/swizzles/14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/14.png -------------------------------------------------------------------------------- /thumbnails/swizzles/15.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/15.png -------------------------------------------------------------------------------- /thumbnails/swizzles/16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/16.png -------------------------------------------------------------------------------- /thumbnails/swizzles/17.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/17.png -------------------------------------------------------------------------------- /thumbnails/swizzles/18.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/18.png -------------------------------------------------------------------------------- /thumbnails/swizzles/19.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/19.png -------------------------------------------------------------------------------- /thumbnails/swizzles/20.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/20.png -------------------------------------------------------------------------------- /thumbnails/swizzles/21.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/21.png -------------------------------------------------------------------------------- /thumbnails/swizzles/22.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/22.png -------------------------------------------------------------------------------- /thumbnails/swizzles/23.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/23.png -------------------------------------------------------------------------------- /thumbnails/swizzles/24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/24.png -------------------------------------------------------------------------------- /thumbnails/swizzles/25.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/25.png -------------------------------------------------------------------------------- /thumbnails/swizzles/26.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/26.png -------------------------------------------------------------------------------- /thumbnails/swizzles/27.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/27.png -------------------------------------------------------------------------------- /thumbnails/swizzles/28.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/thumbnails/swizzles/28.png -------------------------------------------------------------------------------- /data/templates/thumbnail.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/data/templates/thumbnail.blend -------------------------------------------------------------------------------- /data/templates/exampleplugin.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/data/templates/exampleplugin.zip -------------------------------------------------------------------------------- /data/templates/outfittemplate.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/data/templates/outfittemplate.blend -------------------------------------------------------------------------------- /data/templates/shiptemplate.blend: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/data/templates/shiptemplate.blend -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /james.properties: -------------------------------------------------------------------------------- 1 | token: 2 | 3 | github: 4 | 5 | # No Case-sensitivity needed. No Spaces! 6 | optinRoles: OTPlus,NotOT,NotES 7 | timeoutRole: Bad Boy/Girl 8 | 9 | ontopicCategories: 360834717530062858,490954007494262794,460557457748394014 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | 2 | FROM eclipse-temurin:17-jdk-alpine as builder 3 | ADD . /app 4 | WORKDIR /app 5 | RUN ./gradlew --no-daemon shadowJar 6 | 7 | FROM eclipse-temurin:17-jre-alpine 8 | COPY data /data 9 | COPY --from=builder /app/build/libs/ES-Bot-2.0-SNAPSHOT-all.jar /bot.jar 10 | CMD ["java", "-jar", "bot.jar"] -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | /build/ 3 | /.gradle/ 4 | /out/ 5 | 6 | # IntelliJ 7 | /.idea/ 8 | *.iml 9 | *.ipr 10 | *.iws 11 | 12 | # Eclipse 13 | .classpath 14 | .project 15 | .settings/ 16 | /bin/ 17 | 18 | # James Auths 19 | james.sh 20 | /gitauth.txt 21 | james.properties 22 | 23 | # James Data 24 | /data/playlists.json 25 | 26 | # Other 27 | hs_err_pid* 28 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This settings file was generated by the Gradle 'init' task. 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * In a single project build this file can be empty or even removed. 6 | * 7 | * Detailed information about configuring a multi-project build in Gradle can be found 8 | * in the user guide at https://docs.gradle.org/3.4.1/userguide/multi_project_builds.html 9 | */ 10 | 11 | /* 12 | // To declare projects as part of a multi-project build use the 'include' method 13 | include 'shared' 14 | include 'api' 15 | include 'services:webservice' 16 | */ 17 | 18 | rootProject.name = 'ES-Bot' 19 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/misc/Dog.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.misc; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | 8 | public class Dog extends Command{ 9 | 10 | public Dog() { 11 | name = "dog"; 12 | help = "Posts a random dog image."; 13 | category = James.misc; 14 | } 15 | 16 | @Override 17 | protected void execute(CommandEvent event) { 18 | event.reply("https://random.dog/" + Util.getContentFromUrl("https://random.dog/woof")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/misc/Birb.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.misc; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | 8 | public class Birb extends Command{ 9 | 10 | public Birb() { 11 | name = "birb"; 12 | help = "Posts a random birb image."; 13 | category = James.misc; 14 | } 15 | 16 | @Override 17 | protected void execute(CommandEvent event) { 18 | event.reply("https://random.birb.pw/img/" + Util.getContentFromUrl("http://random.birb.pw/tweet/")); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/misc/Cat.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.misc; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | import org.json.JSONObject; 8 | 9 | public class Cat extends Command{ 10 | 11 | public Cat() { 12 | name = "cat"; 13 | help = "Posts a random cat image."; 14 | category = James.misc; 15 | } 16 | 17 | @Override 18 | protected void execute(CommandEvent event) { 19 | event.reply(new JSONObject(Util.getContentFromUrl("https://aws.random.cat/meow")).getString("file")); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /.github/workflows/docker-image.yml: -------------------------------------------------------------------------------- 1 | name: docker 2 | 3 | on: 4 | push: 5 | branches: 6 | - "master" 7 | 8 | jobs: 9 | docker: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Login to GitHub Container Registry 13 | uses: docker/login-action@v2 14 | with: 15 | registry: ghcr.io 16 | username: ${{ github.repository_owner }} 17 | password: ${{ secrets.GITHUB_TOKEN }} 18 | - name: Build and push 19 | uses: docker/build-push-action@v4 20 | with: 21 | push: true 22 | tags: | 23 | ghcr.io/endlessskycommunity/endlesssky-discord-bot:${{ github.sha }} 24 | ghcr.io/endlessskycommunity/endlesssky-discord-bot:latest 25 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: oraclejdk11 3 | dist: xenial 4 | 5 | before cache: 6 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 7 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 8 | 9 | cache: 10 | directories: 11 | - $HOME/.gradle/caches/ 12 | - $HOME/.gradle/wrapper/ 13 | 14 | notifications: 15 | email: 16 | on_success: never 17 | on_failure: change 18 | 19 | script: gradle build 20 | 21 | after_success: 22 | - wget https://raw.githubusercontent.com/k3rn31p4nic/travis-ci-discord-webhook/master/send.sh 23 | - chmod +x send.sh 24 | - ./send.sh success $WEBHOOK_URL 25 | after_failure: 26 | - wget https://raw.githubusercontent.com/k3rn31p4nic/travis-ci-discord-webhook/master/send.sh 27 | - chmod +x send.sh 28 | - ./send.sh failure $WEBHOOK_URL 29 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Pause.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.audio.Audio; 7 | 8 | public class Pause extends Command { 9 | 10 | private final Audio audio; 11 | 12 | public Pause(Audio audio) { 13 | name = "pause"; 14 | help = "Pauses playback."; 15 | category = James.audio; 16 | this.audio = audio; 17 | } 18 | 19 | @Override 20 | protected void execute(CommandEvent event) { 21 | if (audio.getVoiceChannel() != null && event.getMember().getVoiceState().getChannel().equals(audio.getVoiceChannel())) 22 | audio.pause(event); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Shuffle.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.audio.Audio; 7 | 8 | public class Shuffle extends Command { 9 | private final Audio audio; 10 | 11 | public Shuffle(Audio audio) { 12 | name = "shuffle"; 13 | help = "Shuffles the AudioPlayer's queue."; 14 | category = James.audio; 15 | this.audio = audio; 16 | } 17 | 18 | @Override 19 | protected void execute(CommandEvent event) { 20 | if (audio.getVoiceChannel() != null && event.getMember().getVoiceState().getChannel().equals(audio.getVoiceChannel())) 21 | audio.shuffle(event); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Unpause.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.audio.Audio; 7 | 8 | public class Unpause extends Command { 9 | 10 | private final Audio audio; 11 | 12 | public Unpause(Audio audio) { 13 | name = "unpause"; 14 | help = "Resumes Playback"; 15 | aliases = new String[]{"resume"}; 16 | category = James.audio; 17 | this.audio = audio; 18 | } 19 | 20 | @Override 21 | protected void execute(CommandEvent event) { 22 | if (audio.getVoiceChannel() != null && event.getMember().getVoiceState().getChannel().equals(audio.getVoiceChannel())) 23 | audio.unpause(event); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Stop.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.audio.Audio; 7 | 8 | public class Stop extends Command { 9 | 10 | private final Audio audio; 11 | 12 | public Stop(Audio audio) { 13 | name = "stop"; 14 | help = "Stops playback and disconnects from the VoiceChannel"; 15 | arguments = ""; 16 | category = James.audio; 17 | this.audio = audio; 18 | } 19 | 20 | @Override 21 | protected void execute(CommandEvent event) { 22 | if (audio.getVoiceChannel() != null && event.getMember().getVoiceState().getChannel().equals(audio.getVoiceChannel())) 23 | audio.stopAndDisconnect(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Current.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.audio.Audio; 7 | 8 | 9 | public class Current extends Command { 10 | 11 | private final Audio audio; 12 | 13 | public Current(Audio audio) { 14 | name = "current"; 15 | help = "Displays the currently playing song."; 16 | aliases = new String[]{"playing"}; 17 | category = James.audio; 18 | this.audio = audio; 19 | } 20 | 21 | @Override 22 | protected void execute(CommandEvent event) { 23 | if (audio.getVoiceChannel() != null && event.getMember().getVoiceState().getChannel().equals(audio.getVoiceChannel())) 24 | audio.announceCurrentTrack(event); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/info/Ping.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.info; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import net.dv8tion.jda.api.EmbedBuilder; 7 | 8 | public class Ping extends Command { 9 | 10 | public Ping() { 11 | name = "ping"; 12 | help = "Displays the time of the bot's last heartbeat."; 13 | category = James.info; 14 | } 15 | 16 | @Override 17 | protected void execute(CommandEvent event) { 18 | event.reply(new EmbedBuilder() 19 | .setTitle("EndlessSky-Discord-Bot", James.GITHUB_URL) 20 | .setDescription("Last Heartbeat took " + event.getJDA().getGatewayPing() + "ms.") 21 | .setColor(event.getGuild().getSelfMember().getColor()) 22 | .build() 23 | ); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/lookup/Showdata.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.lookup; 2 | 3 | import com.jagrosh.jdautilities.command.CommandEvent; 4 | import me.mcofficer.esparser.DataNode; 5 | import me.mcofficer.james.commands.lookup.ShowCommand; 6 | import me.mcofficer.james.James; 7 | import me.mcofficer.james.Util; 8 | import me.mcofficer.james.tools.Lookups; 9 | 10 | import java.util.ArrayList; 11 | import java.util.Arrays; 12 | import java.util.List; 13 | 14 | public class Showdata extends ShowCommand { 15 | 16 | public Showdata(Lookups lookups) { 17 | super(lookups); 18 | name = "showdata"; 19 | help = "Outputs the data associated with ."; 20 | arguments = ""; 21 | category = James.lookup; 22 | } 23 | 24 | protected void reply(DataNode node, CommandEvent event) { 25 | Util.sendInChunks(event.getTextChannel(), lookups.getNodeAsText(node).split("(?=\n)")); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/audio/AudioPlayerSendHandler.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.audio; 2 | 3 | import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; 4 | import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame; 5 | import net.dv8tion.jda.api.audio.AudioSendHandler; 6 | 7 | import java.nio.ByteBuffer; 8 | 9 | public class AudioPlayerSendHandler implements AudioSendHandler { 10 | private final AudioPlayer audioPlayer; 11 | private AudioFrame lastFrame; 12 | 13 | public AudioPlayerSendHandler(AudioPlayer audioPlayer) { 14 | this.audioPlayer = audioPlayer; 15 | } 16 | 17 | @Override 18 | public boolean canProvide() { 19 | lastFrame = audioPlayer.provide(); 20 | return lastFrame != null; 21 | } 22 | 23 | @Override 24 | public ByteBuffer provide20MsAudio() { 25 | return ByteBuffer.wrap(lastFrame.getData()); 26 | } 27 | 28 | @Override 29 | public boolean isOpus() { 30 | return true; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/lookup/Commit.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.lookup; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | 8 | public class Commit extends Command{ 9 | 10 | public Commit() { 11 | name = "commit"; 12 | help = "Gets a commit from the ES repo by it's hash."; 13 | arguments = ""; 14 | category = James.lookup; 15 | } 16 | 17 | @Override 18 | protected void execute(CommandEvent event) { 19 | String url = James.ES_GITHUB_URL + "commit/" + event.getMessage().getContentDisplay().split(" ")[1]; 20 | 21 | int s = Util.getHttpStatus(url); 22 | 23 | if ( (200 <= s && s < 400) || s >= 500) 24 | event.reply(url); 25 | else if(s == 404) 26 | event.reply("Commit not found, make sure you entered a valid commithash."); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/lookup/Showimage.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.lookup; 2 | 3 | import com.jagrosh.jdautilities.command.CommandEvent; 4 | import me.mcofficer.esparser.DataNode; 5 | import me.mcofficer.james.commands.lookup.ShowCommand; 6 | import me.mcofficer.james.James; 7 | import me.mcofficer.james.Util; 8 | import me.mcofficer.james.tools.Lookups; 9 | import net.dv8tion.jda.api.EmbedBuilder; 10 | import net.dv8tion.jda.api.entities.Guild; 11 | import net.dv8tion.jda.api.entities.MessageEmbed; 12 | 13 | import java.util.List; 14 | 15 | public class Showimage extends ShowCommand { 16 | 17 | public Showimage(Lookups lookups) { 18 | super(lookups); 19 | name = "showimage"; 20 | help = "Outputs the image associated with ."; 21 | arguments = ""; 22 | category = James.lookup; 23 | } 24 | 25 | protected void reply(DataNode node, CommandEvent event) { 26 | event.reply(embedImageByNode(node, event.getGuild(), lookups, false).build()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/lookup/Issue.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.lookup; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | 8 | public class Issue extends Command{ 9 | 10 | public Issue() { 11 | name = "issue"; 12 | help = "Gets an issue from the ES repo by it's number."; 13 | arguments = ""; 14 | category = James.lookup; 15 | aliases = new String[]{"pull", "pr"}; 16 | } 17 | 18 | @Override 19 | protected void execute(CommandEvent event) { 20 | String url = James.ES_GITHUB_URL + "issues/" + event.getMessage().getContentDisplay().split(" ")[1]; 21 | 22 | int s = Util.getHttpStatus(url); 23 | 24 | if ( (200 <= s && s < 400) || s >= 500) 25 | event.reply(url); 26 | else if(s == 404) 27 | event.reply("Issue not found, make sure you entered the correct number."); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Skip.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.audio.Audio; 7 | 8 | public class Skip extends Command { 9 | private final Audio audio; 10 | 11 | public Skip(Audio audio) { 12 | name = "skip"; 13 | help = "Skips X songs (defaults to 1)."; 14 | arguments = "X"; 15 | category = James.audio; 16 | this.aliases = new String[]{"next"}; 17 | this.audio = audio; 18 | } 19 | 20 | @Override 21 | protected void execute(CommandEvent event) { 22 | if (audio.getVoiceChannel() != null 23 | && event.getMember().getVoiceState().getChannel().equals(audio.getVoiceChannel()) 24 | && audio.getPlayingTrack() != null) { 25 | int amount = 1; 26 | try { 27 | amount = Integer.parseInt(event.getArgs()); 28 | } 29 | catch (NumberFormatException e) {} 30 | audio.skip(event, amount); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/lookup/Show.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.lookup; 2 | 3 | import com.jagrosh.jdautilities.command.CommandEvent; 4 | import me.mcofficer.esparser.DataNode; 5 | import me.mcofficer.james.commands.lookup.ShowCommand; 6 | import me.mcofficer.james.James; 7 | import me.mcofficer.james.Util; 8 | import me.mcofficer.james.tools.Lookups; 9 | import net.dv8tion.jda.api.EmbedBuilder; 10 | import net.dv8tion.jda.api.MessageBuilder; 11 | import net.dv8tion.jda.api.entities.Guild; 12 | import net.dv8tion.jda.api.entities.Message; 13 | 14 | import java.util.List; 15 | 16 | public class Show extends ShowCommand { 17 | 18 | public Show(Lookups lookups) { 19 | super(lookups); 20 | name = "show"; 21 | help = "Outputs the image and data associated with ."; 22 | arguments = ""; 23 | category = James.lookup; 24 | } 25 | 26 | protected void reply(DataNode node, CommandEvent event) { 27 | Guild guild = event.getGuild(); 28 | EmbedBuilder embedBuilder = embedImageByNode(node, guild, lookups, false); 29 | event.reply(new MessageBuilder() 30 | .setEmbed(embedBuilder.isEmpty() ? null : embedBuilder.build()) // if no image was found, the embed builder cannot be built 31 | .append(Util.sendInChunksReturnLast(event.getTextChannel(), lookups.getNodeAsText(node).split("(?=\n)"))) 32 | .build()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/moderation/Optout.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.moderation; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | import net.dv8tion.jda.api.entities.Role; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.concurrent.TimeUnit; 12 | 13 | public class Optout extends Command { 14 | 15 | private final String[] optinRoles; 16 | 17 | public Optout(String[] optinRoles) { 18 | name = "optout"; 19 | help = "Removes the user from one or more roles X (, Y, Z). A list of free-to-join roles can be found in the rules."; 20 | arguments = "X [Y Z]"; 21 | category = James.moderation; 22 | this.optinRoles = optinRoles; 23 | } 24 | 25 | @Override 26 | protected void execute(CommandEvent event) { 27 | List newRoles = new ArrayList<>(event.getMember().getRoles()); 28 | newRoles.removeAll(Util.getOptinRolesByQuery(event.getArgs(), event.getGuild(), optinRoles)); 29 | event.getGuild().modifyMemberRoles(event.getMember(), newRoles).queue(success1 -> 30 | event.getMessage().addReaction("\uD83D\uDC4C").queue(success2 -> 31 | event.getMessage().delete().queueAfter(20, TimeUnit.SECONDS) 32 | ) 33 | ); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/lookup/Lookup.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.lookup; 2 | 3 | import com.jagrosh.jdautilities.command.CommandEvent; 4 | import me.mcofficer.esparser.DataNode; 5 | import me.mcofficer.james.commands.lookup.ShowCommand; 6 | import me.mcofficer.james.James; 7 | import me.mcofficer.james.Util; 8 | import me.mcofficer.james.tools.Lookups; 9 | import net.dv8tion.jda.api.EmbedBuilder; 10 | import net.dv8tion.jda.api.entities.Guild; 11 | import net.dv8tion.jda.api.entities.MessageEmbed; 12 | 13 | import java.util.List; 14 | 15 | public class Lookup extends ShowCommand { 16 | 17 | public Lookup(Lookups lookups) { 18 | super(lookups); 19 | name = "lookup"; 20 | help = "Outputs the image and description of ."; 21 | arguments = ""; 22 | category = James.lookup; 23 | } 24 | 25 | protected void reply(DataNode node, CommandEvent event) { 26 | Guild guild = event.getGuild(); 27 | EmbedBuilder embedBuilder = embedImageByNode(node, guild, lookups, true); 28 | String description = lookups.getDescription(node); 29 | 30 | if (description == null) 31 | embedBuilder.appendDescription("Couldn't find a description node!"); 32 | else 33 | embedBuilder.setDescription(description); 34 | 35 | //embedBuilder.appendDescription("\n\n" + lookups.getLinks(node)); 36 | 37 | event.reply(embedBuilder.build()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Remove.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.audio.Audio; 7 | 8 | public class Remove extends Command { 9 | private final Audio audio; 10 | 11 | public Remove(Audio audio) { 12 | name = "remove"; 13 | help = "Removes the track at the specified position in the queue."; 14 | arguments = "X"; 15 | category = James.audio; 16 | this.audio = audio; 17 | } 18 | 19 | @Override 20 | protected void execute(CommandEvent event) { 21 | if (audio.getVoiceChannel() != null 22 | && event.getMember().getVoiceState().getChannel().equals(audio.getVoiceChannel()) 23 | && audio.getPlayingTrack() != null) { 24 | int position = 0; 25 | boolean validNumber = true; 26 | try { 27 | position = Integer.parseInt(event.getArgs()); 28 | } 29 | catch (NumberFormatException e) { 30 | validNumber = false; 31 | } 32 | if (!validNumber || position < -1 || position == 0) { 33 | audio.announceInvalidRemove(event); 34 | return; 35 | } 36 | audio.remove(event, position); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Queue.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.audio.Audio; 7 | 8 | import java.util.Arrays; 9 | 10 | public class Queue extends Command { 11 | 12 | private final Audio audio; 13 | 14 | public Queue(Audio audio) { 15 | name = "queue"; 16 | help = "Displays the current Queue or (using `-queue print`) returns a text file containing the Queue and currently playing song."; 17 | category = James.audio; 18 | this.audio = audio; 19 | } 20 | 21 | @Override 22 | protected void execute(CommandEvent event) { 23 | if (audio.getVoiceChannel() != null && event.getMember().getVoiceState().getChannel().equals(audio.getVoiceChannel())) { 24 | String[] args = event.getArgs().split(" "); 25 | 26 | if (args[0].equalsIgnoreCase("print")) { 27 | String fileName = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); 28 | if (fileName.length() == 0) 29 | fileName = "queue.txt"; 30 | else if (!fileName.endsWith(".txt")) 31 | fileName += ".txt"; 32 | audio.sendQueueFile(event, fileName); 33 | } 34 | else 35 | audio.createQueueEmbed(event); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Play.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.audio.Audio; 7 | 8 | import java.io.IOException; 9 | import java.net.URL; 10 | import java.net.URLConnection; 11 | 12 | public class Play extends Command { 13 | 14 | private final Audio audio; 15 | 16 | public Play(Audio audio) { 17 | name = "play"; 18 | help = "Plays a track by it's url, or searches for it by a query"; 19 | arguments = ""; 20 | category = James.audio; 21 | this.audio = audio; 22 | } 23 | 24 | @Override 25 | protected void execute(CommandEvent event) { 26 | if (!event.getGuild().getSelfMember().getVoiceState().inVoiceChannel() || 27 | event.getMember().getVoiceState().getChannel().equals(audio.getVoiceChannel())) { 28 | String query = event.getArgs(); 29 | try { 30 | URL url = new URL(query); 31 | URLConnection conn = url.openConnection(); 32 | conn.connect(); 33 | } catch (IOException e) { // URL is invalid or unreachable 34 | query = "ytsearch:" + query; 35 | } 36 | 37 | audio.connect(event.getMember().getVoiceState().getChannel()); 38 | audio.loadItem(query, event); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Loop.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.audio.Audio; 7 | 8 | public class Loop extends Command { 9 | 10 | private final Audio audio; 11 | 12 | public Loop(Audio audio) { 13 | name = "loop"; 14 | help = "Controls whether or not to loo the current track.\nNo argument returns whether or not looping is currently on.\n`-loop on` will turn looping on if it isn't already.\n`-loop off` will turn looping off if it isn't already."; 15 | category = James.audio; 16 | this.aliases = new String[]{"repeat"}; 17 | this.audio = audio; 18 | } 19 | 20 | @Override 21 | protected void execute(CommandEvent event) { 22 | if (audio.getVoiceChannel() != null 23 | && event.getMember().getVoiceState().getChannel().equals(audio.getVoiceChannel()) 24 | && audio.getPlayingTrack() != null) { 25 | String args = event.getArgs(); 26 | if (args.length() == 0) { 27 | audio.getLoop(event); 28 | } 29 | else { 30 | String arg = args.split(" ")[0]; 31 | if (arg.equals("on")) 32 | audio.setLoop(event, true); 33 | else if (arg.equals("off")) 34 | audio.setLoop(event, false); 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/Eval.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.audio.Playlists; 6 | import me.mcofficer.james.tools.Lookups; 7 | 8 | import javax.script.ScriptEngine; 9 | import javax.script.ScriptEngineManager; 10 | import java.util.Properties; 11 | 12 | public class Eval extends Command { 13 | 14 | private final Lookups lookups; 15 | private final Playlists playlists; 16 | private final Properties config; 17 | 18 | public Eval(Lookups lookups, Playlists playlists, Properties config) { 19 | name = "eval"; 20 | arguments = "code"; 21 | hidden = true; 22 | ownerCommand = true; 23 | this.lookups = lookups; 24 | this.playlists = playlists; 25 | this.config = config; 26 | } 27 | 28 | @Override 29 | protected void execute(CommandEvent event) { 30 | ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn"); 31 | engine.put("jda", event.getJDA()); 32 | engine.put("event", event); 33 | engine.put("guild", event.getGuild()); 34 | engine.put("channel", event.getChannel()); 35 | engine.put("lookups", lookups); 36 | engine.put("playlists", playlists); 37 | engine.put("config", config); 38 | 39 | try { 40 | event.reply("Eval successful:\n```\n" + engine.eval(event.getArgs()) + "\n```"); 41 | } 42 | catch (Exception e) { 43 | e.printStackTrace(); 44 | event.reply("An Exception occured:\n```\n" + e + "\n```"); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/misc/Translate.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.misc; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.tools.Translator; 7 | import net.dv8tion.jda.api.EmbedBuilder; 8 | 9 | import java.io.IOException; 10 | import java.io.PrintWriter; 11 | import java.io.StringWriter; 12 | import java.util.Arrays; 13 | 14 | public class Translate extends Command { 15 | 16 | private final Translator translator; 17 | 18 | public Translate(Translator translator) { 19 | this.translator = translator; 20 | name = "translate"; 21 | help = "Translates a Query Q from a auto-detected source language to another language T."; 22 | arguments = "T Q"; 23 | category = James.misc; 24 | } 25 | 26 | @Override 27 | protected void execute(CommandEvent event) { 28 | String[] args = event.getArgs().split(" "); 29 | String target = args[0]; 30 | String query = String.join(" ", Arrays.copyOfRange(args, 1, args.length)); 31 | 32 | try { 33 | EmbedBuilder embedBuilder = new EmbedBuilder() 34 | .setTitle("Translation requested by " + event.getMember().getEffectiveName()) 35 | .setDescription(translator.translate(null, target, query)); 36 | event.reply(embedBuilder.build()); 37 | } 38 | catch (IOException e) { 39 | StringWriter stringWriter = new StringWriter(); 40 | e.printStackTrace(new PrintWriter(stringWriter)); 41 | event.reply("An error occured:\n```" + stringWriter.toString() + "```"); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/moderation/Optin.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.moderation; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | import net.dv8tion.jda.api.entities.Role; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.concurrent.TimeUnit; 12 | 13 | public class Optin extends Command { 14 | 15 | private final String[] optinRoles; 16 | private final String sTimeoutRole; 17 | 18 | public Optin(String[] optinRoles, String timeoutRole) { 19 | name = "optin"; 20 | help = "Adds the user to one or more roles X (, Y, Z). A list of free-to-join roles can be found in the rules."; 21 | arguments = "X [Y Z]"; 22 | category = James.moderation; 23 | this.optinRoles = optinRoles; 24 | sTimeoutRole = timeoutRole; 25 | } 26 | 27 | @Override 28 | protected void execute(CommandEvent event) { 29 | Role timeoutRole = event.getGuild().getRolesByName(sTimeoutRole, true). get(0); 30 | if (event.getMember().getRoles().contains(timeoutRole)) { 31 | event.reply(Util.getRandomDeniedMessage()); 32 | return; 33 | } 34 | 35 | List newRoles = new ArrayList<>(event.getMember().getRoles()); 36 | newRoles.addAll(Util.getOptinRolesByQuery(event.getArgs(), event.getGuild(), optinRoles)); 37 | event.getGuild().modifyMemberRoles(event.getMember(), newRoles).queue(success1 -> 38 | event.getMessage().addReaction("\uD83D\uDC4C").queue(success2 -> 39 | event.getMessage().delete().queueAfter(20, TimeUnit.SECONDS) 40 | ) 41 | ); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/creatortools/Template.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.creatortools; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import net.dv8tion.jda.api.EmbedBuilder; 7 | 8 | import java.util.HashMap; 9 | 10 | public class Template extends Command { 11 | 12 | private HashMap templates = new HashMap<>() { 13 | { 14 | put("plugin", "exampleplugin.zip"); 15 | put("outfit", "outfittemplate.blend"); 16 | put("ship", "shiptemplate.blend"); 17 | put("thumbnail", "thumbnail.blend"); 18 | }}; 19 | 20 | public Template() { 21 | name = "template"; 22 | help = "Serves a template X for content creators. Available templates are: " 23 | + String.join(", ", templates.keySet()); 24 | category = James.creatorTools; 25 | arguments = "X"; 26 | } 27 | 28 | @Override 29 | protected void execute(CommandEvent event) { 30 | String key = event.getArgs().toLowerCase(); 31 | if (templates.containsKey(key)) { 32 | String url = James.GITHUB_RAW_URL + "data/templates/" + templates.get(key); 33 | event.reply(new EmbedBuilder() 34 | .setTitle(templates.get(key), url) 35 | .setColor(event.getGuild().getSelfMember().getColor()) 36 | .setDescription("Here's your template, served hot and crunchy :)") 37 | .build() 38 | ); 39 | } 40 | else 41 | event.reply(String.format("Which template would you like? I have the following flavours available: %s.", 42 | String.join(", ", templates.keySet()))); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/creatortools/SwizzleImage.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.creatortools; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.tools.ImageSwizzler; 7 | import net.dv8tion.jda.api.entities.Message; 8 | 9 | import java.io.IOException; 10 | import java.util.List; 11 | 12 | public class SwizzleImage extends Command { 13 | 14 | private final ImageSwizzler swizzler = new ImageSwizzler(); 15 | 16 | public SwizzleImage() { 17 | name = "swizzleimage"; 18 | help = "Applies the Swizzle X to the uploaded image[s]. If X is not defined, applies swizzles 1-6."; 19 | arguments = "[X] "; 20 | category = James.creatorTools; 21 | } 22 | 23 | @Override 24 | protected void execute(CommandEvent event) { 25 | List attachments = event.getMessage().getAttachments(); 26 | if (attachments.isEmpty()) 27 | event.reply("Please attach one or more images."); 28 | else 29 | for (Message.Attachment a : attachments) { 30 | if (a.getWidth() > 1000 || a.getHeight() > 1000) { 31 | event.reply(a.getFileName() + " is larger than 1000px."); 32 | continue; 33 | } 34 | 35 | a.retrieveInputStream().thenAccept(inputStream -> { 36 | try { 37 | event.getTextChannel().sendFile(swizzler.swizzle(inputStream, event.getArgs()), "swizzled.png").queue(); 38 | } 39 | catch (IOException e) { 40 | e.printStackTrace(); 41 | } 42 | }); 43 | } 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/lookup/ShowCommand.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.lookup; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.esparser.DataNode; 6 | import me.mcofficer.james.James; 7 | import me.mcofficer.james.Util; 8 | import me.mcofficer.james.tools.Lookups; 9 | import net.dv8tion.jda.api.EmbedBuilder; 10 | import net.dv8tion.jda.api.MessageBuilder; 11 | import net.dv8tion.jda.api.entities.Guild; 12 | import net.dv8tion.jda.api.entities.Message; 13 | 14 | import java.util.List; 15 | 16 | public abstract class ShowCommand extends Command { 17 | 18 | protected final Lookups lookups; 19 | 20 | public ShowCommand(Lookups lookups) { 21 | super(); 22 | this.lookups = lookups; 23 | } 24 | 25 | @Override 26 | protected void execute(CommandEvent event) { 27 | List matches = lookups.getNodesByString(event.getArgs()); 28 | 29 | if (matches.size() < 1) 30 | event.reply("Found no matches for `" + event.getArgs() + "`!"); 31 | else if (matches.size() == 1) 32 | reply(matches.get(0), event); 33 | else 34 | Util.displayNodeSearchResults(matches, event, ((message, integer) -> reply(matches.get(integer - 1), event))); 35 | } 36 | 37 | protected EmbedBuilder embedImageByNode(DataNode node, Guild guild, Lookups lookups, boolean thumbnail) { 38 | String imageToEmbedUrl = lookups.getImageUrl(node, thumbnail); 39 | EmbedBuilder embedBuilder = new EmbedBuilder() 40 | .setColor(guild.getSelfMember().getColor()); 41 | if (imageToEmbedUrl == null) 42 | embedBuilder.appendDescription("Couldn't find an image node!\n\n"); 43 | else 44 | embedBuilder.setImage(imageToEmbedUrl); 45 | return embedBuilder; 46 | } 47 | 48 | protected abstract void reply(DataNode node, CommandEvent event); 49 | 50 | } 51 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [master, ] 6 | pull_request: 7 | # The branches below must be a subset of the branches above 8 | branches: [master] 9 | schedule: 10 | - cron: '0 7 * * 4' 11 | 12 | jobs: 13 | analyse: 14 | name: Analyse 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v2 20 | with: 21 | # We must fetch at least the immediate parents so that if this is 22 | # a pull request then we can checkout the head. 23 | fetch-depth: 2 24 | 25 | # If this run was triggered by a pull request event, then checkout 26 | # the head of the pull request instead of the merge commit. 27 | - run: git checkout HEAD^2 28 | if: ${{ github.event_name == 'pull_request' }} 29 | 30 | - uses: actions/setup-java@v1 31 | with: 32 | java-version: '11' # The JDK version to make available on the path. 33 | java-package: jdk # (jre, jdk, or jdk+fx) - defaults to jdk 34 | architecture: x64 # (x64 or x86) - defaults to x64 35 | 36 | # Initializes the CodeQL tools for scanning. 37 | - name: Initialize CodeQL 38 | uses: github/codeql-action/init@v1 39 | # Override language selection by uncommenting this and choosing your languages 40 | # with: 41 | # languages: go, javascript, csharp, python, cpp, java 42 | 43 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 44 | # If this step fails, then you should remove it and run the build manually (see below) 45 | - name: Autobuild 46 | uses: github/codeql-action/autobuild@v1 47 | 48 | # ℹ️ Command-line programs to run using the OS shell. 49 | # 📚 https://git.io/JvXDl 50 | 51 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 52 | # and modify them (or add more) to build your code if your project 53 | # uses a compiled language 54 | 55 | #- run: | 56 | # make bootstrap 57 | # make release 58 | 59 | - name: Perform CodeQL Analysis 60 | uses: github/codeql-action/analyze@v1 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EndlessSky-Discord-Bot 2 | [![Build Status](https://travis-ci.org/EndlessSkyCommunity/EndlessSky-Discord-Bot.svg?branch=master)](https://travis-ci.org/MCOfficer/EndlessSky-Discord-Bot) 3 | [![GitHub license](https://img.shields.io/github/license/EndlessSkyCommunity/EndlessSky-Discord-Bot)](https://github.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/blob/master/LICENSE) 4 | 5 | Meet James, the Discord Bot made specifically for the Endless Sky Server. 6 | 7 | ## Installation 8 | ### Requirements 9 | - A JDK (Java 11 or better) or Docker 10 | 11 | ### Setup 12 | 1. Clone or fork this repository 13 | 2. Using the Discord API, make a new Bot and save token in `james.properties` (follow [this guide](https://github.com/DV8FromTheWorld/JDA/wiki/3%29-Getting-Started) until "2. Setup JDA Project" to obtain a token) 14 | 3. Acquire a GitHub API Key and save it in `james.properties` 15 | 4. Start James using 16 | - ... your JDK: `./gradlew run` (`gradlew.bat run` on windows) 17 | - ... Docker: `docker run -v /path/to/your/james.properties:/james.properties ghcr.io/endlessskycommunity/endlesssky-discord-bot:latest` (optional: also mount `/data/playlists.json` to preserve custom playlists) 18 | 19 | ## Features 20 | - Displays portions of the Endless Sky data files (Ships & their variants, Outfits, Sprites/Thumbnails, Missions) 21 | - Links to PRs, commits and issues of the Endless Sky repository 22 | - Links to [various](http://endless-sky.7vn.io/) [online](http://bunker.tejat.net/endless-ships/) [resources](https://endlesssky.mcofficer.me/ship_gallery/) 23 | - Basic Moderation Commands (purge and move messages, timeout bad boys/girls) 24 | - Several tools for Plugin Creators, such as various Templates & Infos about the swizzles used by the game 25 | - Some fun commands (random dogs and cats etc.) 26 | - Full Music Player functionality using [lavaplayer](https://github.com/sedmelluq/lavaplayer) 27 | 28 | ## Credit 29 | Original Creator: @Wrzlprnft 30 | 31 | Original Maintainer / Hoster: @Nechochwen-D 32 | 33 | Current Maintainer / Hoster: @MCOfficer 34 | 35 | Contributors / PR Bots: 36 | - @tehhowch 37 | - @warp-core 38 | 39 | 24/7 Development Support: @MinnDevelopment and the JDA Discord Server 40 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/misc/UnixTime.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.misc; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | 7 | public class UnixTime extends Command { 8 | 9 | public UnixTime() { 10 | name = "unix-time"; 11 | help = "Returns the unix time representation of the current time, or the time X units after this time. The unit for the time offset is given as a single, case-insensitive character: 'S' for seconds, 'M' for minutes, 'H' for hours, 'D' for days, 'W' for weeks."; 12 | arguments = "[X [U]]"; 13 | category = James.misc; 14 | } 15 | 16 | @Override 17 | protected void execute(CommandEvent event) { 18 | long unixTime = event.getMessage().getTimeCreated().toEpochSecond(); 19 | unixTime += GetOffset(event); 20 | event.reply(Long.toString(unixTime)); 21 | } 22 | 23 | private static long GetOffset(CommandEvent event) { 24 | String argString = event.getArgs(); 25 | if(argString.isEmpty()) 26 | return 0; 27 | String[] args = argString.split(" "); 28 | long offset = 0; 29 | try { 30 | offset = Long.parseLong(args[0]); 31 | } catch (NumberFormatException e) { 32 | e.printStackTrace(); 33 | event.reply("Failed to parse \"" + args[1] + "\" as Long!"); 34 | return 0; 35 | } 36 | if(args.length > 1) 37 | return offset * GetMultiplier(args[1]); 38 | return offset; 39 | } 40 | 41 | private static int GetMultiplier(String multiplierString) { 42 | if(multiplierString.isEmpty()) 43 | return 1; 44 | char multiplier = multiplierString.toUpperCase().charAt(0); 45 | switch (multiplier) { 46 | case 'S': 47 | return 1; 48 | case 'M': 49 | return 60; 50 | case 'H': 51 | return 60 * 60; 52 | case 'D': 53 | return 24 * 60 * 60; 54 | case 'W': 55 | return 7 * 24 * 60 * 60; 56 | default: 57 | return 1; 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/moderation/Timeout.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.moderation; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | import net.dv8tion.jda.api.Permission; 8 | import net.dv8tion.jda.api.entities.Guild; 9 | import net.dv8tion.jda.api.entities.Member; 10 | import net.dv8tion.jda.api.entities.Role; 11 | 12 | import java.util.List; 13 | 14 | public class Timeout extends Command { 15 | 16 | private final String sTimeoutRole; 17 | 18 | public Timeout(String timeoutRole) { 19 | name = "timeout"; 20 | help = "Sends the Member(s) X [Y, Z] for S seconds to #the-corner. S must always be the last argument."; 21 | arguments = "X [Y Z] S"; 22 | sTimeoutRole = timeoutRole; 23 | category = James.moderation; 24 | } 25 | 26 | @Override 27 | protected void execute(CommandEvent event) { 28 | Role timeoutRole = event.getGuild().getRolesByName(sTimeoutRole, true).get(0); 29 | 30 | if (!event.getMember().hasPermission(Permission.MANAGE_ROLES)) { 31 | event.reply(Util.getRandomDeniedMessage()); 32 | return; 33 | } 34 | 35 | List toTimeout = event.getMessage().getMentionedMembers(); 36 | String[] args = event.getArgs().split(" "); 37 | long time; 38 | try { 39 | time = Long.parseLong(args[toTimeout.size()]); 40 | } catch (NumberFormatException e) { 41 | e.printStackTrace(); 42 | event.reply("Failed to parse \"" + args[toTimeout.size()] + "\" as Long!"); 43 | return; 44 | } 45 | 46 | for (Member member : toTimeout) { 47 | String onCommand = String.format("Sent Member %s to the corner for %s seconds (Ordered by `%s#%s`).", 48 | member.getAsMention(), time, event.getMember().getUser().getName(), event.getMember().getUser().getDiscriminator()); 49 | String onRelease = "Released Member " + member.getAsMention() + " from the corner."; 50 | Util.replaceRolesTemporarily(timeoutRole, time, member, onCommand, onRelease); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/tools/Translator.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.tools; 2 | 3 | import okhttp3.*; 4 | import org.json.JSONArray; 5 | import org.json.JSONObject; 6 | 7 | import javax.annotation.Nullable; 8 | import java.io.IOException; 9 | 10 | public class Translator { 11 | 12 | private OkHttpClient okHttpClient = new OkHttpClient(); 13 | 14 | public Translator(OkHttpClient okHttpClient) { 15 | this.okHttpClient = okHttpClient; 16 | } 17 | 18 | /** 19 | * @param sourceLang The source language, defaults to "auto" 20 | * @param targetLang The target language, defaults to "en" 21 | * @param query The text to be translated 22 | * @return The translated text. 23 | */ 24 | public String translate(@Nullable String sourceLang, @Nullable String targetLang, String query) throws IOException{ 25 | if (sourceLang == null) 26 | sourceLang = "auto"; 27 | if (targetLang == null) 28 | targetLang = "en"; 29 | 30 | HttpUrl url = new HttpUrl.Builder() 31 | .scheme("https") 32 | .host("translate.googleapis.com") 33 | .addPathSegments("translate_a/single") 34 | .addQueryParameter("client", "gtx") 35 | .addQueryParameter("sl", sourceLang) 36 | .addQueryParameter("tl", targetLang) 37 | .addQueryParameter("dt", "t") 38 | .addQueryParameter("q", query) 39 | .build(); 40 | 41 | Request request = new Request.Builder() 42 | .url(url) 43 | .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0") 44 | .get() 45 | .build(); 46 | 47 | Response response = okHttpClient.newCall(request).execute(); 48 | JSONArray json = new JSONArray(response.body().string()); 49 | 50 | StringBuilder stringBuilder = new StringBuilder(); 51 | for (Object snippet : json.getJSONArray(0)) // Why use a raw iterator here, org.json? WHY? 52 | if (snippet instanceof JSONArray) 53 | stringBuilder.append(((JSONArray) snippet).getString(0)); 54 | 55 | return stringBuilder.toString(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/info/Info.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.info; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | import net.dv8tion.jda.api.EmbedBuilder; 8 | import org.json.JSONArray; 9 | import org.json.JSONObject; 10 | 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | 14 | public class Info extends Command { 15 | 16 | private String commit; 17 | 18 | public Info(String githubToken) { 19 | name = "info"; 20 | help = "Shows information about the bot."; 21 | category = James.info; 22 | getInfo(githubToken); 23 | } 24 | 25 | @Override 26 | protected void execute(CommandEvent event) { 27 | String description = String.format( 28 | "- **Author:** Maximilian Korber\n" + 29 | "- **Language**: Java\n" + 30 | "- **Utilized Libraries:** JDA, JDA-Utilities, ESParser-java\n" + 31 | "- **Maintainers:** M\\*C\\*O, tehhowch\n" + 32 | "\n" + 33 | "**Latest Commit:** %s\n" + 34 | "\n" + 35 | "[View known issues and feature requests](%s)", 36 | commit, James.GITHUB_URL + "issues/"); 37 | 38 | EmbedBuilder builder = new EmbedBuilder() 39 | .setTitle("EndlessSky-Discord-Bot", James.GITHUB_URL) 40 | .setColor(event.getGuild().getSelfMember().getColor()) 41 | .setDescription(description); 42 | event.reply(builder.build()); 43 | } 44 | 45 | private void getInfo(String githubToken) { 46 | Map headers = new HashMap<>(); 47 | headers.put("Authorization", "token "+ githubToken); 48 | JSONObject latest = new JSONArray(Util.getContentFromUrl("https://api.github.com/repos/EndlessSkyCommunity/EndlessSky-Discord-Bot/commits", headers)) 49 | .getJSONObject(0); 50 | commit = String.format("[%s](%s): %s", latest.getString("sha").substring(0, 7), latest.getString("html_url"), 51 | latest.getJSONObject("commit").getString("message")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/creatortools/CRConvert.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.creatortools; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import net.dv8tion.jda.api.MessageBuilder; 7 | 8 | import java.lang.Math; 9 | import java.util.Arrays; 10 | 11 | public class CRConvert extends Command { 12 | 13 | public CRConvert() { 14 | name = "crconvert"; 15 | help = "Converts between combat ratings and points.\n`-crconvert cr X` where X is the raw points score returns the corresponding combat rating.\n`-crconvert points X` where X is the combat rating returns the minimum number of points to achieve that rating.\nX must be an integer."; 16 | category = James.creatorTools; 17 | arguments = "[cr|points] X"; 18 | } 19 | 20 | @Override 21 | protected void execute(CommandEvent event) { 22 | String args = event.getArgs(); 23 | if (args == null) { 24 | invalidInputPrintHelp(event); 25 | } 26 | String[] argsList = args.split(" "); 27 | if (argsList.length < 2) { 28 | invalidInputPrintHelp(event); 29 | return; 30 | } 31 | String X = argsList[1]; 32 | int value = 0; 33 | try { 34 | value = Integer.parseInt(X); 35 | } 36 | catch (NumberFormatException e) { 37 | invalidInputPrintHelp(event); 38 | return; 39 | } 40 | if (argsList[0].equals("cr")) { 41 | int rating = getRatingFromPoints(value); 42 | event.reply(new MessageBuilder().append(String.format("Combat points %s gives a rating of %s.", value, rating)).build()); 43 | } 44 | else if (argsList[0].equals("points")) { 45 | int points = getPointsFromRating(value); 46 | event.reply(new MessageBuilder().append(String.format("Combat rating %s requires %s combat points.", value, points)).build()); 47 | } 48 | } 49 | 50 | private int getRatingFromPoints(int points) { 51 | return (int)Math.log(points); 52 | } 53 | 54 | private int getPointsFromRating(int rating) { 55 | return (int)Math.ceil(Math.exp(rating)); 56 | } 57 | 58 | private void invalidInputPrintHelp(CommandEvent event) { 59 | event.reply(new MessageBuilder().append("That's not how this works.\n").append(help).build()); 60 | } 61 | 62 | 63 | } -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/moderation/Purge.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.moderation; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | import net.dv8tion.jda.api.EmbedBuilder; 8 | import net.dv8tion.jda.api.Permission; 9 | import net.dv8tion.jda.api.entities.TextChannel; 10 | 11 | public class Purge extends Command { 12 | 13 | public Purge() { 14 | name = "purge"; 15 | help = "Purges the last X messages from the current channel."; 16 | arguments = "X"; 17 | category = James.moderation; 18 | } 19 | 20 | @Override 21 | protected void execute(CommandEvent event) { 22 | if (event.getMember().hasPermission(event.getTextChannel(), Permission.MESSAGE_MANAGE)) { 23 | try { 24 | int amount = Integer.parseInt(event.getArgs()); 25 | if (amount < 2 || 100 < amount) 26 | throw new NumberFormatException(); 27 | TextChannel channel = event.getTextChannel(); 28 | 29 | event.getMessage().delete().queue( a -> 30 | channel.getHistory().retrievePast(amount).queue( messages -> { 31 | try { 32 | channel.deleteMessages(messages).queue(b -> { 33 | EmbedBuilder embedBuilder = new EmbedBuilder() 34 | .setTitle("Moderation") 35 | .setColor(event.getGuild().getSelfMember().getColor()) 36 | .setDescription("Spaced " + messages.size() + " Messages! Who's next?!"); 37 | event.reply(embedBuilder.build()); 38 | Util.log(event.getGuild(), String.format("Purged %s messages in %s, ordered by `%s`.", 39 | amount, channel.getAsMention(), event.getMember().getEffectiveName())); 40 | }); 41 | } 42 | catch(IllegalArgumentException e) { 43 | event.reply(event.getMember().getAsMention() + " One or more messages are older than 2 weeks and cannot be deleted."); 44 | } 45 | }) 46 | ); 47 | } 48 | catch (NumberFormatException e) { 49 | event.reply("'" + event.getArgs() + "' is not a valid integer between 2 and 100!"); 50 | } 51 | } 52 | else { 53 | event.reply(Util.getRandomDeniedMessage()); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/audio/TrackScheduler.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.audio; 2 | 3 | import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; 4 | import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter; 5 | import com.sedmelluq.discord.lavaplayer.track.AudioTrack; 6 | import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason; 7 | 8 | import javax.annotation.CheckForNull; 9 | import java.util.Collections; 10 | import java.util.LinkedList; 11 | 12 | public class TrackScheduler extends AudioEventAdapter { 13 | 14 | private final AudioPlayer player; 15 | private final LinkedList queue = new LinkedList<>(); 16 | 17 | private boolean looping; 18 | 19 | public TrackScheduler(AudioPlayer player) { 20 | this.player = player; 21 | player.addListener(this); 22 | looping = false; 23 | } 24 | 25 | /** 26 | * Shuffles the Queue. 27 | */ 28 | public void shuffle() { 29 | Collections.shuffle(queue); 30 | } 31 | 32 | /** 33 | * Removes the first song in the {@link #queue} and plays it. Stops playback if the queue is empty. 34 | */ 35 | public void skip() { 36 | play(queue.poll()); 37 | } 38 | 39 | public AudioTrack remove(int position) { 40 | if (position > getQueueSize()) 41 | return null; 42 | return queue.remove(position - 1); 43 | } 44 | 45 | /** 46 | * Plays a track immediately. You probably want to use {@link #enqueue(AudioTrack)} instead. 47 | * @param track 48 | */ 49 | public void play(AudioTrack track) { 50 | player.playTrack(track); 51 | } 52 | 53 | /** Plays a track if nothing is playing currently, otherwise adds it to the {@link #queue}. 54 | * @param track 55 | */ 56 | public void enqueue(AudioTrack track) { 57 | if(!player.startTrack(track, true)) //something is currently playing 58 | queue.offer(track); 59 | } 60 | 61 | @Override 62 | public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) { 63 | if(endReason.mayStartNext) { 64 | if (looping) 65 | play(track.makeClone()); 66 | else 67 | skip(); 68 | } 69 | } 70 | 71 | /** 72 | * Stops Playback and clears the {@link #queue}. 73 | */ 74 | public void stop() { 75 | player.stopTrack(); 76 | looping = false; 77 | queue.clear(); 78 | } 79 | 80 | public void setLooping(boolean loop) { 81 | looping = loop; 82 | } 83 | 84 | public boolean getLooping() { 85 | return looping; 86 | } 87 | 88 | public int getQueueSize() { 89 | return queue.size(); 90 | } 91 | 92 | public LinkedList getQueue() { 93 | return queue; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/audio/Playlists.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.audio; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | import org.json.JSONTokener; 6 | 7 | import java.io.FileReader; 8 | import java.io.IOException; 9 | import java.nio.charset.Charset; 10 | import java.nio.charset.StandardCharsets; 11 | import java.nio.file.Files; 12 | import java.nio.file.Path; 13 | import java.nio.file.Paths; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | public class Playlists { 19 | 20 | private Path playlistsFile; 21 | 22 | public Playlists() { 23 | playlistsFile = Paths.get("data/playlists.json"); 24 | 25 | try { 26 | if (!playlistsFile.toFile().exists()) 27 | writeFile("{}"); 28 | } 29 | catch (IOException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | 34 | public boolean isOwner(String key, String ownerId) throws IOException, JSONException { 35 | return readFile().getJSONObject(key).getString("ownerId").equals(ownerId); 36 | } 37 | 38 | public boolean keyExists(String key) throws IOException { 39 | return readFile().has(key); 40 | } 41 | 42 | public String getPlaylistUrl(String key) throws IOException, JSONException { 43 | return readFile().getJSONObject(key).getString("url"); 44 | } 45 | 46 | public Map.Entry getPlaylistInfo(String key) throws IOException, JSONException { 47 | JSONObject json = readFile().getJSONObject(key); 48 | return Map.entry(json.getString("url"), json.getString("ownerId")); 49 | } 50 | 51 | public void changePlaylistUrl(String key, String url) throws IOException { 52 | JSONObject json = readFile(); 53 | json.getJSONObject(key).put("url", url); 54 | writeFile(json); 55 | } 56 | 57 | public void removePlaylist(String key) throws IOException { 58 | JSONObject json = readFile(); 59 | json.remove(key); 60 | writeFile(json); 61 | } 62 | 63 | public List getKeys() throws IOException { 64 | ArrayList keys = new ArrayList<>(); 65 | readFile().keys().forEachRemaining(keys::add); 66 | return keys; 67 | } 68 | 69 | public void addPlaylist(String key, String url, String ownerId) throws IOException { 70 | JSONObject json = readFile(); 71 | JSONObject playlist = new JSONObject() 72 | .put("url", url) 73 | .put("ownerId", ownerId); 74 | json.put(key, playlist); 75 | writeFile(json); 76 | } 77 | 78 | private JSONObject readFile() throws IOException { 79 | JSONTokener jsonTokener = new JSONTokener(new FileReader(playlistsFile.toFile())); 80 | return new JSONObject(jsonTokener); 81 | } 82 | 83 | private void writeFile(JSONObject json) throws IOException { 84 | writeFile(json.toString(2)); 85 | } 86 | 87 | private void writeFile(String string) throws IOException { 88 | Files.write(playlistsFile, string.getBytes(StandardCharsets.UTF_8)); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/moderation/Activity.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.moderation; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | import net.dv8tion.jda.api.entities.*; 8 | 9 | import java.time.Instant; 10 | import java.time.OffsetDateTime; 11 | import java.time.ZoneId; 12 | import java.util.*; 13 | import java.util.concurrent.ExecutionException; 14 | import java.util.stream.Collectors; 15 | 16 | public class Activity extends Command { 17 | 18 | private final String[] ontopicCategories; 19 | 20 | public Activity(String[] ontopicCategories) { 21 | name = "activity"; 22 | arguments = "[member]"; 23 | help = "Provides stats about Member Activity over the last 2 weeks in ontopic channels. For Mods only, has 30 seconds cooldown."; 24 | cooldown = 30; 25 | category = James.moderation; 26 | this.ontopicCategories = ontopicCategories; 27 | } 28 | 29 | @Override 30 | protected void execute(CommandEvent event) { 31 | // only allowed for Mods 32 | if (event.getMember().getRoles().get(0).getPosition() < event.getGuild().getSelfMember().getRoles().get(0).getPosition()) { 33 | event.reply(Util.getRandomDeniedMessage()); 34 | return; 35 | } 36 | 37 | OffsetDateTime cutoffTime = OffsetDateTime.ofInstant(Instant.now().minusSeconds(1209600L), ZoneId.systemDefault()); 38 | 39 | List messages = new ArrayList<>(); 40 | for (String catId : ontopicCategories) { 41 | net.dv8tion.jda.api.entities.Category category = event.getJDA().getCategoryById(catId); 42 | if (category != null) { 43 | for (TextChannel channel : category.getTextChannels()) { 44 | try { 45 | messages.addAll( 46 | channel 47 | .getIterableHistory() 48 | .takeUntilAsync(msg -> msg.getTimeCreated().isBefore(cutoffTime)) 49 | .get() 50 | ); 51 | } catch (InterruptedException | ExecutionException e) { 52 | e.printStackTrace(); 53 | } 54 | } 55 | } else { 56 | event.reply("Failed to find category with ID " + catId + ", results will be inaccurate. Please contact my hoster."); 57 | } 58 | } 59 | 60 | Map results = new HashMap<>(); 61 | for (Message msg : messages) { 62 | if (msg.getMember() != null) { 63 | results.merge(msg.getMember(), 1, Integer::sum); 64 | } 65 | } 66 | 67 | try { 68 | Member query = event.getMessage().getMentionedMembers().get(0); 69 | if (results.containsKey(query)) { 70 | event.reply(query.getEffectiveName() + " sent " + results.getOrDefault(query, 0) + " Messages in Ontopic-Channels over the last 2 weeks."); 71 | } 72 | } catch (IndexOutOfBoundsException oob) { 73 | int maxLength = results 74 | .keySet() 75 | .stream() 76 | .max(Comparator.comparingInt(o -> o.getEffectiveName().length())) 77 | .orElseThrow() 78 | .getEffectiveName() 79 | .length(); 80 | String formatString = "%-" + (maxLength + 5) + "s%04d\n"; 81 | 82 | List tableLines = results.entrySet().stream() 83 | .sorted(Comparator.comparingInt(Map.Entry::getValue)) 84 | .map(e -> String.format(formatString, e.getKey().getEffectiveName(), e.getValue())) 85 | .collect(Collectors.toList()); 86 | Util.sendInChunks(event.getTextChannel(), tableLines, "```", "```"); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/info/Help.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.info; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandClient; 5 | import com.jagrosh.jdautilities.command.CommandEvent; 6 | import me.mcofficer.james.James; 7 | import net.dv8tion.jda.api.EmbedBuilder; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.function.Consumer; 12 | 13 | public class Help implements Consumer { 14 | 15 | private final List commands; 16 | private final String prefix; 17 | private EmbedBuilder helpEmbedBuilder; 18 | 19 | public Help(CommandClient client) { 20 | commands = client.getCommands(); 21 | prefix = client.getPrefix(); 22 | helpEmbedBuilder = createHelpEmbedBuilder(); 23 | } 24 | 25 | @Override 26 | public void accept(CommandEvent e) { 27 | if (e.getArgs().isEmpty()) 28 | e.reply(helpEmbedBuilder 29 | .setColor(e.getGuild().getSelfMember().getColor()) 30 | .build()); 31 | else { 32 | String args = e.getArgs().startsWith("-") ? e.getArgs().substring(1) : e.getArgs(); 33 | // TODO: Check for aliases 34 | for (Command c : commands) 35 | if (c.getName().equalsIgnoreCase(args)) { 36 | e.reply(createHelpEmbedBuilder(c) 37 | .setColor(e.getGuild().getSelfMember().getColor()) 38 | .build()); 39 | break; 40 | } 41 | } 42 | } 43 | 44 | /** 45 | * @return an EmbedBuilder containing a help text for all Commands defined in {@link #commands}. 46 | */ 47 | private EmbedBuilder createHelpEmbedBuilder() { 48 | List categories = new ArrayList<>(); 49 | for (Command c : commands) 50 | if (c.getCategory() != null && !categories.contains(c.getCategory())) 51 | categories.add(c.getCategory()); 52 | 53 | EmbedBuilder embedBuilder = new EmbedBuilder(); 54 | 55 | for (Command.Category category : categories) { 56 | StringBuilder sb = new StringBuilder(); 57 | for (Command c : commands) { 58 | if (c.isHidden() || !c.getCategory().equals(category)) 59 | continue; 60 | 61 | sb.append(String.format("`%s%s %s`", prefix, c.getName(), c.getArguments() == null ? "" : c.getArguments())); 62 | if (c.getAliases().length > 0) { 63 | sb.append(" ("); 64 | for (String alias : c.getAliases()) 65 | sb.append(String.format("`%s%s`, ", prefix, alias)); 66 | sb.delete(sb.length() - 2, sb.length()); 67 | sb.append(")"); 68 | } 69 | sb.append("\n"); 70 | } 71 | embedBuilder.addField(category.getName(), sb.toString(), true); 72 | } 73 | 74 | embedBuilder.setTitle("EndlessSky-Discord-Bot", James.GITHUB_URL); 75 | 76 | return embedBuilder; 77 | } 78 | 79 | /** 80 | * @param c A Command. 81 | * @return An EmbedBuilder containing the help text for c. 82 | */ 83 | private EmbedBuilder createHelpEmbedBuilder(Command c) { 84 | EmbedBuilder embedBuilder = new EmbedBuilder() 85 | .setTitle("EndlessSky-Discord-Bot", James.GITHUB_URL) 86 | .setDescription(String.format("`%s %s`\n", c.getName(), c.getArguments() == null ? "" : c.getArguments())) 87 | .appendDescription(c.getHelp() + "\n"); 88 | 89 | if (c.getAliases().length > 0) { 90 | embedBuilder.appendDescription("**Aliases: **"); 91 | StringBuilder sb = new StringBuilder(); 92 | for (String alias : c.getAliases()) 93 | sb.append(String.format("`%s`, ", alias)); 94 | sb.delete(sb.length() - 2, sb.length()); 95 | embedBuilder.appendDescription(sb); 96 | } 97 | 98 | return embedBuilder; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/lookup/Swizzle.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.lookup; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.esparser.DataNode; 6 | import me.mcofficer.james.James; 7 | import me.mcofficer.james.tools.Lookups; 8 | import net.dv8tion.jda.api.EmbedBuilder; 9 | 10 | import java.util.HashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | public class Swizzle extends Command { 15 | 16 | private HashMap>> vectors = new HashMap<>(); 17 | private final Lookups lookups; 18 | 19 | 20 | public Swizzle(Lookups lookups) { 21 | name = "swizzle"; 22 | help = "Displays information about a swizzle X (can range from 0-28)"; 23 | arguments = "X"; 24 | category = James.lookup; 25 | this.lookups = lookups; 26 | initVectors(); 27 | } 28 | 29 | private void initVectors() { 30 | String[] vectorStrings = new String[]{ 31 | "{GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, // 0 red + yellow markings (republic)", 32 | "{GL_RED, GL_BLUE, GL_GREEN, GL_ALPHA}, // 1 red + magenta markings", 33 | "{GL_GREEN, GL_RED, GL_BLUE, GL_ALPHA}, // 2 green + yellow (free worlds)", 34 | "{GL_BLUE, GL_RED, GL_GREEN, GL_ALPHA}, // 3 green + cyan", 35 | "{GL_GREEN, GL_BLUE, GL_RED, GL_ALPHA}, // 4 blue + magenta (syndicate)", 36 | "{GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA}, // 5 blue + cyan (merchant)", 37 | "{GL_GREEN, GL_BLUE, GL_BLUE, GL_ALPHA}, // 6 red and black (pirate)", 38 | "{GL_RED, GL_BLUE, GL_BLUE, GL_ALPHA}, // 7 pure red", 39 | "{GL_RED, GL_GREEN, GL_GREEN, GL_ALPHA}, // 8 faded red", 40 | "{GL_BLUE, GL_BLUE, GL_BLUE, GL_ALPHA}, // 9 pure black", 41 | "{GL_GREEN, GL_GREEN, GL_GREEN, GL_ALPHA}, // 10 faded black", 42 | "{GL_RED, GL_RED, GL_RED, GL_ALPHA}, // 11 pure white", 43 | "{GL_BLUE, GL_BLUE, GL_GREEN, GL_ALPHA}, // 12 darkened blue", 44 | "{GL_BLUE, GL_BLUE, GL_RED, GL_ALPHA}, // 13 pure blue", 45 | "{GL_GREEN, GL_GREEN, GL_RED, GL_ALPHA}, // 14 faded blue", 46 | "{GL_BLUE, GL_GREEN, GL_GREEN, GL_ALPHA}, // 15 darkened cyan", 47 | "{GL_BLUE, GL_RED, GL_RED, GL_ALPHA}, // 16 pure cyan", 48 | "{GL_GREEN, GL_RED, GL_RED, GL_ALPHA}, // 17 faded cyan", 49 | "{GL_BLUE, GL_GREEN, GL_BLUE, GL_ALPHA}, // 18 darkened green", 50 | "{GL_BLUE, GL_RED, GL_BLUE, GL_ALPHA}, // 19 pure green", 51 | "{GL_GREEN, GL_RED, GL_GREEN, GL_ALPHA}, // 20 faded green", 52 | "{GL_GREEN, GL_GREEN, GL_BLUE, GL_ALPHA}, // 21 darkened yellow", 53 | "{GL_RED, GL_RED, GL_BLUE, GL_ALPHA}, // 22 pure yellow", 54 | "{GL_RED, GL_RED, GL_GREEN, GL_ALPHA}, // 23 faded yellow", 55 | "{GL_GREEN, GL_BLUE, GL_GREEN, GL_ALPHA}, // 24 darkened magenta", 56 | "{GL_RED, GL_BLUE, GL_RED, GL_ALPHA}, // 25 pure magenta", 57 | "{GL_RED, GL_GREEN, GL_RED, GL_ALPHA}, // 26 faded magenta", 58 | "{GL_BLUE, GL_ZERO, GL_ZERO, GL_ALPHA}, // 27 red only (cloaked)", 59 | "{GL_ZERO, GL_ZERO, GL_ZERO, GL_ALPHA} // 28 black only (outline)" 60 | }; 61 | 62 | for (int i = 0; i < vectorStrings.length; i++) 63 | vectors.put(i, Map.entry(vectorStrings[i], lookups.getGovernmentsBySwizzle(i))); 64 | } 65 | 66 | @Override 67 | protected void execute(CommandEvent event) { 68 | int swizzle = Integer.parseInt(event.getArgs()); 69 | 70 | if (!vectors.containsKey(swizzle)) 71 | event.reply("Swizzle not found!"); 72 | else { 73 | Map.Entry> vector = vectors.get(swizzle); 74 | StringBuilder govStringBuilder = new StringBuilder(); 75 | for (DataNode node : vector.getValue()) 76 | govStringBuilder.append("\n\u2022 ") 77 | .append(String.join(" ", node.getTokens().subList(1, node.getTokens().size()))); 78 | 79 | EmbedBuilder embedBuilder = new EmbedBuilder() 80 | .setTitle("EndlessSky-Discord-Bot", James.GITHUB_URL) 81 | .setColor(event.getGuild().getSelfMember().getColor()) 82 | .setDescription(String.format("**Swizzle Vector:**\n```%s```\n\n**Governments using this swizzle:**\n%s", 83 | vector.getKey(), govStringBuilder.toString())) 84 | .setThumbnail(James.GITHUB_RAW_URL + "thumbnails/swizzles/" + swizzle + ".png"); 85 | event.reply(embedBuilder.build()); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/moderation/Move.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.moderation; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | import net.dv8tion.jda.api.EmbedBuilder; 8 | import net.dv8tion.jda.api.Permission; 9 | import net.dv8tion.jda.api.entities.Member; 10 | import net.dv8tion.jda.api.entities.Message; 11 | import net.dv8tion.jda.api.entities.TextChannel; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | 15 | import java.time.format.DateTimeFormatter; 16 | import java.util.*; 17 | import java.util.concurrent.CompletableFuture; 18 | 19 | public class Move extends Command { 20 | 21 | private static final Logger log = LoggerFactory.getLogger(Move.class); 22 | 23 | public Move() { 24 | name = "move"; 25 | help = "Moves X messages to Channel C. Removes Embeds in the process."; 26 | arguments = "C X"; 27 | aliases = new String[]{"wormhole"}; 28 | category = James.moderation; 29 | } 30 | 31 | @Override 32 | protected void execute(CommandEvent event) { 33 | String[] args = event.getArgs().split(" "); 34 | int amount; 35 | TextChannel dest = event.getMessage().getMentionedChannels().get(0); 36 | try { 37 | amount = Integer.parseInt(args[1]); 38 | } catch (NumberFormatException e) { 39 | e.printStackTrace(); 40 | event.reply("Failed to parse \"" + args[1] + "\"as Integer!"); 41 | return; 42 | } 43 | 44 | if (event.getMember().hasPermission(event.getTextChannel(), Permission.MESSAGE_MANAGE) 45 | && event.getMember().hasPermission(dest, Permission.MESSAGE_WRITE) 46 | && event.getGuild().getSelfMember().hasPermission(dest, Permission.MESSAGE_WRITE)) { 47 | event.getMessage().delete().complete(); 48 | 49 | // Use a lambda to asynchronously perform this request: 50 | event.getTextChannel().getIterableHistory().takeAsync(amount).thenAccept(toDelete -> { 51 | if (toDelete.isEmpty()) 52 | return; 53 | LinkedList toMove = new LinkedList<>(); 54 | for (Message m : toDelete) { 55 | String authorName = Optional.ofNullable(m.getMember()).map(Member::getEffectiveName).orElse("unknown author"); 56 | String content = m.getContentStripped().trim(); 57 | if (content.isEmpty()) 58 | continue; 59 | toMove.addFirst(m.getTimeCreated() 60 | .format(DateTimeFormatter.ISO_INSTANT).substring(11, 19) 61 | + "Z " + authorName + ": " + content + "\n" 62 | ); 63 | } 64 | 65 | // Remove the messages from the original channel 66 | for (CompletableFuture future : event.getChannel().purgeMessages(toDelete)) 67 | { 68 | future.exceptionally(t -> { 69 | t.printStackTrace(); 70 | return null; 71 | }); 72 | } 73 | 74 | EmbedBuilder replyEmbed = new EmbedBuilder(); 75 | replyEmbed.setDescription(dest.getAsMention()); 76 | replyEmbed.setThumbnail("https://cdn.discordapp.com/emojis/344684586904584202.png"); 77 | replyEmbed.appendDescription("\n(" + toMove.size() + " messages await)"); 78 | if (toDelete.size() - toMove.size() > 0) 79 | replyEmbed.appendDescription("\n(Some embeds were eaten)"); 80 | event.getTextChannel().sendMessage(replyEmbed.build()).queue(); 81 | 82 | // Transport the message content to the new channel. 83 | if (!toMove.isEmpty()) 84 | Util.sendInChunks(dest, toMove, "Incoming wormhole content from " + event.getTextChannel().getAsMention() + ":\n```", "```"); 85 | 86 | // Log the move in mod-log. 87 | String report = "Moved " + toMove.size() + 88 | " messages from " + event.getTextChannel().getAsMention() + 89 | " to " + dest.getAsMention() + ", ordered by `" + 90 | event.getMember().getEffectiveName() + "`."; 91 | Util.log(event.getGuild(), report); 92 | }).exceptionally(e -> { 93 | log.error("Failed to to move messages", e); 94 | return null; 95 | } 96 | ); 97 | } else 98 | event.reply(Util.getRandomDeniedMessage()); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/commands/audio/Playlist.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.commands.audio; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandEvent; 5 | import me.mcofficer.james.James; 6 | import me.mcofficer.james.Util; 7 | import me.mcofficer.james.audio.Audio; 8 | import me.mcofficer.james.audio.Playlists; 9 | import net.dv8tion.jda.api.EmbedBuilder; 10 | 11 | import java.io.IOException; 12 | import java.util.Arrays; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | public class Playlist extends Command { 17 | 18 | private Audio audio; 19 | private Playlists playlists; 20 | 21 | public Playlist(Audio audio, Playlists playlists) { 22 | name = "playlist"; 23 | help = "Saves URLs as playlists, to be quickly accessible. Each playlist is associated with a key.\n" + 24 | "`-playlist X` plays a playlist X.\n" + 25 | "`-playlist list` shows all available playlists.\n" + 26 | "`-playlist save X U` saves the URL U under the key X.\n" + 27 | "`-playlist delete X` deletes the playlist X, if you are the owner of X.\n" + 28 | "`-playlist edit X U` updates the playlist X with the URL U.\n" + 29 | "`-playlist info X` Shows the URL and Owner of the playlist X.\n"; 30 | arguments = "[list|save|delete|edit|info] [X [U]]"; 31 | category = James.audio; 32 | 33 | this.audio = audio; 34 | this.playlists = playlists; 35 | } 36 | 37 | @Override 38 | protected void execute(CommandEvent event) { 39 | if (event.getArgs().length() == 0) 40 | return; 41 | 42 | String[] args = event.getArgs().split(" "); 43 | String arg = args[0]; 44 | String[] revisedArgs = Arrays.copyOfRange(args, 1, args.length); 45 | 46 | try { 47 | if (arg.equals("list")) 48 | list(event); 49 | else if (arg.equals("save")) 50 | save(event, revisedArgs); 51 | else if (arg.equals("delete")) 52 | delete(event, revisedArgs); 53 | else if (arg.equals("edit")) 54 | edit(event, revisedArgs); 55 | else if (arg.equals("info")) 56 | info(event, revisedArgs); 57 | else 58 | play(event); 59 | } 60 | catch (IOException e) { 61 | e.printStackTrace(); 62 | } 63 | 64 | } 65 | 66 | private void play(CommandEvent event) throws IOException { 67 | audio.connect(event.getMember().getVoiceState().getChannel()); 68 | audio.loadItem(playlists.getPlaylistUrl(event.getArgs()), event); 69 | } 70 | 71 | private void list(CommandEvent event) throws IOException { 72 | List keys = playlists.getKeys(); 73 | StringBuilder stringBuilder = new StringBuilder(); 74 | 75 | for (String key : keys) 76 | stringBuilder.append(String.format("\n\u2022 `%s`\n", key)); 77 | 78 | EmbedBuilder embedBuider = new EmbedBuilder() 79 | .setTitle("EndlessSky-Discord-Bot", James.GITHUB_URL) 80 | .setColor(event.getGuild().getSelfMember().getColor()) 81 | .setDescription(String.format("Playlists: %s\n%s", keys.size(), stringBuilder.toString())); 82 | event.reply(embedBuider.build()); 83 | } 84 | 85 | private void save(CommandEvent event, String[] args) throws IOException { 86 | if (playlists.keyExists(args[0])) 87 | event.reply("A playlist with key `" + args[0] + "` already exists!"); 88 | else { 89 | playlists.addPlaylist(args[0], args[1], event.getAuthor().getId()); 90 | event.reply("Saved playlist as `" + args[0] + "`"); 91 | } 92 | } 93 | 94 | private void delete(CommandEvent event, String[] args) throws IOException { 95 | if (!playlists.isOwner(args[0], event.getAuthor().getId())) 96 | event.reply("You're not the Owner of this playlist!"); 97 | else { 98 | playlists.removePlaylist(args[0]); 99 | event.reply("Playlist `" + args[0] + "` has been removed."); 100 | } 101 | } 102 | 103 | private void edit(CommandEvent event, String[] args) throws IOException { 104 | if (!playlists.isOwner(args[0], event.getAuthor().getId())) 105 | event.reply("You're not the Owner of this playlist!"); 106 | else { 107 | playlists.changePlaylistUrl(args[0], args[1]); 108 | event.reply("Playlist `" + args[0] + "` has been edited."); 109 | } 110 | } 111 | 112 | private void info(CommandEvent event, String[] args) throws IOException { 113 | Map.Entry info = playlists.getPlaylistInfo(args[0]); 114 | event.getJDA().retrieveUserById(info.getValue()).queue(user -> { 115 | EmbedBuilder embedBuilder = new EmbedBuilder() 116 | .setTitle("EndlessSky-Discord-Bot", James.GITHUB_URL) 117 | .setColor(event.getGuild().getSelfMember().getColor()) 118 | .setDescription(String.format("Key: `%s`\nURL: %s\n Owner: %s", args[0], info.getKey(), user.getAsMention())); 119 | event.reply(embedBuilder.build()); 120 | }); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/tools/ImageSwizzler.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.tools; 2 | 3 | import javax.annotation.Nullable; 4 | import javax.imageio.IIOImage; 5 | import javax.imageio.ImageIO; 6 | import javax.imageio.ImageWriteParam; 7 | import javax.imageio.ImageWriter; 8 | import javax.imageio.metadata.IIOMetadata; 9 | import javax.imageio.stream.MemoryCacheImageOutputStream; 10 | import java.awt.Graphics2D; 11 | import java.awt.image.BufferedImage; 12 | import java.io.ByteArrayInputStream; 13 | import java.io.ByteArrayOutputStream; 14 | import java.io.IOException; 15 | import java.io.InputStream; 16 | 17 | public class ImageSwizzler { 18 | 19 | private final static String[] swizzles = { 20 | "rbg", 21 | "grb", 22 | "brg", 23 | "gbr", 24 | "bgr", 25 | "gbb", 26 | "rbb", 27 | "rgg", 28 | "bbb", 29 | "ggg", 30 | "rrr", 31 | "bbg", 32 | "bbr", 33 | "ggr", 34 | "bgg", 35 | "brr", 36 | "grr", 37 | "bgb", 38 | "brb", 39 | "grg", 40 | "ggb", 41 | "rrb", 42 | "rrg", 43 | "gbg", 44 | "rbr", 45 | "rgr" 46 | }; 47 | 48 | /** 49 | * Swizzles (swaps color channels) an image. 50 | * If arg is defined, swaps an image's color channels in accordance to arg's value in {@link #swizzles}. 51 | * Else returns an image with 2x height and 3x width, containing images of all color channel swaps defined in swizzles. 52 | * @param imgStream The image. 53 | * @param arg The number of the swizzle that should be applied. 54 | * @return A .png-encoded image. 55 | * @throws IOException if an error occurs during reading or writing. 56 | * Blame {@link ImageIO#read(InputStream)} or {@link ImageWriter#write(IIOMetadata, IIOImage, ImageWriteParam)}. 57 | */ 58 | public InputStream swizzle(InputStream imgStream, @Nullable String arg) throws IOException { 59 | BufferedImage img = ImageIO.read(imgStream); 60 | int[][][] channels = splitByChannels(img); 61 | 62 | BufferedImage output; 63 | if(arg == null || arg.isEmpty()) 64 | output = createAllSwizzles(img, channels); 65 | else 66 | output = createSwizzledImage(img.getWidth(), img.getHeight(), channels, swizzles[Integer.parseInt(arg) - 1]); 67 | 68 | ByteArrayOutputStream os = new ByteArrayOutputStream(); 69 | ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next(); 70 | writer.setOutput(new MemoryCacheImageOutputStream(os)); 71 | 72 | ImageWriteParam param = writer.getDefaultWriteParam(); 73 | if(param.canWriteCompressed()) { 74 | param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); 75 | param.setCompressionQuality(0.5f); 76 | } 77 | 78 | writer.write(null, new IIOImage(output, null, null), param); 79 | writer.dispose(); 80 | 81 | return new ByteArrayInputStream(os.toByteArray()); 82 | } 83 | 84 | private BufferedImage createSwizzledImage(int width, int height, int[][][] channels, String swizzle) { 85 | 86 | int channelOne = getChannelIndexByChar(swizzle.charAt(0)); 87 | int channelTwo = getChannelIndexByChar(swizzle.charAt(1)); 88 | int channelThree = getChannelIndexByChar(swizzle.charAt(2)); 89 | 90 | BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 91 | for(int col = 0; col < width; col++) { 92 | for (int row = 0; row < height; row++) { 93 | int a = channels[0][col][row]; 94 | int r = channels[channelOne][col][row]; 95 | int g = channels[channelTwo][col][row]; 96 | int b = channels[channelThree][col][row]; 97 | int pixel = (a << 24) | (r << 16) | (g << 8) | b; 98 | img.setRGB(col, row, pixel); 99 | } 100 | } 101 | return img; 102 | } 103 | 104 | private int getChannelIndexByChar(char c) { 105 | if(c == 'r') return 1; 106 | else if(c == 'g') return 2; 107 | else if(c == 'b') return 3; 108 | else return 0; 109 | } 110 | 111 | private int[][][] splitByChannels(BufferedImage img) { 112 | int width = img.getWidth(); 113 | int height = img.getHeight(); 114 | /* An array that contains 4 channels, with each channel being represented by matrix of integers. 115 | the channel order is ARGB. */ 116 | int[][][] channels = new int[4][width][height]; 117 | for(int col = 0; col < width; col++) { 118 | for (int row = 0; row < height; row++) { 119 | int rgb = img.getRGB(col, row); 120 | channels[0][col][row] = (rgb >> 24) & 0x000000FF; 121 | channels[1][col][row] = (rgb >> 16) & 0x000000FF; 122 | channels[2][col][row] = (rgb >> 8) & 0x000000FF; 123 | channels[3][col][row] = (rgb) & 0x000000FF; 124 | } 125 | } 126 | return channels; 127 | } 128 | 129 | private BufferedImage createAllSwizzles(BufferedImage img, int[][][] channels) { 130 | int width = img.getWidth(); 131 | int height = img.getHeight(); 132 | 133 | BufferedImage[] images = new BufferedImage[6]; 134 | for (int i = 0; i < 6; i++) 135 | images[i] = createSwizzledImage(width, height, channels, swizzles[i]); 136 | 137 | BufferedImage output = new BufferedImage(width * 3, height * 2, BufferedImage.TYPE_INT_ARGB); 138 | Graphics2D g2d = output.createGraphics(); 139 | g2d.drawImage(images[0], null, 0, 0); 140 | g2d.drawImage(images[1], null, width, 0); 141 | g2d.drawImage(images[2], null, width * 2, 0); 142 | g2d.drawImage(images[3], null, 0, height); 143 | g2d.drawImage(images[4], null, width, height); 144 | g2d.drawImage(images[5], null, width * 2, height); 145 | g2d.dispose(); 146 | 147 | return output; 148 | } 149 | } -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/James.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james; 2 | 3 | import com.jagrosh.jdautilities.command.Command; 4 | import com.jagrosh.jdautilities.command.CommandClientBuilder; 5 | import com.jagrosh.jdautilities.commons.waiter.EventWaiter; 6 | import me.mcofficer.esparser.DataFile; 7 | import me.mcofficer.james.audio.Audio; 8 | import me.mcofficer.james.audio.Playlists; 9 | import me.mcofficer.james.commands.*; 10 | import me.mcofficer.james.commands.audio.*; 11 | import me.mcofficer.james.commands.creatortools.*; 12 | import me.mcofficer.james.commands.misc.Birb; 13 | import me.mcofficer.james.commands.misc.Cat; 14 | import me.mcofficer.james.commands.misc.Dog; 15 | import me.mcofficer.james.commands.info.*; 16 | import me.mcofficer.james.commands.lookup.*; 17 | import me.mcofficer.james.commands.misc.Translate; 18 | import me.mcofficer.james.commands.misc.UnixTime; 19 | import me.mcofficer.james.commands.moderation.*; 20 | import me.mcofficer.james.tools.Lookups; 21 | import me.mcofficer.james.tools.Translator; 22 | import net.dv8tion.jda.api.JDA; 23 | import net.dv8tion.jda.api.JDABuilder; 24 | import net.dv8tion.jda.api.requests.GatewayIntent; 25 | import net.dv8tion.jda.api.utils.ChunkingFilter; 26 | import okhttp3.OkHttpClient; 27 | import org.slf4j.Logger; 28 | import org.slf4j.LoggerFactory; 29 | 30 | import javax.security.auth.login.LoginException; 31 | import java.io.File; 32 | import java.io.FileReader; 33 | import java.io.IOException; 34 | import java.util.ArrayList; 35 | import java.util.Properties; 36 | 37 | public class James { 38 | 39 | public final static String GITHUB_URL = "https://github.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/"; 40 | public final static String GITHUB_RAW_URL = "https://raw.githubusercontent.com/EndlessSkyCommunity/EndlessSky-Discord-Bot/master/"; 41 | public final static String ES_GITHUB_URL = "https://github.com/endless-sky/endless-sky/"; 42 | 43 | public final static EventWaiter eventWaiter = new EventWaiter(); 44 | private final OkHttpClient okHttpClient = new OkHttpClient(); 45 | private static Properties cfg = new Properties(); 46 | 47 | public static Command.Category audio = new Command.Category("Audio"); 48 | public static Command.Category misc = new Command.Category("Misc"); 49 | public static Command.Category info = new Command.Category("Info"); 50 | public static Command.Category creatorTools = new Command.Category("Creator Tools"); 51 | public static Command.Category lookup = new Command.Category("Lookup"); 52 | public static Command.Category moderation = new Command.Category("Moderation"); 53 | 54 | private Logger log = LoggerFactory.getLogger(James.class); 55 | 56 | public static void main(String[] args) { 57 | try { 58 | cfg.load(new FileReader("james.properties")); 59 | } 60 | catch (IOException e) { 61 | e.printStackTrace(); 62 | } 63 | 64 | try { 65 | new James(cfg); 66 | } 67 | catch (LoginException | InterruptedException | IOException e) { 68 | e.printStackTrace(); 69 | } 70 | } 71 | 72 | private James(Properties cfg) throws LoginException, InterruptedException, IOException { 73 | CommandClientBuilder clientBuilder = new CommandClientBuilder() 74 | .setPrefix("-") 75 | .setActivity(net.dv8tion.jda.api.entities.Activity.listening("-help")) 76 | .setOwnerId("177733454824341505"); // yep, that's me 77 | addCommands(clientBuilder, cfg.getProperty("github")); 78 | 79 | clientBuilder.setHelpConsumer(new Help(clientBuilder.build())); // this HAS to be done after adding all Commands! 80 | 81 | JDA jda = JDABuilder.createDefault(cfg.getProperty("token")) 82 | .setChunkingFilter(ChunkingFilter.ALL) 83 | .enableIntents(GatewayIntent.GUILD_MEMBERS) 84 | .addEventListeners(clientBuilder.build(), eventWaiter) 85 | .build() 86 | .awaitReady(); 87 | } 88 | 89 | private void addCommands(CommandClientBuilder builder, String githubToken) throws IOException { 90 | log.info("Downloading game data..."); 91 | ArrayList paths = Util.fetchGameData(githubToken); 92 | ArrayList dataFiles = new ArrayList<>(); 93 | for (File path : paths) 94 | dataFiles.add(new DataFile(path.getAbsolutePath())); 95 | 96 | log.info("Fetching image paths..."); 97 | ArrayList imagePaths = Util.get1xImagePaths(githubToken); 98 | Lookups lookups = new Lookups(okHttpClient, dataFiles, imagePaths); 99 | log.info("Lookups instantiated"); 100 | 101 | log.info("Starting background thread to fetch hdpi image paths..."); 102 | new Thread(() -> { 103 | lookups.setImagePaths(Util.get2xImagePaths(imagePaths)); 104 | log.info("Hdpi image paths fetched successfully."); 105 | }).start(); 106 | 107 | Audio audio = new Audio(); 108 | Playlists playlists= new Playlists(); 109 | 110 | String[] optinRoles = cfg.getProperty("optinRoles").split(","); 111 | String[] ontopicCategories = cfg.getProperty("ontopicCategories").split(","); 112 | 113 | builder.addCommands( 114 | new Eval(lookups, playlists, cfg), 115 | new Play(audio), new Stop(audio), new Loop(audio), new Skip(audio), new Remove(audio), new Shuffle(audio), new Current(audio), 116 | new Pause(audio), new Unpause(audio), new Queue(audio), new Playlist(audio, playlists), 117 | new SwizzleImage(), new Template(), new CRConvert(), 118 | new Cat(), new Dog(), new Birb(), new Translate(new Translator(okHttpClient)), new UnixTime(), 119 | new Info(githubToken), new Ping(), 120 | new Issue(), new Commit(), new Showdata(lookups), new Showimage(lookups), new Show(lookups), new Lookup(lookups), new Swizzle(lookups), 121 | new Purge(), new Optin(optinRoles, cfg.getProperty("timeoutRole")), new Optout(optinRoles), 122 | new Timeout(cfg.getProperty("timeoutRole")), new Activity(ontopicCategories), new Move() 123 | ); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/tools/Lookups.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.tools; 2 | 3 | import me.mcofficer.esparser.DataFile; 4 | import me.mcofficer.esparser.DataNode; 5 | import me.mcofficer.james.Util; 6 | import okhttp3.*; 7 | import org.json.JSONException; 8 | import org.json.JSONObject; 9 | import org.simmetrics.StringMetric; 10 | import org.simmetrics.metrics.StringMetrics; 11 | 12 | import javax.annotation.CheckForNull; 13 | import javax.annotation.CheckReturnValue; 14 | import java.io.IOException; 15 | import java.io.UnsupportedEncodingException; 16 | import java.nio.charset.StandardCharsets; 17 | import java.util.*; 18 | import java.util.stream.Collectors; 19 | 20 | public class Lookups { 21 | 22 | private OkHttpClient okHttpClient; 23 | private final ArrayList dataFiles; 24 | private ArrayList imagePaths; 25 | 26 | public Lookups(OkHttpClient okhttpClient, ArrayList dataFiles, ArrayList imagePaths) { 27 | this.okHttpClient = okhttpClient; 28 | this.dataFiles = dataFiles; 29 | this.imagePaths = imagePaths; 30 | } 31 | 32 | /** 33 | * Compiles online references for the given Node, which can be used in Embeds. 34 | * @param node The Node in question. 35 | * @return A String containing markdown links (may be empty) 36 | */ 37 | public String getLinks(DataNode node) { 38 | StringBuilder stringBuilder = new StringBuilder(); 39 | 40 | String nodeName = String.join(" ", node.getTokens().subList(1, node.getTokens().size())); 41 | String nodeType = node.getTokens().get(0); 42 | 43 | // endless-sky.7vn.io/endless-ships/ 44 | if (nodeType.equals("outfit")) { 45 | String url = "http://endless-sky.7vn.io/outfits/" + nodeName.replace(" ", "-").toLowerCase(); 46 | if (Util.getHttpStatus(url) == 200) 47 | stringBuilder.append(String.format("[\"%s\" on 7vn.io](%s)\n", nodeName, url)); 48 | } 49 | else if (nodeType.equals("ship")) { 50 | String url = "http://endless-sky.7vn.io/ships/" + nodeName.replace(" ", "-").toLowerCase(); 51 | if (Util.getHttpStatus(url) == 200) 52 | stringBuilder.append(String.format("[\"%s\" on 7vn.io](%s)\n", nodeName, url)); 53 | } 54 | 55 | // bunker.tejat.net/endless-ships | bunker.tejat.net/endless-outfits 56 | if (nodeType.equals("outfit")) { 57 | String url = "https://bunker.tejat.net/endless-outfits/" 58 | + nodeName.replace(" ", "_").replace("-", "_").toLowerCase() + ".html"; 59 | if (Util.getHttpStatus(url) == 200) 60 | stringBuilder.append(String.format("[\"%s\" on bunker.tejat.net](%s)\n", nodeName, url)); 61 | } 62 | else if (nodeType.equals("ship")) { 63 | String url = "https://bunker.tejat.net/endless-ships/" 64 | + nodeName.replace(" ", "_").replace("-", "_").toLowerCase() + ".html"; 65 | if (Util.getHttpStatus(url) == 200) 66 | stringBuilder.append(String.format("[\"%s\" on bunker.tejat.net](%s)\n", nodeName, url)); 67 | } 68 | 69 | // endlesssky.mcofficer.me/ship_gallery/ 70 | if (nodeType.equals("ship")) { 71 | String base_url = "https://endlesssky.mcofficer.me/ship_gallery/"; 72 | String file = "assets/" + nodeName.toLowerCase().replace(" ", "%20") + ".json"; 73 | if (Util.getHttpStatus(base_url + file) == 200) 74 | stringBuilder.append(String.format("[View the %s model in 3D](%swebplayer.html?load=%s)\n", nodeName, base_url, file)); 75 | } 76 | 77 | // endlesssky.mcofficer.me/assets/ 78 | for (String link : getAssetsUrls(node)) 79 | stringBuilder.append(String.format("[%s](%s)\n", link.substring(link.lastIndexOf('/') + 1).replace("%20", " "), link)); 80 | 81 | // TODO: endless-sky.wikia.com 82 | 83 | return stringBuilder.toString(); 84 | } 85 | 86 | /** 87 | * Attempts to fetch the source files corresponding with the DataNode node from endlesssky.mcofficer.me/assets/ 88 | * @param node 89 | * @return A possibly-empty list of download URLs. 90 | */ 91 | @CheckReturnValue 92 | private List getAssetsUrls(DataNode node) { 93 | String baseUrl = "https://endlesssky.mcofficer.me/"; 94 | String nodeType = node.getTokens().get(0); 95 | String nodeName = String.join(" ", node.getTokens().subList(1, node.getTokens().size())); 96 | List returnUrls = new ArrayList<>(); 97 | 98 | String dir; 99 | if (nodeType.equals("ship")) 100 | dir = "ships"; 101 | else if (nodeType.equals("outfit")) 102 | dir = "outfits"; 103 | else if (nodeType.equals("projectile")) 104 | dir = "projectiles"; 105 | else 106 | return returnUrls; 107 | 108 | String query = String.format("{ \"action\": \"get\", \"search\": { \"href\": \"/\",\"pattern\": \"%s\", \"ignorecase\": true } }", nodeName); 109 | RequestBody body = RequestBody.create(MediaType.get("application/json"), query); 110 | Request request = new Request.Builder() 111 | .url(baseUrl + "assets/?") 112 | .post(body) 113 | .build(); 114 | try (Response response = okHttpClient.newCall(request).execute()) { 115 | JSONObject json = new JSONObject(response.body().string()); 116 | for (Object result : json.getJSONArray("search")) 117 | if (result instanceof JSONObject) { // sigh 118 | String url = baseUrl + ((JSONObject) result).getString("href"); 119 | String[] urlSegments = url.split("/"); 120 | if (urlSegments[urlSegments.length - 2].equals(dir)) 121 | returnUrls.add(url); 122 | } 123 | } 124 | catch (IOException | JSONException e) { 125 | e.printStackTrace(); 126 | } 127 | 128 | return returnUrls; 129 | } 130 | 131 | /** 132 | * Searches through all DataNodes and returns any that
133 | * a) are of the type "government" and
134 | * b) have a subnode of the type "swizzle", whose value matches the swizzle parameter. 135 | * @param swizzle an Integer 136 | * @return A List of DataNodes 137 | */ 138 | public List getGovernmentsBySwizzle(int swizzle) { 139 | List governments = new ArrayList<>(); 140 | for (DataFile file : dataFiles) 141 | for (DataNode node : file.getNodes()) 142 | if (node.getTokens().get(0).equals("government")) 143 | for (DataNode child : node.getChildren()) 144 | if (child.getTokens().get(0).equals("swizzle") && child.getTokens().get(1).equals(String.valueOf(swizzle))) 145 | governments.add(node); 146 | return governments; 147 | } 148 | 149 | /** Searches through the datafiles and returns 10 or less Nodes matching the query. 150 | * @param query 151 | * @return A possibly empty List of Nodes. 152 | */ 153 | @CheckReturnValue 154 | public List getNodesByString(String query) { 155 | Map matches = new HashMap<>(); 156 | for (DataFile file : dataFiles) { 157 | for (DataNode node : file.getNodes()) { 158 | StringMetric metric = StringMetrics.needlemanWunch(); 159 | String tokens = String.join(" ", node.getTokens()).trim(); 160 | matches.put(node, metric.compare(query.toLowerCase(), tokens.toLowerCase())); 161 | } 162 | } 163 | // Sort in descending order & limit to 10 results 164 | return matches.entrySet().stream() 165 | .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) 166 | .limit(10) 167 | .map(Map.Entry::getKey) 168 | .collect(Collectors.toList()); 169 | } 170 | 171 | public String getNodeAsText(DataNode node) { 172 | return printNodeRecursive(node); 173 | } 174 | 175 | private String printNodeRecursive(DataNode node) { 176 | StringBuilder sb = new StringBuilder(); 177 | sb.append("\n") 178 | .append(String.join(" ", node.getTokens()).trim()); 179 | for(DataNode child : node.getChildren()) 180 | sb.append("\t\t") 181 | .append(printNodeRecursive(child).replace("\n", "\n\t")); 182 | return sb.toString(); 183 | } 184 | 185 | /** Gets a description and image from a Node. 186 | * @param node 187 | * @return A String[] possibly containing null. 188 | */ 189 | @CheckReturnValue 190 | public String[] getLookupByNode(DataNode node) { 191 | return new String[]{getImageUrl(node, true), getDescription(node)}; 192 | } 193 | 194 | /** Gets the description of a Node. 195 | * @param node 196 | * @return A String or null. 197 | */ 198 | @CheckForNull 199 | public String getDescription(DataNode node) { 200 | DataNode descNode = getDescriptionChildNode(node); 201 | if (descNode == null) 202 | return null; 203 | return String.join(" ", descNode.getTokens().subList(1, descNode.getTokens().size())); 204 | } 205 | 206 | /** Tries to get an Image URL from the Node node. If thumbnail is true, tries to get a thumbnail (instead of a sprite/landscape/...). 207 | * @param node 208 | * @param thumbnail 209 | * @return A String or null. 210 | */ 211 | @CheckForNull 212 | public String getImageUrl(DataNode node, boolean thumbnail) { 213 | DataNode imageNode = getImageChildNode(node, thumbnail); 214 | if (imageNode == null) 215 | return null; 216 | String path = String.join(" ", imageNode.getTokens().subList(1, imageNode.getTokens().size())); 217 | String bestMatch = null; 218 | try { 219 | // Find the shortest possible image url containing `path` 220 | for (String imagePath : imagePaths) { 221 | String decoded = java.net.URLDecoder.decode(imagePath, StandardCharsets.UTF_8.name()); 222 | if (decoded.contains(path) && 223 | (bestMatch == null ? Integer.MAX_VALUE : bestMatch.substring(bestMatch.lastIndexOf('/')).length()) 224 | > imagePath.substring(imagePath.lastIndexOf('/')).length()) 225 | bestMatch = imagePath; 226 | } 227 | } 228 | catch (UnsupportedEncodingException e) { //Should never happen since UTF-8 is from StandardCharsets 229 | e.printStackTrace(); 230 | } 231 | return bestMatch; 232 | } 233 | 234 | /** Searches a Node for a description Subnode. 235 | * @param node 236 | * @return The Subnode containing the description. 237 | */ 238 | @CheckForNull 239 | private DataNode getDescriptionChildNode(DataNode node) { 240 | for (DataNode child : node.getChildren()) { 241 | String identifier = child.getTokens().get(0); 242 | if (identifier.equals("description")) 243 | return child; 244 | } 245 | return null; 246 | } 247 | 248 | /** Searches a Node for an image Subnode. If thumbnail is true, tries to get a thumbnail, otherwise sprite takes priority. 249 | * @param node 250 | * @param thumbnail 251 | * @return The Subnode containing the relative image path. 252 | */ 253 | @CheckForNull 254 | private DataNode getImageChildNode(DataNode node, boolean thumbnail) { 255 | DataNode imageNode = null; 256 | 257 | if (thumbnail) 258 | imageNode = getThumbnailChildNode(node); 259 | if (imageNode != null) 260 | return imageNode; 261 | 262 | for (DataNode child : node.getChildren()) { 263 | String identifier = child.getTokens().get(0); 264 | if (identifier.equals("sprite") || identifier.equals("landscape")) 265 | return child; 266 | } 267 | 268 | // No need to search for a thumbnail twice 269 | if (!thumbnail) 270 | return getThumbnailChildNode(node); 271 | return null; 272 | } 273 | 274 | /** Searches a Node for an image Subnode of the type thumbnail. 275 | * If you want to fallback to sprites/landscapes if no thumbnail exists, use {@link #getImageChildNode(DataNode, boolean)}. 276 | * @param node 277 | * @return The Subnode containing the relative image path. 278 | */ 279 | @CheckForNull 280 | private DataNode getThumbnailChildNode(DataNode node) { 281 | for (DataNode child : node.getChildren()) 282 | if (child.getTokens().get(0).equals("thumbnail")) 283 | return child; 284 | return null; 285 | } 286 | 287 | public ArrayList getImagePaths() { 288 | return imagePaths; 289 | } 290 | 291 | public void setImagePaths(ArrayList imagePaths) { 292 | this.imagePaths = imagePaths; 293 | } 294 | 295 | public ArrayList getDataFiles() { 296 | return dataFiles; 297 | } 298 | } 299 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/audio/Audio.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james.audio; 2 | 3 | import com.jagrosh.jdautilities.command.CommandEvent; 4 | import com.jagrosh.jdautilities.menu.Paginator; 5 | import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler; 6 | import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; 7 | import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; 8 | import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; 9 | import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; 10 | import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; 11 | import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; 12 | import com.sedmelluq.discord.lavaplayer.track.AudioTrack; 13 | import me.mcofficer.james.James; 14 | import me.mcofficer.james.Util; 15 | import net.dv8tion.jda.api.EmbedBuilder; 16 | import net.dv8tion.jda.api.entities.Guild; 17 | import net.dv8tion.jda.api.entities.VoiceChannel; 18 | import net.dv8tion.jda.api.managers.AudioManager; 19 | 20 | import javax.annotation.CheckForNull; 21 | import java.io.ByteArrayInputStream; 22 | import java.nio.charset.StandardCharsets; 23 | import java.util.ArrayList; 24 | import java.util.LinkedList; 25 | import java.util.concurrent.TimeUnit; 26 | 27 | public class Audio { 28 | 29 | private final AudioPlayerManager playerManager = new DefaultAudioPlayerManager(); 30 | private final AudioPlayer player; 31 | private final AudioPlayerSendHandler audioPlayerSendHandler; 32 | private final TrackScheduler trackScheduler; 33 | private AudioManager audioManager; 34 | 35 | public Audio() { 36 | AudioSourceManagers.registerRemoteSources(playerManager); 37 | player = playerManager.createPlayer(); 38 | 39 | trackScheduler = new TrackScheduler(player); 40 | audioPlayerSendHandler = new AudioPlayerSendHandler(player); 41 | } 42 | 43 | /** Connects to bot to a VoiceChannel. Silently fails if the bot is already connected. 44 | * @param voiceChannel 45 | */ 46 | public void connect(VoiceChannel voiceChannel) { 47 | if (audioManager == null || !audioManager.isConnected()) { 48 | audioManager = voiceChannel.getGuild().getAudioManager(); 49 | audioManager.openAudioConnection(voiceChannel); 50 | audioManager.setSendingHandler(audioPlayerSendHandler); 51 | } 52 | } 53 | 54 | /** 55 | * Stops Playback, clears the Queue and disconnects from the VoiceChannel. 56 | */ 57 | public void stopAndDisconnect() { 58 | trackScheduler.stop(); 59 | audioManager.closeAudioConnection(); 60 | } 61 | 62 | /** 63 | * Attempts to load a track/playlist that matches the identifier. 64 | * If successful, enqueues the item and calls {@link #announceTrack(AudioTrack, CommandEvent)} 65 | * or {@link #announcePlaylist(AudioPlaylist, CommandEvent)} respectively. 66 | * @param identifier 67 | * @param event 68 | */ 69 | public void loadItem(String identifier, CommandEvent event) { 70 | playerManager.loadItem(identifier, new AudioLoadResultHandler() { 71 | @Override 72 | public void trackLoaded(AudioTrack track) { 73 | trackScheduler.enqueue(track); 74 | announceTrack(track, event); 75 | } 76 | 77 | @Override 78 | public void playlistLoaded(AudioPlaylist playlist) { 79 | if (playlist.isSearchResult()) { 80 | AudioTrack track = playlist.getTracks().get(0); 81 | trackScheduler.enqueue(track); 82 | announceTrack(track, event); 83 | } 84 | else { 85 | playlist.getTracks().forEach(trackScheduler::enqueue); 86 | announcePlaylist(playlist, event); 87 | } 88 | } 89 | 90 | @Override 91 | public void noMatches() { 92 | 93 | } 94 | 95 | @Override 96 | public void loadFailed(FriendlyException exception) { 97 | 98 | } 99 | }); 100 | } 101 | 102 | /** 103 | * @param guild 104 | * @return an EmbedBuilder with title and color set. 105 | */ 106 | private EmbedBuilder createEmbedTemplate(Guild guild) { 107 | return new EmbedBuilder() 108 | .setTitle("Audio-Player", James.GITHUB_URL) 109 | .setColor(guild.getSelfMember().getColor()); 110 | } 111 | 112 | /** 113 | * Announces that a new Track has been enqueued. 114 | * @param track 115 | * @param event 116 | */ 117 | private void announceTrack(AudioTrack track, CommandEvent event) { 118 | EmbedBuilder embedBuilder = createEmbedTemplate(event.getGuild()) 119 | .setDescription( 120 | String.format("Queueing `%s` [\uD83D\uDD17](%s)\n(requested by %s)", 121 | track.getInfo().title, track.getInfo().uri, event.getMember().getAsMention()) 122 | ) 123 | .setThumbnail(getThumbnail(track)); 124 | event.reply(embedBuilder.build()); 125 | } 126 | 127 | /** 128 | * Announces that a new Playlist has been enqueued. 129 | * @param playlist 130 | * @param event 131 | */ 132 | private void announcePlaylist(AudioPlaylist playlist, CommandEvent event) { 133 | EmbedBuilder embedBuilder = createEmbedTemplate(event.getGuild()) 134 | .setDescription( 135 | String.format("Queueing Playlist `%s` (%s tracks, requested by %s)", 136 | playlist.getName(), playlist.getTracks().size(), event.getMember().getAsMention()) 137 | ) 138 | .setThumbnail(James.GITHUB_RAW_URL + "thumbnails/play.png"); 139 | event.reply(embedBuilder.build()); 140 | } 141 | 142 | public void getLoop(CommandEvent event) { 143 | boolean looping = trackScheduler.getLooping(); 144 | event.reply(createEmbedTemplate(event.getGuild()).setDescription("Currently " + (looping ? "" : "not ") + "looping.").build()); 145 | } 146 | 147 | public void setLoop(CommandEvent event, boolean loop) { 148 | trackScheduler.setLooping(loop); 149 | event.reply(createEmbedTemplate(event.getGuild()).setDescription("Turned looping " + (loop ? "on" : "off") + ".").build()); 150 | } 151 | 152 | /** Skips a number of Tracks and announces it. 153 | * @param event 154 | * @param amount 155 | */ 156 | public void skip(CommandEvent event, int amount) { 157 | for (int i = 0; i < amount; i++) 158 | trackScheduler.skip(); 159 | announceSkip(event, amount); 160 | } 161 | 162 | private void announceSkip(CommandEvent event, int amount) { 163 | EmbedBuilder embedBuilder = createEmbedTemplate(event.getGuild()) 164 | .setDescription( 165 | String.format("Skipped %s track(s)\n(requested by %s)", amount, event.getMember().getAsMention()) 166 | ) 167 | .setThumbnail(James.GITHUB_RAW_URL + "thumbnails/skip.png"); 168 | event.reply(embedBuilder.build()); 169 | } 170 | 171 | public void remove(CommandEvent event, int position) { 172 | announceRemove(event, trackScheduler.remove(position == -1 ? trackScheduler.getQueueSize() : position)); 173 | } 174 | 175 | private void announceRemove(CommandEvent event, AudioTrack removed) { 176 | EmbedBuilder embedBuilder = createEmbedTemplate(event.getGuild()); 177 | if (removed == null) 178 | embedBuilder.setDescription(String.format("No track removed. There are only %s tracks in the queue!", trackScheduler.getQueueSize())); 179 | else 180 | embedBuilder.setDescription(String.format("Removed a track from the queue\n(requested by %s)", event.getMember().getAsMention())); 181 | event.reply(embedBuilder.build()); 182 | } 183 | 184 | public void announceInvalidRemove(CommandEvent event) { 185 | event.reply(createEmbedTemplate(event.getGuild()).setDescription(String.format("That's not a valid number!")).build()); 186 | } 187 | 188 | /** 189 | * @return the VoiceChannel the bot is connected to, or null if it's not connected at all. 190 | */ 191 | @CheckForNull 192 | public VoiceChannel getVoiceChannel() { 193 | return audioManager.getConnectedChannel(); 194 | } 195 | 196 | public void shuffle(CommandEvent event) { 197 | trackScheduler.shuffle(); 198 | announceShuffle(event); 199 | } 200 | 201 | private void announceShuffle(CommandEvent event) { 202 | EmbedBuilder embedBuilder = createEmbedTemplate(event.getGuild()) 203 | .setDescription(String.format("The Queue has been shuffled by %s", event.getMember().getAsMention())) 204 | .setThumbnail(James.GITHUB_RAW_URL + "thumbnails/shuffle.png"); 205 | event.reply(embedBuilder.build()); 206 | } 207 | 208 | /** 209 | * @return The currently playing AudioTrack or null. 210 | */ 211 | @CheckForNull 212 | public AudioTrack getPlayingTrack() { 213 | return player.getPlayingTrack(); 214 | } 215 | 216 | /** Announces the currently playing Track. 217 | * @param event 218 | */ 219 | public void announceCurrentTrack(CommandEvent event) { 220 | AudioTrack track = player.getPlayingTrack(); 221 | if (track == null) 222 | event.reply("Not playing anything!"); 223 | else { 224 | String trackString = String.format("**Playing:** %s [\uD83D\uDD17](%s)\n", 225 | track.getInfo().title, track.getInfo().uri); 226 | EmbedBuilder embedBuilder = createEmbedTemplate(event.getGuild()) 227 | .setDescription(trackString) 228 | .appendDescription(String.format("**Time:** [%s / %s]", 229 | Util.MilisToTimestring(track.getPosition()), 230 | Util.MilisToTimestring(track.getDuration()))) 231 | .setThumbnail(getThumbnail(track)); 232 | 233 | event.getTextChannel().sendMessage(embedBuilder.build()).queue(message -> { 234 | while (track.equals(getPlayingTrack())) { 235 | embedBuilder.setDescription(trackString) 236 | .appendDescription(String.format("**Time:** [%s / %s]", 237 | Util.MilisToTimestring(track.getPosition()), 238 | Util.MilisToTimestring(track.getDuration())) 239 | ); 240 | 241 | message.editMessage(embedBuilder.build()).queue(); 242 | try { 243 | TimeUnit.SECONDS.sleep(15); 244 | } 245 | catch (InterruptedException e) { 246 | e.printStackTrace(); 247 | } 248 | } 249 | }); 250 | } 251 | } 252 | 253 | /** Pauses playback and announces it. 254 | * @param event 255 | */ 256 | public void pause(CommandEvent event) { 257 | player.setPaused(true); 258 | announcePause(event); 259 | } 260 | 261 | private void announcePause(CommandEvent event) { 262 | EmbedBuilder embedBuilder = createEmbedTemplate(event.getGuild()) 263 | .setDescription(String.format("The Audio Player has been paused.\n(requested by %s)", 264 | event.getMember().getAsMention())) 265 | .setThumbnail(James.GITHUB_RAW_URL + "thumbnails/pause.png"); 266 | event.reply(embedBuilder.build()); 267 | } 268 | 269 | /** Pauses playback and announces it. 270 | * @param event 271 | */ 272 | public void unpause(CommandEvent event) { 273 | if (player.isPaused()) { 274 | player.setPaused(false); 275 | announceUnpause(event); 276 | } 277 | } 278 | 279 | private void announceUnpause(CommandEvent event) { 280 | EmbedBuilder embedBuilder = createEmbedTemplate(event.getGuild()) 281 | .setDescription(String.format("The Audio Player has been unpaused\n(requested by %s)", 282 | event.getMember().getAsMention())) 283 | .setThumbnail(James.GITHUB_RAW_URL + "thumbnails/play.png"); 284 | event.reply(embedBuilder.build()); 285 | } 286 | 287 | /** 288 | * @param event 289 | */ 290 | public void createQueueEmbed(CommandEvent event) { 291 | LinkedList queue = trackScheduler.getQueue(); 292 | 293 | if(queue.isEmpty()) 294 | event.reply("The Queue is empty!"); 295 | else { 296 | ArrayList items = new ArrayList<>(); 297 | long queueLength = 0; 298 | for(AudioTrack track : queue){ 299 | items.add(String.format("`[%s]` %s", Util.MilisToTimestring(track.getDuration()), track.getInfo().title)); 300 | queueLength += track.getDuration(); 301 | } 302 | 303 | new Paginator.Builder() 304 | .setText(String.format("Showing %s Tracks. \n Total Queue Time Length: %s", queue.size(), Util.MilisToTimestring(queueLength))) 305 | .setItems(items.toArray(new String[0])) 306 | .setItemsPerPage(10) 307 | .setEventWaiter(James.eventWaiter) 308 | .setColor(event.getGuild().getSelfMember().getColor()) 309 | .useNumberedItems(true) 310 | .waitOnSinglePage(true) 311 | .setBulkSkipNumber(items.size() > 50 ? 5 : 0) // Only show bulk skip buttons when the Queue is sufficiently large 312 | .build() 313 | .display(event.getChannel()); 314 | } 315 | } 316 | 317 | /** 318 | * Writes the currently playing track & queue's URIs to a file and sends it to the user. 319 | * @param event 320 | * @param fileName 321 | */ 322 | public void sendQueueFile(CommandEvent event, String fileName) { 323 | StringBuilder builder = new StringBuilder(); 324 | try { 325 | builder.append(getPlayingTrack().getInfo().uri); 326 | } 327 | catch (NullPointerException e) { 328 | event.reply("Nothing Playing!"); 329 | } 330 | for (AudioTrack track : trackScheduler.getQueue()) 331 | builder.append("\n").append(track.getInfo().uri); 332 | 333 | event.getTextChannel().sendFile( 334 | new ByteArrayInputStream(builder.toString().getBytes(StandardCharsets.UTF_8)), fileName 335 | ).queue(); 336 | } 337 | 338 | /** Attempts to find a Thumbnail URL for the AudioTrack track. 339 | * If nothing is found (or the service is not supported), returns the default "Playing" Icon. 340 | * @param track An AudioTrack. 341 | * @return A valid Thumbnail URL. 342 | */ 343 | public String getThumbnail(AudioTrack track) { 344 | String url = null; // Util.getHttpStatus will catch it 345 | 346 | if (track.getInfo().uri.startsWith("https://www.youtube.com/watch?v=")) // lavaplayer *always* constructs YT URLs like this 347 | url = "http://i1.ytimg.com/vi/" + track.getIdentifier() + "/0.jpg"; 348 | else if (track.getInfo().uri.startsWith("https://soundcloud.com/")) 349 | url = getSoundcloudThumbnail(track.getInfo().uri); 350 | 351 | if (Util.getHttpStatus(url) == 200) 352 | return url; 353 | return James.GITHUB_RAW_URL + "thumbnails/play.png"; 354 | } 355 | 356 | /** Not the most reliable method, but i doesn't *have* to work, and i don't want to depend on yet another API. 357 | * @param trackUrl The URL of a Soundcloud track. 358 | * @return A Soundcloud Thumbnail URL (500x500) or null. 359 | */ 360 | @CheckForNull 361 | private String getSoundcloudThumbnail(String trackUrl){ 362 | String html = Util.getContentFromUrl(trackUrl); 363 | int pos = html.indexOf("\"artwork_url\":") + 15; 364 | try{ 365 | String artwork_url = html.substring(pos, html.indexOf("-large.jpg\"", pos) + 10); 366 | if(artwork_url.contains("-large.png")) 367 | artwork_url = html.substring(pos, html.indexOf("-large.png\"", pos) + 10); 368 | return artwork_url; 369 | } 370 | catch(IndexOutOfBoundsException e){ 371 | return null; 372 | } 373 | } 374 | } 375 | -------------------------------------------------------------------------------- /src/main/java/me/mcofficer/james/Util.java: -------------------------------------------------------------------------------- 1 | package me.mcofficer.james; 2 | 3 | import com.jagrosh.jdautilities.command.CommandEvent; 4 | import com.jagrosh.jdautilities.menu.OrderedMenu; 5 | import me.mcofficer.esparser.DataNode; 6 | import me.mcofficer.esparser.Sources; 7 | import net.dv8tion.jda.api.entities.*; 8 | import okhttp3.Request; 9 | import okhttp3.Response; 10 | import org.json.JSONArray; 11 | import org.json.JSONException; 12 | import org.json.JSONObject; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | import okhttp3.OkHttpClient; 16 | 17 | import javax.annotation.CheckReturnValue; 18 | import javax.annotation.Nullable; 19 | import java.io.*; 20 | import java.net.HttpURLConnection; 21 | import java.net.MalformedURLException; 22 | import java.net.URL; 23 | import java.nio.channels.Channels; 24 | import java.nio.channels.ReadableByteChannel; 25 | import java.nio.file.Files; 26 | import java.nio.file.Path; 27 | import java.util.*; 28 | import java.util.concurrent.TimeUnit; 29 | import java.util.function.BiConsumer; 30 | 31 | public class Util { 32 | 33 | private static Logger log = LoggerFactory.getLogger(Util.class); 34 | 35 | private static OkHttpClient _client = null; 36 | 37 | /** 38 | * @return A shared OkHttpClient. 39 | */ 40 | public static OkHttpClient okHttpClient() { 41 | if (_client == null) { 42 | _client = new OkHttpClient(); 43 | } 44 | return _client; 45 | } 46 | 47 | /** 48 | * Checks a URL for the HTTP status code. 49 | *

50 | * Returns 0 if an IOException occurs. 51 | * Returns 1 if a MalformedURLException occurs. 52 | * Returns -1 if the Response is invalid. 53 | * @param url The url to check. 54 | * @return The HTTP Status Code. 55 | */ 56 | public static int getHttpStatus(String url) { 57 | try { 58 | URL u = new URL(url); 59 | HttpURLConnection connection = (HttpURLConnection) u.openConnection(); 60 | connection.setRequestMethod("HEAD"); 61 | connection.setRequestProperty("User-Agent", "MarioB(r)owser4.2"); 62 | connection.connect(); 63 | return connection.getResponseCode(); 64 | } 65 | catch (MalformedURLException e) { 66 | e.printStackTrace(); 67 | return 1; 68 | } 69 | catch (IOException e) { 70 | e.printStackTrace(); 71 | return 0; 72 | } 73 | } 74 | 75 | /** Fetches the content reached at the URL as String. If the response is invalid, returns empty String. 76 | * @param url 77 | * @return 78 | */ 79 | @CheckReturnValue 80 | public static String getContentFromUrl(String url) { { 81 | return getContentFromUrl(url, new HashMap<>()); 82 | }} 83 | 84 | /** Fetches the content reached at the URL as String. If the response is invalid, returns empty String. 85 | * @param url 86 | * @param headers 87 | * @return 88 | */ 89 | @CheckReturnValue 90 | public static String getContentFromUrl(String url, Map headers) { 91 | Request.Builder builder = new Request.Builder() 92 | .url(url) 93 | .header("User-Agent", "MarioB(r)owser4.2"); 94 | headers.forEach(builder::addHeader); 95 | try (Response response = okHttpClient().newCall(builder.build()).execute()) { 96 | return response.body().string(); 97 | } 98 | catch (IOException e) { 99 | e.printStackTrace(); 100 | return ""; 101 | } 102 | } 103 | 104 | /** Sends a message to the guild's #mod-log channel. 105 | * @param guild 106 | * @param message 107 | */ 108 | public static void log(Guild guild, String message) { 109 | TextChannel modLog; 110 | try { 111 | modLog = guild.getTextChannelsByName("mod-log", true).get(0); 112 | modLog.sendMessage(message).queue(); 113 | } 114 | catch (IndexOutOfBoundsException | NullPointerException e) { 115 | log.error("Failed to find #mod-log channel in guild " + guild.getId() + ", moderation actions will not be logged."); 116 | } 117 | } 118 | 119 | /** 120 | * Returns a random "access denied" message, for humorously dismissing 121 | * Discord chatters who overstep. 122 | * @return "Access Denied" string. 123 | */ 124 | public static String getRandomDeniedMessage(){ 125 | final String[] messageList = { 126 | "You can't order me around.", 127 | "I don't listen to you.", 128 | "You're not my boss.", 129 | "Try harder.", 130 | "You think you're a hotshot pirate?", 131 | "Your attempt at using 'Pug Magic' has failed.", 132 | "You're no Admiral Danforth.", 133 | "As if.", 134 | "That prison on Clink is looking rather empty...", 135 | "Oh yeah?", 136 | "Nice try.", 137 | "I may be old, but I'm not dumb.", 138 | "I'll pretend you didn't say that.", 139 | "Not today.", 140 | "Oh, to be young again...", 141 | "*yawn*", 142 | "I have the power. You don't.", 143 | "Go play in a hyperspace lane.", 144 | "How about I put *you* in the airlock?", 145 | "Access Denied.", 146 | "Please don't joke about that sort of thing." 147 | }; 148 | int choice = new Random().nextInt(messageList.length); 149 | return messageList[choice]; 150 | } 151 | 152 | /** 153 | * Searches through a Guild guild to find the Roles associated with the Array's Strings. 154 | * Returns only those Roles contained in the Array and the Query. 155 | * @param query The Search String, contains Rolenames separated by spaces 156 | * @param guild The Guild to search in 157 | * @param optinRoles The "Free to Join" Roles 158 | * @return Possibly empty List of Roles. 159 | */ 160 | public static List getOptinRolesByQuery(String query, Guild guild, String[] optinRoles) { 161 | ArrayList add = new ArrayList<>(); 162 | for (String arg : query.split(" ")) { 163 | try { 164 | for (String optinRole : optinRoles) 165 | if (arg.equalsIgnoreCase(optinRole)) 166 | add.add(guild.getRolesByName(arg, true).get(0)); 167 | } 168 | catch (IndexOutOfBoundsException e) { 169 | e.printStackTrace(); 170 | } 171 | } 172 | return add; 173 | } 174 | 175 | /** Downloads a File and saves it in the target dir. 176 | * @param url 177 | * @param targetDir 178 | * @throws IOException 179 | */ 180 | public static void downloadFile(String url, Path targetDir, @Nullable String filename) throws IOException { 181 | if (filename == null) 182 | filename = url.substring(url.lastIndexOf('/')); 183 | ReadableByteChannel channel = Channels.newChannel(new URL(url).openStream()); 184 | FileOutputStream outputStream = new FileOutputStream(targetDir + "/" + filename); 185 | outputStream.getChannel().transferFrom(channel, 0, Long.MAX_VALUE); 186 | } 187 | 188 | /** Creates an OrderedMenu and sends it to the event's channel. 189 | * @param matches The Nodes that should be displayed 190 | * @param event The triggering event. 191 | * @param selection A BiConsumer that gets called once the user makes a selection. 192 | */ 193 | public static void displayNodeSearchResults(List matches, CommandEvent event, BiConsumer selection) { 194 | OrderedMenu.Builder builder = new OrderedMenu.Builder() 195 | .setEventWaiter(James.eventWaiter) 196 | .setSelection(selection) 197 | .setUsers(event.getAuthor()) 198 | .useCancelButton(true) 199 | .setDescription("**Found the following Nodes:**") 200 | .setColor(event.getGuild().getSelfMember().getColor()); 201 | matches.forEach(node -> builder.addChoice(String.join(" ", node.getTokens()))); 202 | builder.build().display(event.getChannel()); 203 | } 204 | 205 | /** Saves the ES data files and returns the temporary directory they were saved in. Should be removed afterwards. 206 | * @param githubToken 207 | * @return 208 | * @throws IOException 209 | */ 210 | public static ArrayList fetchGameData(String githubToken) throws IOException { 211 | Path temp = Files.createTempDirectory("james"); 212 | File data = new File(temp.toAbsolutePath() + "/data/"); 213 | data.mkdir(); 214 | data.deleteOnExit(); 215 | 216 | fetchGameDataRecursive(githubToken, data, "data"); 217 | ArrayList sources = Sources.getSources(temp, null); 218 | Files.walk(temp) 219 | .sorted(Comparator.reverseOrder()) 220 | .map(Path::toFile) 221 | .forEach(File::deleteOnExit); 222 | return sources; 223 | } 224 | 225 | private static void fetchGameDataRecursive(String githubToken, File dataFolder, String repoPath) { 226 | String url = String.format("https://api.github.com/repos/endless-sky/endless-sky/contents/%s?ref=master", repoPath); 227 | Map headers = new HashMap<>(); 228 | headers.put("Authorization", "token "+ githubToken); 229 | JSONArray json = new JSONArray(Util.getContentFromUrl(url, headers)); 230 | for (Object o : json) { 231 | try { 232 | JSONObject j = (JSONObject) o; 233 | if (j.getString("name").endsWith(".txt")) { 234 | Util.downloadFile(j.getString("download_url"), dataFolder.toPath(), j.getString("path").replaceAll("/", "_")); 235 | } else { // assume we have a directory 236 | fetchGameDataRecursive(githubToken, dataFolder, j.getString("path")); 237 | } 238 | } 239 | catch (IOException | JSONException e ) { 240 | e.printStackTrace(); 241 | } 242 | } 243 | } 244 | 245 | /** Compiles a list of valid image URLs from the ES repository. 246 | * @param githubToken 247 | * @return A List of image URLs. Could theoretically be empty, if GitHub is down. 248 | */ 249 | public static ArrayList get1xImagePaths(String githubToken) { 250 | return checkImageDir("https://api.github.com/repos/endless-sky/endless-sky/contents/images?ref=master", githubToken); 251 | } 252 | 253 | /** Iterates recursively through a directory of the GitHub API and compiles a List of image paths. Only for use in {@link #get1xImagePaths(String)}. 254 | * @param url 255 | * @param githubToken 256 | * @return 257 | */ 258 | private static ArrayList checkImageDir(String url, String githubToken) { 259 | Map headers = new HashMap<>(); 260 | headers.put("Authorization", "token "+ githubToken); 261 | JSONArray json = new JSONArray(Util.getContentFromUrl(url, headers)); 262 | ArrayList arrayList = new ArrayList<>(); 263 | for (Object o : json) { 264 | JSONObject j = (JSONObject) o; 265 | if (j.getString("type").equals("dir")) 266 | arrayList.addAll(checkImageDir(j.getString("url"), githubToken)); 267 | else 268 | arrayList.add(j.getString("download_url")); 269 | } 270 | return arrayList; 271 | } 272 | 273 | /** Takes a list of image paths and replaces them with paths to the hdpi repository where applicable. Takes several minutes, run async! 274 | * @param imagePaths 275 | * @return A List of Image Paths, containing hdpi paths where possible. 276 | */ 277 | public static ArrayList get2xImagePaths(ArrayList imagePaths) { 278 | ArrayList revisedPaths = new ArrayList<>(); 279 | for (String path : imagePaths) { 280 | String revised = path.replace("endless-sky/master", "endless-sky-high-dpi/master") 281 | .replace(".png", "@2x.png"); 282 | if (getHttpStatus(revised) == 200) 283 | revisedPaths.add(revised); 284 | else 285 | revisedPaths.add(path); 286 | } 287 | return revisedPaths; 288 | } 289 | 290 | public static String sendInChunksReturnLast(TextChannel channel, String... output) { 291 | return sendInChunksHelper(channel, Arrays.asList(output), "```", "```", true); 292 | } 293 | 294 | /** 295 | * Convenience method for {@link #sendInChunks(TextChannel, List, String, String)}, 296 | * accepts Arrays of Strings and assumes triple backticks as footer & header. 297 | * @param channel 298 | * @param output 299 | */ 300 | public static void sendInChunks(TextChannel channel, String... output) { 301 | sendInChunks(channel, Arrays.asList(output), "```", "```"); 302 | } 303 | 304 | /** 305 | * Utility function that will concatenate a list of strings into valid 306 | * Discord messages. 307 | * @param channel The desired output channel 308 | * @param output The list of strings to write. 309 | * @param header A string that should prefix every chunk. 310 | * @param footer A string that should end every chunk. 311 | */ 312 | public static void sendInChunks(TextChannel channel, List output, String header, String footer) { 313 | String whatever = sendInChunksHelper(channel, output, header, footer, false); 314 | return; 315 | } 316 | 317 | private static String sendInChunksHelper(TextChannel channel, List output, String header, String footer, boolean returnLastChunk) { 318 | if(output.isEmpty()) 319 | return ""; 320 | 321 | StringBuilder chunk = new StringBuilder(header); 322 | int chunkSize = chunk.length() + footer.length(); 323 | final int sizeLimit = 1990; 324 | if(chunkSize > sizeLimit){ 325 | System.out.println("Cannot ever print: header + footer too large."); 326 | return ""; 327 | } 328 | for(String str : output){ 329 | if(chunkSize + str.length() <= sizeLimit) 330 | chunk.append(str); 331 | else{ 332 | channel.sendMessage(chunk.append(footer).toString()).queue(); 333 | chunk = new StringBuilder(header + str); 334 | } 335 | chunkSize = chunk.length() + footer.length(); 336 | } 337 | // Write, or return the final chunk. 338 | if(chunk.length() > header.length()) { 339 | if (returnLastChunk) { 340 | return chunk.append(footer).toString(); 341 | } 342 | channel.sendMessage(chunk.append(footer).toString()).queue(); 343 | } 344 | return ""; 345 | } 346 | 347 | 348 | /** Replaces a Member's Roles with temporaryRole for seconds, and logs the action to #mod-log. 349 | * @param temporaryRole 350 | * @param seconds 351 | * @param member 352 | * @param logOnCommand 353 | * @param logOnRelease 354 | */ 355 | public static void replaceRolesTemporarily(Role temporaryRole, long seconds, Member member, String logOnCommand, String logOnRelease) { 356 | List originalRoles = member.getRoles(); 357 | // Remove current roles & add temporary role 358 | if (member.getRoles().contains(temporaryRole)) 359 | Util.log(member.getGuild(), String.format("Attempted to give Role %s to %s, but %s already has it! Aborting Role Removal.", 360 | temporaryRole.getAsMention(), member.getAsMention(), member.getAsMention())); 361 | else { 362 | Guild guild = member.getGuild(); 363 | 364 | guild.modifyMemberRoles(member, new ArrayList<>() {{ add(temporaryRole); }}, originalRoles).queue(success1 -> 365 | // Remove timout role & re-add old roles 366 | guild.removeRoleFromMember(member, temporaryRole).queueAfter(seconds, TimeUnit.SECONDS, success2 -> { 367 | originalRoles.forEach(role -> guild.addRoleToMember(member, role).queue()); 368 | Util.log(member.getGuild(), logOnRelease); 369 | }) 370 | ); 371 | Util.log(member.getGuild(), logOnCommand); 372 | } 373 | } 374 | 375 | /** 376 | * @param milis 377 | * @return A String of the format HH:MM:SS (hours will be omitted if 0) 378 | */ 379 | public static String MilisToTimestring(long milis) { 380 | int seconds = (int) ((milis / 1000) % 60); 381 | int minutes = (int) ((milis / (1000 * 60)) % 60); 382 | int hours = (int) ((milis / (1000 * 60 * 60)) % 24); 383 | int days = (int) (milis / (1000 * 60 * 60 * 24)); 384 | 385 | if(days > 0) 386 | return String.format("%2dd %02d:%02d:%02d", days, hours, minutes, seconds); 387 | else if(hours > 0) 388 | return String.format("%02d:%02d:%02d", hours, minutes, seconds); 389 | else 390 | return String.format("%02d:%02d", minutes, seconds); 391 | } 392 | 393 | /** 394 | * Returns the a String containing what e's printStacktrace method would print. 395 | * @param e 396 | * @return 397 | */ 398 | public static String ExceptionToString(Exception e) { 399 | StringWriter sw = new StringWriter(); 400 | e.printStackTrace(new PrintWriter(sw)); 401 | return sw.toString(); 402 | } 403 | } 404 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------