Skip to content

Commit

Permalink
Update to Discord4J v3, fixes #14
Browse files Browse the repository at this point in the history
  • Loading branch information
mcmonkey4eva committed May 6, 2019
1 parent 7fc5570 commit 3c71922
Show file tree
Hide file tree
Showing 10 changed files with 525 additions and 329 deletions.
46 changes: 27 additions & 19 deletions pom.xml
Expand Up @@ -7,30 +7,30 @@
<groupId>com.denizenscript</groupId>
<artifactId>ddiscordbot</artifactId>
<packaging>jar</packaging>
<version>0.5</version>
<version>0.6</version>
<name>dDiscordBot</name>
<description>Adds a Discord bot to Denizen</description>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<BUILD_NUMBER>Unknown</BUILD_NUMBER>
<bukkit.version>1.13.2-R0.1-SNAPSHOT</bukkit.version>
<denizen.version>1.0.3-SNAPSHOT</denizen.version>
<bukkit.version>1.14-R0.1-SNAPSHOT</bukkit.version>
<denizen.version>1.0.5-SNAPSHOT</denizen.version>
</properties>

<!-- Repositories -->
<repositories>
<repository>
<id>everything</id>
<url>http://repo.citizensnpcs.co</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Repository Switchboard</name>
<url>http://repo1.maven.org/maven2</url>
</repository>
<repository>
<id>jcenter</id>
<url>http://jcenter.bintray.com</url>
</repository>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
<id>everything</id>
<url>http://repo.citizensnpcs.co</url>
</repository>
</repositories>

Expand All @@ -52,9 +52,8 @@
</dependency>
<dependency>
<groupId>com.discord4j</groupId>
<artifactId>Discord4J</artifactId>
<version>2.10.1</version>
<classifier>shaded</classifier>
<artifactId>discord4j-core</artifactId>
<version>3.0.4</version>
</dependency>

</dependencies>
Expand Down Expand Up @@ -84,22 +83,31 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.1</version>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<minimizeJar>true</minimizeJar>
<artifactSet>
<includes>
<include>com.discord4j:Discord4J</include>
<include>com.discord4j:**</include>
<include>io.projectreactor:**</include>
<include>io.projectreactor.addons:**</include>
<include>io.projectreactor.netty:**</include>
<include>io.netty:**</include>
<include>com.austinv11.servicer:**</include>
<include>com.fasterxml.jackson.core:**</include>
<include>com.fasterxml.jackson.datatype:**</include>
<include>org.reactivestreams:**</include>
</includes>
</artifactSet>
<filters>
<filter>
<artifact>com.discord4j:Discord4J</artifact>
<artifact>com.discord4j:**</artifact>
<includes>
<include>**</include>
</includes>
Expand All @@ -113,7 +121,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<version>3.1.0</version>
<configuration>
<finalName>dDiscordBot-${version}-b${BUILD_NUMBER}</finalName>
<archive>
Expand All @@ -128,7 +136,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
Expand Down
165 changes: 75 additions & 90 deletions src/main/java/com/denizenscript/ddiscordbot/DiscordCommand.java
@@ -1,5 +1,13 @@
package com.denizenscript.ddiscordbot;

import discord4j.core.DiscordClient;
import discord4j.core.DiscordClientBuilder;
import discord4j.core.object.entity.TextChannel;
import discord4j.core.object.entity.User;
import discord4j.core.object.presence.Activity;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.util.Snowflake;
import discord4j.core.spec.UserEditSpec;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.aufdemrand.denizencore.exceptions.InvalidArgumentsException;
import net.aufdemrand.denizencore.objects.Element;
Expand All @@ -10,16 +18,12 @@
import net.aufdemrand.denizencore.scripts.queues.ScriptQueue;
import net.aufdemrand.denizencore.utilities.CoreUtilities;
import org.bukkit.Bukkit;
import sx.blah.discord.api.ClientBuilder;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.handle.obj.*;
import sx.blah.discord.util.RequestBuffer;

