Creating a Minecraft to Discord verification system that integrates with the Paper API and Discord's features involves several steps. Below is a comprehensive guide to help you build this system, complete with code examples and explanations of various components.
Overview
-
System Architecture
- Minecraft Server (Paper): Handles in-game commands and player interactions.
- Discord Bot: Manages verification, role checking, and embeds.
- Database: Stores the linkage between Minecraft accounts and Discord IDs.
-
Key Features
- Verification System: Players link their Discord accounts to their Minecraft accounts.
- Role-Based Team Assignment: OPs can run a command to assign players to teams based on their Discord roles.
- Discord Embeds: Provide rich messages for verification and status updates.
- Security: Ensure that only authorized OPs can execute certain commands.
Prerequisites
- Java Development Kit (JDK) 17 or higher
- Minecraft Server Running Paper
- Discord Bot Token
- Database (e.g., MySQL or SQLite)
- Maven or Gradle for dependency management
- Libraries:
- Paper API for Minecraft plugin development
- JDA (Java Discord API) for Discord bot interactions
- HikariCP for database connection pooling (optional but recommended)
Step-by-Step Implementation
1. Setting Up the Discord Bot
First, create a Discord bot through the Discord Developer Portal.
- Create an Application: Give it a name and navigate to the "Bot" section to create a bot.
- Enable Privileged Intents: Such as
Guild Members to access member roles.
- Invite the Bot to Your Server: Use the OAuth2 URL with appropriate scopes (bot) and permissions.
2. Setting Up the Minecraft Plugin
Create a new Paper plugin project. Below is a Maven pom.xml setup:
<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
<modelVersion>4.0.0</modelVersion>
<groupId>com.yourdomain</groupId>
<artifactId>DiscordVerification</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Paper API -->
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>1.19.4-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- JDA -->
<dependency>
<groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId>
<version>5.0.0-alpha.14</version>
</dependency>
<!-- SQLite (or replace with your preferred DB) -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.3</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>jcenter</id>
<url>https://jcenter.bintray.com/</url>
</repository>
</repositories>
</project>
3. Database Setup
For simplicity, we'll use SQLite. Create a table to store the linkage between Minecraft usernames and Discord IDs.
CREATE TABLE IF NOT EXISTS user_verification (
minecraft_uuid TEXT PRIMARY KEY,
discord_id TEXT UNIQUE,
verified BOOLEAN DEFAULT FALSE
);
4. Plugin Configuration
Create a config.yml to store necessary configurations like Discord token and database path.
discord_token: "YOUR_DISCORD_BOT_TOKEN"
embed_color: "#7289DA" # Discord embed color
database:
type: sqlite
path: "plugins/DiscordVerification/database.db"
verification_channel_id: "DISCORD_CHANNEL_ID"
5. Implementing the Plugin
Below is a simplified version of the plugin's main class.
package com.yourdomain.discordverification;
import net.dv8tion.jda.api.*;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.*;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class DiscordVerification extends JavaPlugin {
private JDA jda;
private Connection connection;
private String embedColor;
@Override
public void onEnable() {
saveDefaultConfig();
embedColor = getConfig().getString("embed_color", "#7289DA");
setupDatabase();
setupDiscordBot();
getCommand("verify").setExecutor(new VerifyCommand(this));
getCommand("discordroleteam").setExecutor(new DiscordRoleTeamCommand(this));
}
private void setupDatabase() {
try {
String dbType = getConfig().getString("database.type", "sqlite");
if (dbType.equalsIgnoreCase("sqlite")) {
String dbPath = getConfig().getString("database.path", "plugins/DiscordVerification/database.db");
connection = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
}
// Implement other DB types if needed
String table = "CREATE TABLE IF NOT EXISTS user_verification (" +
"minecraft_uuid TEXT PRIMARY KEY," +
"discord_id TEXT UNIQUE," +
"verified BOOLEAN DEFAULT FALSE" +
");";
Statement stmt = connection.createStatement();
stmt.execute(table);
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
getServer().getPluginManager().disablePlugin(this);
}
}
private void setupDiscordBot() {
String token = getConfig().getString("discord_token");
if (token == null || token.isEmpty()) {
getLogger().severe("Discord token not found in config.yml");
getServer().getPluginManager().disablePlugin(this);
return;
}
try {
jda = JDABuilder.createDefault(token)
.addEventListeners(new DiscordListener(this))
.setActivity(Activity.watching("for verification"))
.build();
jda.awaitReady();
// Register commands
jda.upsertCommand("verify", "Link your Discord account with your Minecraft account")
.addOption(OptionType.STRING, "code", "Verification code", true)
.queue();
} catch (Exception e) {
e.printStackTrace();
getServer().getPluginManager().disablePlugin(this);
}
}
public JDA getJDA() {
return jda;
}
public Connection getDatabaseConnection() {
return connection;
}
public String getEmbedColor() {
return embedColor;
}
@Override
public void onDisable() {
if (jda != null) {
jda.shutdown();
}
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
6. Verification Mechanism
a. Generating Verification Codes
When a player runs the /verify command in Minecraft, generate a unique code and prompt them to use it in Discord.
package com.yourdomain.discordverification;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class VerifyCommand implements CommandExecutor {
private final DiscordVerification plugin;
private final Map<UUID, String> verificationCodes = new HashMap<>();
public VerifyCommand(DiscordVerification plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Only players can use this command.");
return true;
}
Player player = (Player) sender;
UUID uuid = player.getUniqueId();
String code = UUID.randomUUID().toString().substring(0, 8);
verificationCodes.put(uuid, code);
// In a real implementation, store this in the database with a timestamp
// and expiration logic
// Send embed to Discord verification channel
String verificationChannelId = plugin.getConfig().getString("verification_channel_id");
TextChannel channel = plugin.getJDA().getTextChannelById(verificationChannelId);
if (channel != null) {
channel.sendMessageEmbeds(
new net.dv8tion.jda.api.EmbedBuilder()
.setTitle("Minecraft Verification")
.setDescription(player.getName() + " is verifying their account.")
.addField("Verification Code", code, false)
.setColor(java.awt.Color.decode(plugin.getEmbedColor()))
.build()
).queue();
}
player.sendMessage(ChatColor.GREEN + "A verification code has been sent to the Discord channel. Please enter `/verify <code>` in Discord.");
return true;
}
public Map<UUID, String> getVerificationCodes() {
return verificationCodes;
}
}
b. Handling Discord Verification
Create a DiscordListener to handle Discord interactions.
package com.yourdomain.discordverification;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DiscordListener extends ListenerAdapter {
private final DiscordVerification plugin;
public DiscordListener(DiscordVerification plugin) {
this.plugin = plugin;
}
@Override
public void onSlashCommandInteraction(SlashCommandInteractionEvent event) {
if (!event.getName().equals("verify")) return;
String code = event.getOption("code").getAsString();
String discordId = event.getUser().getId();
try {
Connection conn = plugin.getDatabaseConnection();
// Find if this code exists for any user
String query = "SELECT minecraft_uuid FROM user_verification WHERE discord_id = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, discordId);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
event.reply("You have already verified your account.").setEphemeral(true).queue();
rs.close();
stmt.close();
return;
}
rs.close();
stmt.close();
// Assuming we have stored the code temporarily; in real implementation, you'd have a separate table
// For simplicity, assume code is unique and map to a single UUID
// This part needs proper implementation
// Example: Check verificationCodes map from VerifyCommand
// Here we'll skip and assume verification is successful
// For demonstration, let's assume the code corresponds to a player's UUID
// Replace with actual code-to-UUID mapping
// Example: SELECT minecraft_uuid FROM verification_codes WHERE code = ?
// Then update user_verification table
// Placeholder response
event.reply("Verification successful!").setEphemeral(true).queue();
// You should implement actual verification logic here
} catch (SQLException e) {
e.printStackTrace();
event.reply("An error occurred during verification.").setEphemeral(true).queue();
}
}
}
Note: For a complete implementation, you need to store and manage verification codes properly, possibly in a separate table with expiration logic.
7. Assigning Teams Based on Discord Roles
Implement the /discordroleteam command which can be executed by OPs to assign players to teams based on their Discord roles.
package com.yourdomain.discordverification;
import net.dv8tion.jda.api.entities.Role;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public class DiscordRoleTeamCommand implements CommandExecutor {
private final DiscordVerification plugin;
public DiscordRoleTeamCommand(DiscordVerification plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.hasPermission("discordroleteam.use") && !sender.isOp()) {
sender.sendMessage(ChatColor.RED + "You don't have permission to use this command.");
return true;
}
if (args.length != 1) {
sender.sendMessage(ChatColor.RED + "Usage: /discordroleteam <player>");
return true;
}
Player target = Bukkit.getPlayer(args[0]);
if (target == null) {
sender.sendMessage(ChatColor.RED + "Player not found.");
return true;
}
UUID uuid = target.getUniqueId();
try {
Connection conn = plugin.getDatabaseConnection();
String query = "SELECT discord_id FROM user_verification WHERE minecraft_uuid = ? AND verified = TRUE";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, uuid.toString());
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
String discordId = rs.getString("discord_id");
Member member = plugin.getJDA().getGuilds().get(0).getMemberById(discordId);
if (member == null) {
sender.sendMessage(ChatColor.RED + "Discord member not found.");
rs.close();
stmt.close();
return true;
}
List<Role> roles = member.getRoles();
// Define role-to-team mapping
Map<String, String> roleTeamMap = new HashMap<>();
roleTeamMap.put("Red Team Role Name", "Red");
roleTeamMap.put("Blue Team Role Name", "Blue");
// Add more roles and their corresponding teams as needed
boolean assigned = false;
for (Role role : roles) {
if (roleTeamMap.containsKey(role.getName())) {
String teamName = roleTeamMap.get(role.getName());
// Assign the player to the team in Minecraft
// Implement team assignment logic here, e.g., using Scoreboard
assignPlayerToTeam(target, teamName);
sender.sendMessage(ChatColor.GREEN + "Assigned " + target.getName() + " to " + teamName + " team based on Discord role.");
assigned = true;
break;
}
}
if (!assigned) {
sender.sendMessage(ChatColor.YELLOW + "No matching Discord role found for " + target.getName() + ".");
}
} else {
sender.sendMessage(ChatColor.RED + "Player is not verified with Discord.");
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
sender.sendMessage(ChatColor.RED + "An error occurred while assigning the team.");
}
return true;
}
private void assignPlayerToTeam(Player player, String teamName) {
// Example using Scoreboard teams
if (player.getScoreboard() == null) {
return;
}
// Create or get the team
org.bukkit.scoreboard.Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
org.bukkit.scoreboard.Team team = scoreboard.getTeam(teamName);
if (team == null) {
team = scoreboard.registerNewTeam(teamName);
// Set team properties as needed
team.setColor(net.md_5.bungee.api.ChatColor.valueOf(teamName.toUpperCase()));
}
team.addEntry(player.getName());
player.sendMessage(ChatColor.GREEN + "You have been assigned to the " + teamName + " team!");
}
}
8. Enhancing with Discord Embeds and Advanced Features
a. Rich Embed Messages
Use Discord embeds to provide better information during verification.
// Example in VerifyCommand when sending the embed
channel.sendMessageEmbeds(
new EmbedBuilder()
.setTitle("Minecraft Verification")
.setDescription(player.getName() + " is verifying their account.")
.addField("Verification Code", code, false)
.setFooter("Use /verify <code> in Discord to link your account.")
.setColor(java.awt.Color.decode(plugin.getEmbedColor()))
.build()
).queue();
b. Automatic Role Assignment on Verification
Upon successful verification, assign a specific Discord role to the user.
// Inside DiscordListener after successful verification
Guild guild = event.getGuild();
Role verifiedRole = guild.getRolesByName("Verified", true).get(0);
guild.addRoleToMember(event.getMember(), verifiedRole).queue();
c. Logging Verification Events
Log verification events to a specific Discord channel for administrators.
public void logVerification(Member member, Player player) {
String logChannelId = plugin.getConfig().getString("log_channel_id");
TextChannel logChannel = plugin.getJDA().getTextChannelById(logChannelId);
if (logChannel != null) {
logChannel.sendMessageEmbeds(
new EmbedBuilder()
.setTitle("User Verified")
.addField("Minecraft", player.getName() + " (" + player.getUniqueId() + ")", false)
.addField("Discord", member.getEffectiveName() + " (" + member.getId() + ")", false)
.setColor(java.awt.Color.GREEN)
.build()
).queue();
}
}
d. Error Handling and Feedback
Provide clear feedback to users in both Minecraft and Discord upon successes or failures.
9. Permissions and Security
Ensure that only authorized users (OPs or those with specific permissions) can execute sensitive commands like /discordroleteam.
- Define Permissions: In
plugin.yml, define necessary permissions.
commands:
verify:
description: Link your Discord account.
usage: /verify <code>
discordroleteam:
description: Assign team based on Discord roles.
usage: /discordroleteam <player>
permission: discordroleteam.use
- Check Permissions in Command Executors: As shown in the
DiscordRoleTeamCommand example.
10. Complete plugin.yml
Ensure your plugin.yml includes all commands and permissions.
name: DiscordVerification
version: 1.0
main: com.yourdomain.discordverification.DiscordVerification
api-version: 1.19
commands:
verify:
description: Link your Discord account.
usage: /verify <code>
discordroleteam:
description: Assign team based on Discord roles.
usage: /discordroleteam <player>
permission: discordroleteam.use
permissions:
discordroleteam.use:
description: Allows user to assign teams based on Discord roles.
default: op
Additional Advanced Features
- Web Dashboard: Create a web interface for players to manage their verification and view teams.
- Automatic Role Synchronization: Automatically update Minecraft teams when Discord roles change.
- Notifications: Notify users in Discord or Minecraft when they are assigned to a new team.
- Command Feedback in Discord: Allow administrators to manage teams directly from Discord commands.
- Multi-Discord Server Support: Handle multiple Discord servers if needed.
Final Notes
- Testing: Thoroughly test each component individually and then together to ensure seamless integration.
- Security: Protect the Discord bot token and ensure database queries are secure against SQL injection.
- Scalability: If your server grows, consider using more robust databases and optimizing Discord interactions to handle higher loads.
- Error Handling: Implement comprehensive error handling to manage API failures or unexpected issues gracefully.
By following this guide, you can create a robust Minecraft to Discord verification system leveraging both the Paper API and Discord's rich features. Customize and expand upon this foundation to suit your server's specific needs and enhance the user experience.