Alex Cai
Alex Cai

Reputation: 33

Transfer messages from direct message to specific channel using Java Discord API

I want to make my bot in a server channel to say whatever an user dm it.

public class PrivateMessage extends ListenerAdapter
{
    private TextChannel channel;

    @Override
    public void onReady(@NotNull ReadyEvent event)
    {
        channel = event.getJDA().getChannelById(TextChannel.class, 962688156942073887L);
    }

    @Override
    public void onMessageReceived(@NotNull MessageReceivedEvent event)
    {
        if (event.isFromType(ChannelType.PRIVATE))
            channel.sendMessage(MessageCreateData.fromMessage(event.getMessage())).queue();
    }
}

At first it was working properly, until I dm it an image.

java.lang.IllegalStateException: Cannot build an empty message. You need at least one of content, embeds, components, or files

How can I fix this?

Upvotes: 0

Views: 385

Answers (1)

Loso
Loso

Reputation: 84

  1. The channel is not declared properly. It does not have a type... In this case you should use either TextChannel channel = (whatever) or Channel channel = (whatever)
  2. You get the error message because channel is not within the scope of onMessageReceived() You need to learn about scopes.
  3. The onReady() will have no use in this case. Just as i mentioned before... Because of scopes.

Here is what your code should look like:

    @Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) {
    if(event.isFromType(ChannelType.PRIVATE)){
        TextChannel textChannel = event.getJDA().getGuildById("1046510699809079448").getTextChannelById("1046510701184831540");
        textChannel.sendMessage(event.getMessage().getContentRaw()).queue();
    }

You need to get the TextChannel from a Guild by using their ID's. Then you can get the message that was sent to the bot, by using event.getMessage() and getting its content via .getContentRaw() and send it using textChannel.sendMessage().queue()

Upvotes: 0

Related Questions