public class DiscordCommand extends AbstractCommand implements Holdable {

// <--[command]
// @Name discord
// @Syntax discord [id:<id>] [connect code:<botcode>/disconnect/message/addrole/removerole/status (status:<status>) (activity:<activity>)/rename] (<message>) (channel:<channel>) (user:<user>) (guild:<guild>) (role:<role>)
// @Syntax discord [id:<id>] [connect code:<botcode>/disconnect/message/addrole/removerole/status (status:<status>) (activity:<activity>)/rename] (<message>) (channel:<channel>) (user:<user>) (guild:<guild>) (role:<role>) (url:<url>)
// @Required 2
// @Stable unstable
// @Short Connects to and interacts with Discord.
Expand All @@ -34,8 +38,9 @@ public class DiscordCommand extends AbstractCommand implements Holdable {
//
// Commands may fail if the bot does not have permission within the Discord group to perform them.
//
// When setting the status of the Discord bot, the status argument can be: ONLINE, DND, IDLE, INVISIBLE, OFFLINE or UNKNOWN,
// and the activity argument can be: PLAYING, STREAMING, LISTENING or WATCHING.
// When setting the status of the Discord bot, the status argument can be: ONLINE, DND, IDLE, or INVISIBLE,
// and the activity argument can be: PLAYING, STREAMING, LISTENING, or WATCHING.
// Streaming activity requires a 'url:' input.
//
// @Tags
// TODO: Make tags
Expand Down Expand Up @@ -105,6 +110,10 @@ else if (!scriptEntry.hasObject("channel")
&& arg.matchesPrefix("channel")) {
scriptEntry.addObject("channel", arg.asElement());
}
else if (!scriptEntry.hasObject("url")
&& arg.matchesPrefix("url")) {
scriptEntry.addObject("url", arg.asElement());
}
else if (!scriptEntry.hasObject("user")
&& arg.matchesPrefix("user")) {
scriptEntry.addObject("user", arg.asElement());
Expand Down Expand Up @@ -155,9 +164,10 @@ public static class DiscordConnectThread extends Thread {
@Override
public void run() {
try {
ClientBuilder cb = new ClientBuilder().withToken(code);
cb.registerListener(conn);
conn.client = cb.login();
DiscordClient client = new DiscordClientBuilder(code).build();
conn.client = client;
conn.registerHandlers();
client.login().block();
}
catch (Exception ex) {
Bukkit.getScheduler().runTask(dDiscordBot.instance, () -> {
Expand All @@ -184,14 +194,15 @@ public void execute(ScriptEntry scriptEntry) {
// Fetch required objects
Element id = scriptEntry.getElement("id");
Element instruction = scriptEntry.getElement("instruction");
Element code = scriptEntry.getElement("code");
Element code = scriptEntry.getElement("code"); // Intentionally do not debug this value.
Element channel = scriptEntry.getElement("channel");
Element message = scriptEntry.getElement("message");
Element status = scriptEntry.getElement("status");
Element activity = scriptEntry.getElement("activity");
Element user = scriptEntry.getElement("user");
Element guild = scriptEntry.getElement("guild");
Element role = scriptEntry.getElement("role");
Element url = scriptEntry.getElement("url");

// Debug the execution
dB.report(scriptEntry, getName(), id.debug()
Expand All @@ -200,9 +211,12 @@ public void execute(ScriptEntry scriptEntry) {
+ (message != null ? message.debug(): "")
+ (user != null ? user.debug(): "")
+ (guild != null ? guild.debug(): "")
+ (role != null ? role.debug(): ""));
+ (role != null ? role.debug(): "")
+ (status != null ? status.debug(): "")
+ (activity != null ? activity.debug(): "")
+ (url != null ? url.debug(): ""));

IDiscordClient client;
DiscordClient client;

switch (DiscordInstruction.valueOf(instruction.asString().toUpperCase())) {
case CONNECT:
Expand Down Expand Up @@ -248,24 +262,16 @@ public void execute(ScriptEntry scriptEntry) {
dB.echoError(scriptEntry.getResidingQueue(), "The Discord bot '" + id.asString() + "'is not yet loaded.");
return;
}
RequestBuffer.request(() -> {
if (channel == null) {
IUser userObj = client.getUserByID(user.asLong());
if (userObj == null) {
errorMessage(scriptEntry.getResidingQueue(), "User for ID '" + user.asLong() + "' not found.");
return;
}
client.getOrCreatePMChannel(userObj).sendMessage(message.asString());
}
else {
IChannel channelObj = client.getChannelByID(channel.asLong());
if (channelObj == null) {
errorMessage(scriptEntry.getResidingQueue(), "Channel for ID '" + channel.asLong() + "' not found.");
return;
}
channelObj.sendMessage(message.asString());
}
});
if (channel == null) {
client.getUserById(Snowflake.of(user.asLong())).map(User::getPrivateChannel).flatMap(chanBork -> chanBork.flatMap(
chan -> chan.createMessage(message.asString())))
.doOnError(dB::echoError).subscribe();
}
else {
client.getChannelById(Snowflake.of(channel.asLong()))
.flatMap(chan -> ((TextChannel) chan).createMessage(message.asString()))
.doOnError(dB::echoError).subscribe();
}
break;
case ADDROLE:
if (user == null) {
Expand All @@ -289,24 +295,9 @@ public void execute(ScriptEntry scriptEntry) {
dB.echoError(scriptEntry.getResidingQueue(), "The Discord bot '" + id.asString() + "'is not yet loaded.");
return;
}
RequestBuffer.request(() -> {
IGuild iguild = client.getGuildByID(guild.asLong());
if (iguild == null) {
errorMessage(scriptEntry.getResidingQueue(), "Guild for ID '" + guild.asLong() + "' not found.");
return;
}
IUser userObj = client.getUserByID(user.asLong());
if (userObj == null) {
errorMessage(scriptEntry.getResidingQueue(), "User for ID '" + user.asLong() + "' not found.");
return;
}
IRole roleObj = iguild.getRoleByID(role.asLong());
if (roleObj == null) {
errorMessage(scriptEntry.getResidingQueue(), "Role for ID '" + role.asLong() + "' not found.");
return;
}
userObj.addRole(roleObj);
});
client.getGuildById(Snowflake.of(guild.asLong())).map(guildObj -> guildObj.getMemberById(Snowflake.of(user.asLong())))
.flatMap(memberBork -> memberBork.flatMap(member -> member.addRole(Snowflake.of(role.asLong()))))
.doOnError(dB::echoError).subscribe();
break;
case REMOVEROLE:
if (user == null) {
Expand All @@ -330,24 +321,9 @@ public void execute(ScriptEntry scriptEntry) {
dB.echoError(scriptEntry.getResidingQueue(), "The Discord bot '" + id.asString() + "'is not yet loaded.");
return;
}
RequestBuffer.request(() -> {
IGuild iguild = client.getGuildByID(guild.asLong());
if (iguild == null) {
errorMessage(scriptEntry.getResidingQueue(), "Guild for ID '" + guild.asLong() + "' not found.");
return;
}
IUser userObj = client.getUserByID(user.asLong());
if (userObj == null) {
errorMessage(scriptEntry.getResidingQueue(), "User for ID '" + user.asLong() + "' not found.");
return;
}
IRole roleObj = iguild.getRoleByID(role.asLong());
if (roleObj == null) {
errorMessage(scriptEntry.getResidingQueue(), "Role for ID '" + role.asLong() + "' not found.");
return;
}
userObj.removeRole(roleObj);
});
client.getGuildById(Snowflake.of(guild.asLong())).map(guildObj -> guildObj.getMemberById(Snowflake.of(user.asLong())))
.flatMap(memberBork -> memberBork.flatMap(member -> member.removeRole(Snowflake.of(role.asLong()))))
.doOnError(dB::echoError).subscribe();
break;
case RENAME:
if (!dDiscordBot.instance.connections.containsKey(id.asString())) {
Expand All @@ -361,7 +337,7 @@ public void execute(ScriptEntry scriptEntry) {
}
long userId;
if (user == null) {
userId = client.getOurUser().getLongID();
userId = client.getSelfId().get().asLong();
}
else {
userId = user.asLong();
Expand All @@ -374,19 +350,9 @@ public void execute(ScriptEntry scriptEntry) {
dB.echoError(scriptEntry.getResidingQueue(), "Failed to rename: no name given!");
return;
}
RequestBuffer.request(() -> {
IGuild iguild = client.getGuildByID(guild.asLong());
if (iguild == null) {
errorMessage(scriptEntry.getResidingQueue(), "Guild for ID '" + guild.asLong() + "' not found.");
return;
}
IUser userObj = client.getUserByID(userId);
if (userObj == null) {
errorMessage(scriptEntry.getResidingQueue(), "User for ID '" + userId + "' not found.");
return;
}
iguild.setUserNickname(userObj, message.asString());
});
client.getGuildById(Snowflake.of(guild.asLong())).map(guildObj -> guildObj.getMemberById(Snowflake.of(userId)))
.flatMap(memberBork -> memberBork.flatMap(member -> member.edit(spec -> spec.setNickname(message.asString()))))
.doOnError(dB::echoError).subscribe();
break;
case STATUS:
if (!dDiscordBot.instance.connections.containsKey(id.asString())) {
Expand All @@ -398,16 +364,35 @@ public void execute(ScriptEntry scriptEntry) {
dB.echoError(scriptEntry.getResidingQueue(), "The Discord bot '" + id.asString() + "'is not yet loaded.");
return;
}
StatusType st = status == null ? StatusType.ONLINE : StatusType.valueOf(status.asString().toUpperCase());
if (message == null) {
client.changePresence(st);
return;
Activity.Type at = activity == null ? Activity.Type.PLAYING : Activity.Type.valueOf(activity.asString().toUpperCase());
Activity activityObject;
if (at == Activity.Type.WATCHING) {
activityObject = Activity.watching(message.asString());
}
ActivityType at = activity == null ? ActivityType.PLAYING : ActivityType.valueOf(activity.asString().toUpperCase());
RequestBuffer.request(() -> {
client.changePresence(st, at, message.asString());
});

else if (at == Activity.Type.STREAMING) {
activityObject = Activity.streaming(message.asString(), url.asString());
}
else if (at == Activity.Type.LISTENING) {
activityObject = Activity.listening(message.asString());
}
else {
activityObject = Activity.playing(message.asString());
}
String statusLower = status == null ? "online" : CoreUtilities.toLowerCase(status.asString());
Presence presence;
if (statusLower.equals("idle")) {
presence = Presence.idle(activityObject);
}
else if (statusLower.equals("dnd")) {
presence = Presence.doNotDisturb(activityObject);
}
else if (statusLower.equals("invisible")) {
presence = Presence.invisible();
}
else {
presence = Presence.online(activityObject);
}
client.updatePresence(presence).subscribe();
break;
}
}
Expand Down

0 comments on commit 3c71922

Please sign in to comment.