Discord feature additions, Discord startup flow changed, /f debug added

Signed-off-by: DroppingAnvil <dr0pping.4nvi1@gmail.com>
This commit is contained in:
DroppingAnvil 2019-12-12 04:48:00 -06:00
parent ca9502a4b6
commit fa10bf7003
26 changed files with 655 additions and 48 deletions

View File

@ -1,6 +1,7 @@
package com.massivecraft.factions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.massivecraft.factions.integration.dynmap.DynmapStyle;
import com.massivecraft.factions.util.XMaterial;
import com.massivecraft.factions.zcore.fperms.DefaultPermissions;
@ -104,6 +105,22 @@ public class Conf {
public static String fromDiscordFactionChatPrefix = "&f[&dDiscord&f] ";
public static String avatarUrl = "http://cravatar.eu/helmavatar/%uuid%.png";
public static String webhookName = "SaberFactions Hook";
public static String mainGuildID = "<Discord Server ID here>";
public static String positiveReaction = "<Server emote here>";
public static String negativeReaction = "<Server emote here>";
public static Boolean restrictActionsWhenNotLinked = false;
public static Boolean leaderRoles = false;
public static String leaderRole = "<Leader Role ID>";
public static Boolean factionDiscordTags = false;
public static String factionTag = "(NAME) [FACTION]";
public static Boolean factionRoles = false;
public static List<Integer> factionRoleColor = new ArrayList<Integer>(){{
add(25);
add(162);
add(203);
}};
public static String factionRolePrefix = "";
public static String factionRoleSuffix = "";
// server logging options
public static boolean logFactionCreate = true;
public static boolean logFactionDisband = true;

View File

@ -7,6 +7,7 @@ import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.WarmUpUtil;
import mkremins.fanciful.FancyMessage;
import net.dv8tion.jda.core.entities.User;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
@ -30,6 +31,36 @@ public interface FPlayer extends EconomyParticipator {
boolean hasNotificationsEnabled();
/**
* Get if a player has setup their Discord before
* @return if the player setup Discord as a boolean
*/
boolean discordSetup();
/**
* Get the players Discord user ID
* @return players Discord user ID as a String
*/
String discordUserID();
/**
* Set the players Boolean defining if the player has setup their Discord
* @param b Boolean for discordSetup to be defined to
*/
void setDiscordSetup(Boolean b);
/**
* Set the players Discord user ID
* @param s String for their user ID to be set to
*/
void setDiscordUserID(String s);
/**
* Get the players Discord user (If the player has not setup Discord it will return null!)
* @return User from players set Discord User ID
*/
User discordUser();
/**
* Used to check if this player should be served titles
* @return if this FPlayer has titles enabled as a boolean

View File

@ -11,6 +11,7 @@ import com.massivecraft.factions.cmd.FCommand;
import com.massivecraft.factions.cmd.check.CheckTask;
import com.massivecraft.factions.cmd.check.WeeWooTask;
import com.massivecraft.factions.cmd.chest.AntiChestListener;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.discord.DiscordListener;
import com.massivecraft.factions.discord.FactionChatHandler;
import com.massivecraft.factions.integration.Econ;
@ -267,11 +268,8 @@ public class FactionsPlugin extends MPlugin {
this.getServer().getScheduler().runTaskTimer(this, CheckTask::cleanupTask, 0L, 1200L);
this.getServer().getScheduler().runTaskTimerAsynchronously(this, new WeeWooTask(this), 600L, 600L);
}
if(Conf.useDiscordSystem && !Conf.discordBotToken.equals("<token here>")) {
new FactionChatHandler(this);
} else {
System.out.println("\n\n\n SABER-FACTIONS-DISCORD-INTEGRATION - You are not using Discord integration features, set conf.json option useDiscordSystem to true and put a valid token in before using!\n\n\n");
}
//Setup Discord Bot
new Discord(this);
ShopConfig.setup();
@ -415,7 +413,7 @@ public class FactionsPlugin extends MPlugin {
.registerTypeAdapterFactory(EnumTypeAdapter.ENUM_FACTORY);
}
private void divider() {
public void divider() {
System.out.println(" .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.-");
System.out.println(" / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\");
System.out.println("`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-'");

View File

@ -1,6 +1,7 @@
package com.massivecraft.factions.cmd;
import com.massivecraft.factions.*;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.event.FPlayerJoinEvent;
import com.massivecraft.factions.event.FactionCreateEvent;
import com.massivecraft.factions.integration.Econ;
@ -8,7 +9,10 @@ import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.util.MiscUtil;
import com.massivecraft.factions.zcore.util.TL;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.exceptions.HierarchyException;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import java.util.ArrayList;
@ -32,6 +36,10 @@ public class CmdCreate extends FCommand {
@Override
public void perform(CommandContext context) {
if (Conf.restrictActionsWhenNotLinked && !context.fPlayer.discordSetup()) {
context.player.sendMessage(ChatColor.translateAlternateColorCodes('&', TL.DISCORD_LINK_REQUIRED.toString()));
return;
}
String tag = context.argAsString(0);
if (context.fPlayer.hasFaction()) {
@ -82,7 +90,6 @@ public class CmdCreate extends FCommand {
FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(context.player), faction, FPlayerJoinEvent.PlayerJoinReason.CREATE);
Bukkit.getServer().getPluginManager().callEvent(joinEvent);
// join event cannot be cancelled or you'll have an empty faction
// finish setting up the FPlayer
context.fPlayer.setFaction(faction, false);
// We should consider adding the role just AFTER joining the faction.
@ -94,6 +101,22 @@ public class CmdCreate extends FCommand {
follower.msg(TL.COMMAND_CREATE_CREATED, context.fPlayer.getName(), faction.getTag(follower));
}
}
//Discord
try {
if (Discord.useDiscord && context.fPlayer.discordSetup() && Discord.isInMainGuild(context.fPlayer.discordUser()) && Discord.mainGuild != null) {
Member m = Discord.mainGuild.getMember(context.fPlayer.discordUser());
if (Conf.factionRoles) {
Discord.mainGuild.getController().addSingleRoleToMember(m, Discord.createFactionRole(faction.getTag())).queue();
}
if (Conf.leaderRoles && Discord.leader != null) {
Discord.mainGuild.getController().addSingleRoleToMember(m, Discord.leader).queue();
}
if (Conf.factionDiscordTags) {
Discord.mainGuild.getController().setNickname(m, Discord.getNicknameString(context.fPlayer)).queue();
}
}
} catch (HierarchyException e) {System.out.print(e.getMessage());}
//End Discord
context.msg(TL.COMMAND_CREATE_YOUSHOULD, FactionsPlugin.getInstance().cmdBase.cmdDescription.getUsageTemplate(context));
if (Conf.econEnabled) Econ.setBalance(faction.getAccountId(), Conf.econFactionStartingBalance);
if (Conf.logFactionCreate)

View File

@ -0,0 +1,51 @@
package com.massivecraft.factions.cmd;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.discord.DiscordSetupAttempt;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit;
public class CmdDebug extends FCommand {
public CmdDebug() {
super();
this.aliases.add("debug");
this.requirements = new CommandRequirements.Builder(Permission.DEBUG).build();
}
@Override
public void perform(CommandContext context) {
FactionsPlugin.getInstance().divider();
System.out.print("----------Debug Info----------");
System.out.print("--------Main-------");
System.out.print("Server Version: " + FactionsPlugin.getInstance().getServer().getVersion());
System.out.print("Server Bukkit Version: " + FactionsPlugin.getInstance().getServer().getBukkitVersion());
System.out.print("SaberFactions Version: " + FactionsPlugin.getInstance().getDescription().getVersion());
System.out.print("Is Beta Version: " + (FactionsPlugin.getInstance().getDescription().getFullName().contains("BETA") ? "True" : "False"));
System.out.print("Players Online: " + Bukkit.getOnlinePlayers().size());
System.out.print("------End Main-----");
System.out.print("------Discord------");
System.out.print("Discord Integration enabled in config: " + Discord.confUseDiscord);
System.out.print("Discord Integration enabled: " + Discord.useDiscord);
System.out.print("Setup attempts: " + Discord.setupLog.size());
System.out.print("FPlayers waiting to link: " + Discord.waitingLink.size());
System.out.print("Bot Token: " + (Discord.botToken == "<token here>" ? "Not Set" : "Set"));
System.out.print("JDA Null: " + (Discord.jda == null ? "True" : "False"));
System.out.print("Main Guild ID: " + Discord.mainGuildID);
System.out.print("Main Guild Null: " + (Discord.mainGuild == null ? "True" : "False"));
System.out.print("Emotes enabled: " + Discord.useEmotes);
System.out.print("Leader role null: " + (Discord.leader == null ? "True" : "False"));
System.out.print("Attempt Log:");
for (DiscordSetupAttempt d : Discord.setupLog) {System.out.print(d.getDifferentialFormatted() + " " + d.getSuccess() + " " + d.getReason());}
System.out.print("End Attempt Log");
System.out.print("----End Discord----");
System.out.print("--------End Debug Info--------");
FactionsPlugin.getInstance().divider();
context.fPlayer.msg(TL.COMMAND_DEBUG_PRINTED);
}
@Override
public TL getUsageTranslation() {
return TL.COMMAND_DEBUG_DESCRIPTION;
}
}

View File

@ -0,0 +1,40 @@
package com.massivecraft.factions.cmd;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL;
import java.util.Random;
public class CmdDiscord extends FCommand {
public CmdDiscord() {
super();
this.aliases.add("discord");
this.requirements = new CommandRequirements.Builder(Permission.DISCORD)
.playerOnly()
.build();
}
@Override
public void perform(CommandContext context) {
if (context.fPlayer.discordSetup()) {
context.fPlayer.msg(TL.DISCORD_ALREADY_LINKED, context.fPlayer.discordUser().getName());
} else {
if (Discord.waitingLink.values().contains(context.fPlayer)) {
context.fPlayer.msg(TL.DISCORD_CODE_SENT, Discord.waitingLinkk.get(context.fPlayer), Discord.mainGuild.getSelfMember().getEffectiveName());
return;
}
Integer random = new Random().nextInt(9999);
while (Discord.waitingLink.values().contains(random)) {
random = new Random().nextInt(9999);
}
Discord.waitingLink.put(random, context.fPlayer);
Discord.waitingLinkk.put(context.fPlayer, random);
context.fPlayer.msg(TL.DISCORD_CODE_SENT, String.valueOf(random));
}
}
@Override
public TL getUsageTranslation() {
return TL.COMMAND_DISCORD_DESCRIPTION;
}
}

View File

@ -1,10 +1,13 @@
package com.massivecraft.factions.cmd;
import com.massivecraft.factions.*;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.event.FPlayerJoinEvent;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.fupgrades.UpgradeType;
import com.massivecraft.factions.zcore.util.TL;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.exceptions.HierarchyException;
import org.bukkit.Bukkit;
public class CmdJoin extends FCommand {
@ -120,7 +123,18 @@ public class CmdJoin extends FCommand {
}
faction.deinvite(fplayer);
context.fPlayer.setRole(faction.getDefaultRole());
try {
context.fPlayer.setRole(faction.getDefaultRole());
if (Discord.useDiscord && context.fPlayer.discordSetup() && Discord.isInMainGuild(context.fPlayer.discordUser()) && Discord.mainGuild != null) {
Member m = Discord.mainGuild.getMember(context.fPlayer.discordUser());
if (Conf.factionRoles) {
Discord.mainGuild.getController().addSingleRoleToMember(m, Discord.createFactionRole(faction.getTag())).queue();
}
if (Conf.factionDiscordTags) {
Discord.mainGuild.getController().setNickname(m, Discord.getNicknameString(context.fPlayer)).queue();
}
}
} catch (HierarchyException e) {System.out.print(e.getMessage());}
if (Conf.logFactionJoin) {
if (samePlayer) {

View File

@ -1,7 +1,9 @@
package com.massivecraft.factions.cmd;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.ChatColor;
public class CmdLeave extends FCommand {

View File

@ -2,6 +2,7 @@ package com.massivecraft.factions.cmd;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.listeners.FactionsPlayerListener;
import com.massivecraft.factions.shop.ShopConfig;
import com.massivecraft.factions.struct.Permission;
@ -38,6 +39,8 @@ public class CmdReload extends FCommand {
FactionsPlayerListener.loadCorners();
}
Discord.setupDiscord();
long timeReload = (System.currentTimeMillis() - timeInitStart);
context.msg(TL.COMMAND_RELOAD_TIME, timeReload);

View File

@ -1,6 +1,7 @@
package com.massivecraft.factions.cmd;
import com.massivecraft.factions.*;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.event.FactionRenameEvent;
import com.massivecraft.factions.scoreboards.FTeamWrapper;
import com.massivecraft.factions.struct.Permission;
@ -65,6 +66,7 @@ public class CmdTag extends FCommand {
String oldtag = context.faction.getTag();
context.faction.setTag(tag);
Discord.changeFactionTag(context.faction, oldtag);
// Inform
for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) {

View File

@ -158,6 +158,8 @@ public class FCmdRoot extends FCommand implements CommandExecutor {
public CmdSeeDiscord cmdSeeDiscord = new CmdSeeDiscord();
public CmdInviteBot cmdInviteBot = new CmdInviteBot();
public CmdSetGuild cmdSetGuild = new CmdSetGuild();
public CmdDiscord cmdDiscord = new CmdDiscord();
public CmdDebug cmdDebug = new CmdDebug();
public FCmdRoot() {
super();
@ -239,7 +241,9 @@ public class FCmdRoot extends FCommand implements CommandExecutor {
this.addSubCommand(this.cmdAHome);
this.addSubCommand(this.cmdPerm);
this.addSubCommand(this.cmdPromote);
this.addSubCommand(this.cmdDebug);
this.addSubCommand(this.cmdDemote);
this.addSubCommand(this.cmdDiscord);
this.addSubCommand(this.cmdSetDefaultRole);
this.addSubCommand(this.cmdMapHeight);
this.addSubCommand(this.cmdClaimAt);

View File

@ -5,7 +5,7 @@ import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.discord.FactionChatHandler;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.zcore.util.TL;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.MessageBuilder;
@ -92,7 +92,7 @@ public class CheckTask implements Runnable {
if (channelId.isEmpty()) {
continue;
}
TextChannel textChannel = FactionChatHandler.jda.getTextChannelById(channelId);
TextChannel textChannel = Discord.jda.getTextChannelById(channelId);
if (textChannel == null) {
continue;
}
@ -141,7 +141,7 @@ public class CheckTask implements Runnable {
if (channelId.isEmpty()) {
continue;
}
TextChannel textChannel = FactionChatHandler.jda.getTextChannelById(channelId);
TextChannel textChannel = Discord.jda.getTextChannelById(channelId);
if (textChannel == null) {
continue;
}

View File

@ -1,18 +1,16 @@
package com.massivecraft.factions.cmd.check;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.cmd.CommandContext;
import com.massivecraft.factions.cmd.CommandRequirements;
import com.massivecraft.factions.cmd.FCommand;
import com.massivecraft.factions.discord.FactionChatHandler;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.util.TL;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.Channel;
import net.dv8tion.jda.core.entities.MessageEmbed;
import net.dv8tion.jda.core.entities.TextChannel;
import org.bukkit.OfflinePlayer;
@ -94,7 +92,7 @@ public class CmdCheck extends FCommand {
if (channelId == null || channelId.isEmpty()) {
return;
}
TextChannel textChannel = FactionChatHandler.jda.getTextChannelById(channelId);
TextChannel textChannel = Discord.jda.getTextChannelById(channelId);
if (textChannel == null) {
return;
}
@ -126,7 +124,7 @@ public class CmdCheck extends FCommand {
if (channelId == null || channelId.isEmpty()) {
return;
}
TextChannel textChannel = FactionChatHandler.jda.getTextChannelById(channelId);
TextChannel textChannel = Discord.jda.getTextChannelById(channelId);
if (textChannel == null) {
return;
}

View File

@ -4,10 +4,9 @@ import com.massivecraft.factions.Conf;
import com.massivecraft.factions.cmd.CommandContext;
import com.massivecraft.factions.cmd.CommandRequirements;
import com.massivecraft.factions.cmd.FCommand;
import com.massivecraft.factions.discord.FactionChatHandler;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL;
import net.dv8tion.jda.core.entities.Channel;
import net.dv8tion.jda.core.entities.TextChannel;
public class CmdWeeWoo extends FCommand {
@ -42,7 +41,7 @@ public class CmdWeeWoo extends FCommand {
if (!Conf.useDiscordSystem) return;
String discordChannelId = context.faction.getWeeWooChannelId();
if (discordChannelId != null && !discordChannelId.isEmpty()) {
TextChannel textChannel = FactionChatHandler.jda.getTextChannelById(discordChannelId);
TextChannel textChannel = Discord.jda.getTextChannelById(discordChannelId);
if (textChannel == null) {
return;
}
@ -62,7 +61,7 @@ public class CmdWeeWoo extends FCommand {
if(!Conf.useDiscordSystem) return;
String discordChannelId = context.faction.getWeeWooChannelId();
if (discordChannelId != null && !discordChannelId.isEmpty()) {
TextChannel textChannel = FactionChatHandler.jda.getTextChannelById(discordChannelId);
TextChannel textChannel = Discord.jda.getTextChannelById(discordChannelId);
if (textChannel == null) {
return;
}

View File

@ -4,9 +4,8 @@ import com.massivecraft.factions.Conf;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.FactionsPlugin;
import com.massivecraft.factions.discord.FactionChatHandler;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.zcore.util.TL;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.TextChannel;
@ -36,7 +35,7 @@ public class WeeWooTask implements Runnable {
if (discordChannelId == null || discordChannelId.isEmpty()) {
continue;
}
TextChannel textChannel = FactionChatHandler.jda.getTextChannelById(discordChannelId);
TextChannel textChannel = Discord.jda.getTextChannelById(discordChannelId);
if (textChannel == null) {
continue;
}

View File

@ -21,7 +21,7 @@ public class CmdInviteBot extends FCommand {
@Override
public void perform(CommandContext context) {
JDA jda = FactionChatHandler.jda;
JDA jda = Discord.jda;
FancyMessage fancyMessage = new FancyMessage();
fancyMessage.link(jda.asBot().getInviteUrl(Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, Permission.MESSAGE_HISTORY, Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_EMBED_LINKS));
fancyMessage.text(FactionsPlugin.getInstance().color("&c&lFactions Bot - &2Click here to invite the bot"));

View File

@ -43,7 +43,7 @@ public class CmdSetGuild extends FCommand {
public void perform(CommandContext context) {
String guildId = context.argAsString(0, null);
Faction faction = context.argAsFaction(1, context.faction);
JDA jda = FactionChatHandler.jda;
JDA jda = Discord.jda;
if (jda != null) {
if (!this.waiterAdded) {
jda.addEventListener(new EventWaiter[]{this.eventWaiter});

View File

@ -0,0 +1,227 @@
package com.massivecraft.factions.discord;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.FactionsPlugin;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.exceptions.HierarchyException;
import net.dv8tion.jda.core.exceptions.RateLimitedException;
import javax.security.auth.login.LoginException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.logging.Level;
public class Discord {
//We dont want waitingLink to reset during reload so we are going to set it here
public static HashMap<Integer, FPlayer> waitingLink;
public static HashMap<FPlayer, Integer> waitingLinkk;
//We want to track the amount of times setup has been tried and the result may be useful for determining issues
public static HashSet<DiscordSetupAttempt> setupLog;
private static FactionsPlugin plugin;
public static Boolean confUseDiscord;
public static String botToken;
public static String mainGuildID;
public static Boolean useDiscord;
public static java.awt.Color roleColor;
public static Guild mainGuild;
public static Role leader;
public static JDA jda;
public static Boolean useEmotes;
public static Emote positive;
public static Emote negative;
public Discord(FactionsPlugin plugin) {
this.plugin = plugin;
setupLog = new HashSet<>();
waitingLink = new HashMap<>();
waitingLinkk = new HashMap<>();
setupDiscord();
}
/**
* Called to reload variables and if needed start JDA
*/
public static void setupDiscord() {
if (jda == null) {
if (startBot()) {
varSetup();
jda.addEventListener(new FactionChatHandler(plugin));
jda.addEventListener(new DiscordListener(plugin));
return;
}
}
varSetup();
}
private static Boolean startBot() {
try {
jda = new JDABuilder(AccountType.BOT).setToken(Conf.discordBotToken).buildBlocking();
} catch (LoginException | InterruptedException e) {
e.printStackTrace();
FactionsPlugin.getInstance().getLogger().log(Level.WARNING, "Discord bot was unable to start! Please verify the bot token is correct.");
setupLog.add(new DiscordSetupAttempt(e.getMessage(), System.currentTimeMillis()));
return false;
}
setupLog.add(new DiscordSetupAttempt(System.currentTimeMillis()));
return true;
}
private static void varSetup() {
try {
confUseDiscord = Conf.useDiscordSystem;
botToken = Conf.discordBotToken;
if (jda != null) {mainGuild = jda.getGuildById(Conf.mainGuildID);} else {mainGuild = null;}
mainGuildID = Conf.mainGuildID;
useDiscord = !botToken.equals("<token here>") && !mainGuildID.equals("<Discord Server ID here>") && confUseDiscord;
roleColor = new java.awt.Color(Conf.factionRoleColor.get(0), Conf.factionRoleColor.get(1), Conf.factionRoleColor.get(2));
if (jda != null) {
try {
positive = jda.getEmoteById(Conf.positiveReaction);
negative = jda.getEmoteById(Conf.negativeReaction);
if (positive == null | negative == null) {useEmotes = false;}
} catch (NumberFormatException e) {
FactionsPlugin.getInstance().getLogger().log(Level.WARNING, "Invalid Emote(s) disabling them.");
useEmotes = false;
}
if (mainGuild != null) {leader = mainGuild.getRoleById(Conf.leaderRole);} else {leader = null;}
} else {useEmotes = false; leader = null;}
} catch (NullPointerException e) {
e.printStackTrace();
setupLog.add(new DiscordSetupAttempt("Threw an NPE while setting up variables", System.currentTimeMillis()));
}
}
/**
* Get the nickname that would be assigned to a player
*
* @param f Target as FPlayer
* @return Translated nickname for Discord as a String
*/
public static String getNicknameString(FPlayer f) {
if (useDiscord) {
String temp = Conf.factionTag;
if (temp.contains("NAME")) { temp = temp.replace("NAME", f.getName()); }
if (temp.contains("DiscordName")) { temp = temp.replace("DiscordName", (f.discordUser() == null) ? (f.getName()) : (f.discordUser().getName())); }
if (temp.contains("FACTION")) { temp = temp.replace("FACTION", f.getFaction().getTag()); }
if (temp.contains("FactionRole")) { temp = temp.replace("FactionRole", f.getRole().getRoleCapitalized()); }
if (temp.contains("FactionRolePrefix")) { temp = temp.replace("FactionRolePrefix", f.getRole().getPrefix()); }
return temp;
}
return null;
}
/**
* Check if a faction Role exist
*
* @param s String target Faction tag
* @return
*/
public static Boolean doesFactionRoleExist(String s) {
StringBuilder sb = new StringBuilder();
sb.append(Conf.factionRolePrefix);
sb.append(s);
sb.append(Conf.factionRoleSuffix);
return getRoleFromName(sb.toString()) != null;
}
public static Role getRoleFromName(String s) {
if (useDiscord && mainGuild != null) {
for (Role r : mainGuild.getRoles()) {
if (r.getName().equals(s)) {return r;}
}
}
return null;
}
/**
* Creates a role in Discord for a faction and returns it
*
* @param s String Faction Tag
* @return Role generated faction role
*/
public static Role createFactionRole(String s) {
if (!useDiscord) { return null; }
if (mainGuild == null) { return null; }
StringBuilder sb = new StringBuilder();
sb.append(Conf.factionRolePrefix);
sb.append(s);
sb.append(Conf.factionRoleSuffix);
if (!doesFactionRoleExist(sb.toString())) {
try {
Role newRole = mainGuild.getController().createRole()
.setName(sb.toString())
.setColor(roleColor)
.setPermissions(Permission.EMPTY_PERMISSIONS)
.complete(true);
return newRole;
} catch (RateLimitedException e) {
System.out.print(e.getMessage());
}
} else {
return getRoleFromName(sb.toString());
}
return null;
}
/**
* Get the name of the Faction Role that would be generated with the tag
* @param tag Faction Name/Tag
* @return Name of would be Role
*/
public static String getFactionRoleName(String tag) {
StringBuilder sb = new StringBuilder();
sb.append(Conf.factionRolePrefix);
sb.append(tag);
sb.append(Conf.factionRoleSuffix);
return sb.toString();
}
/**
* Check if the Discord user is in the main Guild/Server
*
* @param u User
* @return Boolean
*/
public static Boolean isInMainGuild(User u) {
if (mainGuild == null) {
return false;
}
return mainGuild.getMember(u) == null ? Boolean.FALSE : Boolean.TRUE;
}
/**
* Reset the players nickname in Discord
*
* @param f FPlayer target
*/
public static void resetNick(FPlayer f) {
if (mainGuild == null) { return; }
if (mainGuild.getMember(f.discordUser()) == null) { return; }
mainGuild.getController().setNickname(mainGuild.getMember(f.discordUser()), f.discordUser().getName()).queue();
}
public static void changeFactionTag(Faction f, String oldTag) {
if (!useDiscord | mainGuild == null) { return; }
for (FPlayer fp : f.getFPlayers()) {
if (fp.discordSetup() && isInMainGuild(fp.discordUser())) {
try {
Member m = mainGuild.getMember(fp.discordUser());
if (Conf.factionDiscordTags) {
mainGuild.getController().setNickname(m, Discord.getNicknameString(fp)).queue();
}
if (Conf.factionRoles) {
mainGuild.getController().removeSingleRoleFromMember(m, getRoleFromName(oldTag)).queue();
mainGuild.getController().addSingleRoleToMember(m, createFactionRole(f.getTag())).queue();
}
} catch (HierarchyException e) {System.out.print(e.getMessage());}
}
}
}
}

View File

@ -6,7 +6,9 @@ import com.massivecraft.factions.zcore.util.TL;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.events.message.priv.PrivateMessageReceivedEvent;
import net.dv8tion.jda.core.exceptions.PermissionException;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import org.bukkit.ChatColor;
@ -64,6 +66,23 @@ public class DiscordListener extends ListenerAdapter {
}
}
public void onPrivateMessageReceived(PrivateMessageReceivedEvent e) {
Integer i = 0;
if (e.getAuthor().isBot()) {return;}
try {
i = Integer.valueOf(e.getMessage().getContentDisplay());
} catch (NumberFormatException ex) {e.getChannel().sendMessage(TL.DISCORD_CODE_INVALID_FORMAT.toString()).queue();
return;}
if (Discord.waitingLink.keySet().contains(i)) {
FPlayer f = Discord.waitingLink.get(i);
f.setDiscordSetup(true);
f.setDiscordUserID(e.getAuthor().getId());
e.getChannel().sendMessage(TL.DISCORD_LINK_SUCCESS.toString()).queue();
Discord.waitingLink.remove(i);
Discord.waitingLinkk.remove(f);
} else {e.getChannel().sendMessage(TL.DISCORD_CODE_INVALID_KEY.toString()).queue();
return;}
}
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
try {

View File

@ -0,0 +1,105 @@
package com.massivecraft.factions.discord;
public class DiscordSetupAttempt {
private Boolean success;
private String reason;
private Long initialTime;
/**
* Constructor used when an attempt fails
* @param reason String reason for the attempt failing
* @param time Long current system time in millis
*/
public DiscordSetupAttempt(String reason, Long time) {
this.success = false;
this.reason = reason;
this.initialTime = time;
}
/**
* Constructor used for successful attempts
* @param time Long Current system time in millis
*/
public DiscordSetupAttempt(Long time) {
this.success = true;
this.reason = null;
this.initialTime = time;
}
/**
* Get if this attempt to setup the Discord bot was successful
* @return Boolean success
*/
public Boolean getSuccess() {return this.success;}
/**
* Get the reason for the setup failing (If it was successful it will return null)
* @return String reason
*/
public String getReason() {return this.reason;}
/**
* Get the time this setup was attempted
* @return Long initialTime
*/
public Long getInitialTime() {return this.initialTime;}
/**
* Get the difference of time between when attempted and present time
* @return Long time difference in milliseconds
*/
public Long getDifferentialTime() {return System.currentTimeMillis()-initialTime;}
/**
* Get the difference in time between when attempted and present time formatted MS,Seconds,Minutes,Hours,Years
* @return String with formatted time difference
*/
public String getDifferentialFormatted() {
Integer timeIndex = 0;
//Milliseconds
Long inProcessTime = getDifferentialTime();
if (inProcessTime >= 1000) {
timeIndex++;
//Seconds
inProcessTime = inProcessTime/Integer.toUnsignedLong(1000);
if (inProcessTime >= 60) {
timeIndex++;
//Minutes
inProcessTime = inProcessTime/Integer.toUnsignedLong(60);
if (inProcessTime >= 60) {
timeIndex++;
//Hours
inProcessTime = inProcessTime/Integer.toUnsignedLong(60);
if (inProcessTime >= 24) {
timeIndex++;
//Days
inProcessTime = inProcessTime/Integer.toUnsignedLong(24);
//Skipping months
if (inProcessTime >= 365) {
timeIndex++;
//Years
//If someone really has 100% uptime in a year idek
inProcessTime = inProcessTime/Integer.toUnsignedLong(365);
}
}
}
}
}
StringBuilder sb = new StringBuilder();
sb.append(inProcessTime);
//Just a separator for looks
sb.append(" ");
String s = "";
switch (timeIndex) {
case 0: s = "MS"; break;
case 1: s = "Seconds"; break;
case 2: s = "Minutes"; break;
case 3: s = "Hours"; break;
case 4: s = "Days"; break;
case 5: s = "Years"; break;
}
sb.append(s);
sb.append(" ago");
return sb.toString();
}
}

View File

@ -6,7 +6,6 @@ import com.massivecraft.factions.Factions;
import com.massivecraft.factions.FactionsPlugin;
import mkremins.fanciful.FancyMessage;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.Message;
@ -25,29 +24,14 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
public class FactionChatHandler extends ListenerAdapter {
/**
* @author Driftay
*/
public static JDA jda;
private FactionsPlugin plugin;
public FactionChatHandler(FactionsPlugin plugin) {
this.plugin = plugin;
startBot();
jda.addEventListener(this);
jda.addEventListener(new DiscordListener(plugin));
}
private void startBot() {
try {
jda = new JDABuilder(AccountType.BOT).setToken(Conf.discordBotToken).buildBlocking();
} catch (LoginException | InterruptedException e) {
e.printStackTrace();
}
}
public static void sendMessage(FactionsPlugin plugin, Faction faction, UUID uuid, String username, String message) {
@ -56,10 +40,10 @@ public class FactionChatHandler extends ListenerAdapter {
if (factionsChatChannelId == null || factionsChatChannelId.isEmpty()) {
return;
}
if (jda == null) {
if (Discord.jda == null) {
return;
}
TextChannel textChannel = jda.getTextChannelById(factionsChatChannelId);
TextChannel textChannel = Discord.jda.getTextChannelById(factionsChatChannelId);
if (textChannel == null) {
return;
}
@ -78,8 +62,8 @@ public class FactionChatHandler extends ListenerAdapter {
List<String> x = new ArrayList<>(Arrays.asList(message.split(" ")));
for (String y : x) {
if (y.contains("@")) {
if (!jda.getUsersByName(y.replace("@", ""), false).isEmpty() && jda.getUsersByName(y.replace("@", ""), false).size() < 2) {
x.set(x.indexOf(y), jda.getUsersByName(y.replace("@", ""), false).get(0).getAsMention());
if (!Discord.jda.getUsersByName(y.replace("@", ""), false).isEmpty() && Discord.jda.getUsersByName(y.replace("@", ""), false).size() < 2) {
x.set(x.indexOf(y), Discord.jda.getUsersByName(y.replace("@", ""), false).get(0).getAsMention());
}
}
}

View File

@ -34,6 +34,7 @@ public enum Permission {
CONVERTCONFIG("convertconfig"),
CREATE("create"),
CORNER("corner"),
DEBUG("debug"),
DEFAULTRANK("defaultrank"),
DEINVITE("deinvite"),
DELHOME("delhome"),

View File

@ -94,6 +94,10 @@ public enum Role implements Permissable {
return this.nicename;
}
public String getRoleCapitalized() {
return this.nicename.replace(Character.toString(nicename.charAt(0)), Character.toString(nicename.charAt(0)).toUpperCase());
}
public TL getTranslation() {
return translation;
}

View File

@ -2,6 +2,7 @@ package com.massivecraft.factions.zcore.persist;
import com.massivecraft.factions.*;
import com.massivecraft.factions.cmd.CmdFly;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.event.*;
import com.massivecraft.factions.event.FactionDisbandEvent.PlayerDisbandReason;
import com.massivecraft.factions.iface.EconomyParticipator;
@ -21,6 +22,9 @@ import com.massivecraft.factions.zcore.fperms.Access;
import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.util.TL;
import mkremins.fanciful.FancyMessage;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.exceptions.HierarchyException;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.*;
import org.bukkit.command.CommandSender;
@ -42,6 +46,8 @@ import java.util.*;
public abstract class MemoryFPlayer implements FPlayer {
public boolean inChest = false;
public boolean discordSetup = false;
public String discordUserID = "";
public boolean inVault = false;
protected HashMap<String, Long> commandCooldown = new HashMap<>();
protected String factionId;
@ -218,12 +224,25 @@ public abstract class MemoryFPlayer implements FPlayer {
public boolean hasNotificationsEnabled() {
return this.notificationsEnabled;
}
public boolean discordSetup() {return this.discordSetup;}
public String discordUserID() {return this.discordUserID;}
public void setDiscordSetup(Boolean b) {this.discordSetup = b;}
public void setDiscordUserID(String s) {this.discordUserID = s;}
public boolean hasTitlesEnabled() {
return this.titlesEnabled;
}
public void setTitlesEnabled(Boolean b) {
this.titlesEnabled = b;
}
public User discordUser() {return Discord.jda.getUserById(this.discordUserID);}
public String getFactionId() {
return this.factionId;
}
@ -258,7 +277,23 @@ public abstract class MemoryFPlayer implements FPlayer {
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
this.role = event.getTo();
try {
if (Discord.useDiscord && this.discordSetup() && Discord.isInMainGuild(this.discordUser()) && Discord.mainGuild != null) {
Member m = Discord.mainGuild.getMember(this.discordUser());
if (Conf.leaderRoles && this.role == Role.LEADER && event.getTo() != Role.LEADER) {
Discord.mainGuild.getController().removeSingleRoleFromMember(m, Discord.mainGuild.getRoleById(Conf.leaderRole)).queue();
}
if (Conf.leaderRoles && event.getTo() == Role.LEADER) {
Discord.mainGuild.getController().addSingleRoleToMember(m, Discord.mainGuild.getRoleById(Conf.leaderRole)).queue();
}
this.role = event.getTo();
if (Conf.factionDiscordTags) {
Discord.mainGuild.getController().setNickname(m, Discord.getNicknameString(this)).queue();
}
} else {
this.role = event.getTo();
}
} catch (HierarchyException e) {System.out.print(e.getMessage());}
}
}
@ -376,6 +411,22 @@ public abstract class MemoryFPlayer implements FPlayer {
// clean up any territory ownership in old faction, if there is one
if (factionId != null && Factions.getInstance().isValidFactionId(this.getFactionId())) {
Faction currentFaction = this.getFaction();
//Discord
try {
if (Discord.useDiscord && this.discordSetup() && Discord.isInMainGuild(this.discordUser()) && Discord.mainGuild != null) {
Member m = Discord.mainGuild.getMember(this.discordUser());
if (Conf.leaderRoles && this.role == Role.LEADER && Discord.leader != null) {
Discord.mainGuild.getController().removeSingleRoleFromMember(m, Discord.leader).queue();
}
if (Conf.factionRoles) {
Discord.mainGuild.getController().removeSingleRoleFromMember(m, Discord.createFactionRole(this.getFaction().getTag())).queue();
}
if (Conf.factionDiscordTags) {
Discord.resetNick(this);
}
}
} catch (HierarchyException e) {System.out.print(e.getMessage());}
//End Discord
currentFaction.removeFPlayer(this);
if (currentFaction.isNormal()) {
currentFaction.clearClaimOwnership(this);

View File

@ -1,6 +1,7 @@
package com.massivecraft.factions.zcore.persist;
import com.massivecraft.factions.*;
import com.massivecraft.factions.discord.Discord;
import com.massivecraft.factions.event.FPlayerLeaveEvent;
import com.massivecraft.factions.event.FactionDisbandEvent;
import com.massivecraft.factions.event.FactionDisbandEvent.PlayerDisbandReason;
@ -21,6 +22,7 @@ import com.massivecraft.factions.zcore.fperms.Permissable;
import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.fupgrades.UpgradeType;
import com.massivecraft.factions.zcore.util.TL;
import net.dv8tion.jda.core.entities.Member;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@ -345,9 +347,21 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
return;
}
// Send FPlayerLeaveEvent for each player in the faction
// Send FPlayerLeaveEvent for each player in the faction and reset their Discord settings
for (FPlayer fplayer : this.getFPlayers()) {
Bukkit.getServer().getPluginManager().callEvent(new FPlayerLeaveEvent(fplayer, this, FPlayerLeaveEvent.PlayerLeaveReason.DISBAND));
if (Discord.useDiscord && fplayer.discordSetup() && Discord.isInMainGuild(fplayer.discordUser()) && Discord.mainGuild != null) {
Member m = Discord.mainGuild.getMember(fplayer.discordUser());
if (Conf.leaderRoles && fplayer.getRole() == Role.LEADER) {
Discord.mainGuild.getController().removeSingleRoleFromMember(m, Discord.mainGuild.getRoleById(Conf.leaderRole)).queue();
}
if (Conf.factionRoles) {
Discord.mainGuild.getController().removeSingleRoleFromMember(m, Discord.createFactionRole(this.getTag())).queue();
}
if (Conf.factionDiscordTags) {
Discord.resetNick(fplayer);
}
}
}
if (Conf.logFactionDisband) {
@ -1313,6 +1327,18 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
oldLeader.setRole(Role.NORMAL);
}
replacements.get(0).setRole(Role.LEADER);
if (Discord.useDiscord && replacements.get(0).discordSetup() && Discord.isInMainGuild(replacements.get(0).discordUser()) && Discord.mainGuild != null) {
Member m = Discord.mainGuild.getMember(replacements.get(0).discordUser());
if (Conf.factionRoles) {
Discord.mainGuild.getController().addSingleRoleToMember(m, Discord.createFactionRole(this.getTag())).queue();
}
if (Conf.leaderRoles) {
Discord.mainGuild.getController().addSingleRoleToMember(m, Discord.mainGuild.getRoleById(Conf.leaderRole)).queue();
}
if (Conf.factionDiscordTags) {
Discord.mainGuild.getController().setNickname(m, Discord.getNicknameString(replacements.get(0)));
}
}
this.msg(TL.AUTOLEAVE_ADMIN_PROMOTED, oldLeader == null ? "" : oldLeader.getName(), replacements.get(0).getName());
FactionsPlugin.getInstance().log("Faction " + this.getTag() + " (" + this.getId() + ") admin was removed. Replacement admin: " + replacements.get(0).getName());
}

View File

@ -327,6 +327,9 @@ public enum TL {
CHECK_LEADERBOARD_HEADER("&8---- Check Leaderboard ----"),
CHECK_LEADERBOARD_LINE("&f%1$s. &d%2$s: &f%3$s (%4$s Buffer, %5$s Walls)"),
CHECK_LEADERBOARD_NO_DATA("&8No data"),
COMMAND_DISCORD_DESCRIPTION("Link your Discord account"),
COMMAND_DEBUG_DESCRIPTION("Print debugging info to console"),
COMMAND_DEBUG_PRINTED("&c&l[!]&7 Debug info has been printed to console"),
//DISCORD
WEEWOO_ALREADY_STARTED_DISCORD("Weewoo already started"),
@ -345,6 +348,12 @@ public enum TL {
SET_GUILD_ID_RESET_ID("&cGuild id removed"),
SET_GUILD_ID_PMING_OWNER("&aNow Direct messaging the Discord server owner to approve the link, times out in 15 seconds."),
CANT_FORCE_SET_GUILD_ID("&cYou cannot forcefully set guild ids for other guilds."),
DISCORD_LINK_REQUIRED("&c&l[!] You cannot do this while your Discord is not linked! Link your account by using /f discord link"),
DISCORD_LINK_SUCCESS("Your account has been linked!"),
DISCORD_CODE_SENT("&c&l[!]&7 Your code is &f%1$s &7please send this to the SaberFactions bot on Discord"),
DISCORD_ALREADY_LINKED("&c&l[!]&7 Your account is already linked to &f%1$s"),
DISCORD_CODE_INVALID_KEY("That code is invalid, verify the code is correct."),
DISCORD_CODE_INVALID_FORMAT("If you are submitting a code please only type the code. Example message: 0000"),
COMMAND_DEINVITE_CANDEINVITE("&c&l[!]&7 Players you can &cdeinvite: "),