game_master229

Make a discord bot that can call with other discord servers in chat

Kodari AI
KodariOct 17 at 12:47 am 1
CrossServerChatBridge
A Minecraft plugin that connects Discord servers to the in-game chat, enabling seamless cross-communication. Players can send messages to linked Discord channels and receive replies from Discord users directly in-game. Features include configurable channel linking, message formatting with player names and Discord usernames, optional webhook integration for rich embeds, command-based linking, and permission-based control. The plugin maintains persistent connections via JDA, handles reconnection logic, and supports multiple Discord servers simultaneously. Chat messages are relayed bidirectionally with customizable prefixes, colors, and placeholders, providing a unified communication experience between Minecraft and Discord communities.

I’ll create a Java/JDA bot that relays messages between configured Discord text channels, with the channel IDs and bot token supplied through environment variables.

Created a Discord chat bridge. Set DISCORD_TOKEN and BRIDGE_CHANNEL_IDS (comma-separated text-channel IDs) as environment variables. Add the bot to each server with permission to view and send messages in those channels, and enable Message Content Intent in the Discord Developer Portal. Messages posted in any configured channel will be relayed to the others.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
manifest.kod
Code
3 125
src/main/java/com/kodari/chatbridge/Main.java
package com.kodari.chatbridge;

import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.requests.GatewayIntent;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public final class Main {
    private Main() {
    }

    public static void main(String[] args) throws InterruptedException {
        String token = requiredEnvironmentVariable("DISCORD_TOKEN");
        Set<String> channelIds = Stream.of(requiredEnvironmentVariable("BRIDGE_CHANNEL_IDS").split(","))
                .map(String::trim)
                .filter(channelId -> !channelId.isEmpty())
                .collect(Collectors.toCollection(LinkedHashSet::new));

        if (channelIds.size() < 2) {
            throw new IllegalArgumentException("BRIDGE_CHANNEL_IDS must contain at least two comma-separated text channel IDs.");
        }

        JDA jda = JDABuilder.createDefault(token)
                .enableIntents(GatewayIntent.MESSAGE_CONTENT)
                .addEventListeners(new ChatBridge(channelIds))
                .build();
        jda.awaitReady();
        System.out.println("Chat bridge is online for " + channelIds.size() + " channels.");
    }

    private static String requiredEnvironmentVariable(String name) {
        String value = System.getenv(name);
        if (value == null || value.isBlank()) {
            throw new IllegalStateException("Set the " + name + " environment variable before starting the bot.");
        }
        return value;
    }

    private static final class ChatBridge extends ListenerAdapter {
        private final Set<String> channelIds;

        private ChatBridge(Set<String> channelIds) {
            this.channelIds = Set.copyOf(channelIds);
        }

        @Override
        public void onMessageReceived(MessageReceivedEvent event) {
            Message message = event.getMessage();
            String sourceChannelId = event.getChannel().getId();
            if (message.getAuthor().isBot() || message.isWebhookMessage() || !channelIds.contains(sourceChannelId)) {
                return;
            }

            String text = message.getContentDisplay();
            for (Message.Attachment attachment : message.getAttachments()) {
                if (!text.isEmpty()) {
                    text += "\n";
                }
                text += attachment.getUrl();
            }
            if (text.isBlank()) {
                return;
            }

            String displayName = event.getMember() == null
                    ? message.getAuthor().getName()
                    : event.getMember().getEffectiveName();
            String relayedMessage = ("[" + event.getGuild().getName() + "] " + displayName + ": " + text)
                    .replace("@", "@\u200B");
            if (relayedMessage.codePointCount(0, relayedMessage.length()) > 2000) {
                relayedMessage = relayedMessage.substring(0, relayedMessage.offsetByCodePoints(0, 1997)) + "...";
            }

            for (String targetChannelId : channelIds) {
                if (targetChannelId.equals(sourceChannelId)) {
                    continue;
                }
                TextChannel target = event.getJDA().getTextChannelById(targetChannelId);
                if (target == null) {
                    System.err.println("Bridge channel is unavailable: " + targetChannelId);
                    continue;
                }
                target.sendMessage(relayedMessage).queue(
                        ignored -> { },
                        error -> System.err.println("Could not relay message to " + targetChannelId + ": " + error.getMessage())
                );
            }
        }
    }
}