I'm making a JDA (Java Discord API) program that needs to check if a message was sent by the bot itself. How can I achieve this? I thought about checking if the user ID of the message sender equals the bot's user ID, but how can I get the user ID of the bot itself in the program?
If you use the MessageReceivedEvent, you can just check if the sender is a bot by using:
event.getAuthor.isBot().
You can access the user of the bot itself by accessing JDA and calling getSelfUser() as follows with the MessageReceivedEvent in mind:
event.getJDA().getSelfUser()
On the SelfUser you can call SelfUser#getId() or SelfUser#getIdLong() to access the ID.
Example Code
public class Listener extends ListenerAdapter {
#Override
public void onMessageReceived(MessageReceivedEvent event) {
boolean isBot = event.getAuthor().isBot() //Check if the Message Sender is a bot
long id = event.getJDA().getSelfUser().getIdLong() //the bot ID
}
}
Related
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?
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)
You get the error message because channel is not within the scope of
onMessageReceived() You need to learn about scopes.
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()
`public class VerificationSystem extends ListenerAdapter {
#Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
System.out.println("WORKS!");
String memberName = event.getMember().getEffectiveName();
Member member = event.getMember();
event.getGuild().addRoleToMember(member,event.getGuild().getRoleById("1034143551568752682")).queue(); //Grants the new member "Unverified" role
TextChannel textChannel = event.getGuild().createTextChannel("Verification for: " + memberName).complete(); // Creates new verification channel
textChannel.getManager().getChannel().upsertPermissionOverride(event.getMember()).setAllowed(Permission.VIEW_CHANNEL).queue(); // Grants the new member view permissions to the channel
textChannel.getManager().getChannel().upsertPermissionOverride(event.getGuild().getRoleById("1034143551568752682")).setDenied(Permission.VIEW_CHANNEL).queue(); // Revokes the view permission for #everyone
}`
The event register:
JDA jda = JDABuilder.createDefault(token)
.setActivity(Activity.playing("Football Manager"))
.addEventListeners(new VerificationSystem())
.build().awaitReady();
For some reason this method does not work. It is correctly registered, and it does not work whenever someone joins the server. Please help, this is killing me!!
Since one of updates Discord added such thing as "Intents". Now all developers have to specify what kind of data their bots need.
To accept events of members' joining you need to use intent "GUILD_MEMBERS". Note that this intent is priveleged, what means you can use it easily until your bot reaches 100 servers, then you must get verification from Discord.
To enable intents in bot visit Developers portal
To enable intents in JDA use enableIntents method in builder.
JDA jda = JDABuilder.createDefault(token)
.setActivity(Activity.playing("Football Manager"))
.addEventListeners(new VerificationSystem())
// Enables GUILD_MEMBERS intent
.enableIntents(GatewayIntent.GUILD_MEMBERS)
.build().awaitReady();
I'm trying to make a simple Discord Bot within a Minecraft Mod, and it doesn't work. I do have to say that I am new to coding discord bots in java, as I am more based to javascript.
Here is what I made:
DiscordBot.java
public class DiscordBot
{
public JDA jda;
private String token = "----";
public static DiscordBot instance = new DiscordBot();
#SuppressWarnings("deprecation")
public void startDiscordBot() throws LoginException
{
jda = new JDABuilder()
.setToken(token)
.setStatus(OnlineStatus.DO_NOT_DISTURB)
.addEventListeners(new DiscordEventListener())
.build();
}
}
DiscordEventListener.java
public class DiscordEventListener extends ListenerAdapter
{
#Override
public void onMessageReceived(MessageReceivedEvent event)
{
if(event.getMessage().getContentRaw().equals("-login"))
{
EmbedBuilder eb1 = new EmbedBuilder();
EmbedBuilder eb2 = new EmbedBuilder();
event.getAuthor().openPrivateChannel().queue(channel -> {
eb2.setColor(Color.MAGENTA);
eb2.setTitle(placeholder-text);
eb2.setDescription(placeholder-text);
channel.sendMessage(eb2.build());
});
The DiscordEventListener takes "-login" and responds with the rest of the code, but the problem is, while the bot does go online, it doesn't do anything when I send -login in the discord server, nor dms. Also no errors occur on launch neither on the event. Also, I have a depricated version of JDA (4.2.1) because I don't understand how to use the new one.
I tried multiple little things but they showed 0 results, so I don't know what is wrong here.
(Also yes, I have initialised the DiscordBot class in the Main one, so I don't think that is the problem)
#dan1st figured it out, I forgot to add .queue(); to the end of channel.sendMessage, so thanks to them.
I tried tracking if people on the bots guild change activities (like starting to play a game)
After reading the javadoc I found out:
GatewayIntent.GUILD_PRESENCES
CacheFlag.ACTIVITY
MemberCachePolicy.ONLINE (therefore GatewayIntent.GUILD_MEMBERS)
must be active.
so thats my Main:
JDABuilder builder = JDABuilder.createDefault(token);
builder.enableIntents(GatewayIntent.GUILD_PRESENCES);
builder.enableIntents(GatewayIntent.GUILD_MEMBERS);
builder.enableCache(CacheFlag.ACTIVITY);
builder.setMemberCachePolicy(MemberCachePolicy.ONLINE);
builder.setChunkingFilter(ChunkingFilter.ALL);
this.jda = builder.build();
jda.addEventListener( new ActivityListener(jda));
And this my Listener:
public class ActivityListener extends ListenerAdapter {
private final JDA jda;
public ActivityListener(JDA jda) {
this.jda = jda;
}
#Override
public void onUserUpdateActivities(#NotNull UserUpdateActivitiesEvent event) {
super.onUserUpdateActivities(event);
System.out.println(event.getUser().getAsTag() + " " + event.getUser().getIdLong());
}
}
Sadly when I or someone else starts a game or smt else it never triggers.
Edit:
I used jda.getUserCache(); to check if the caching worked and I am i the cache, but it still doesn't work.
The members for the associated users have to be cached before the event fires. Since you use lazy loading this might take a while to happen since members are added to cache through messages or voice states.
You can use setChunkingFilter(ChunkingFilter.ALL) to eagerly load all members on startup.
There was a bug which caused these events to not fire which has been fixed in 4.2.1_264.
the UserUpdateActivitiesEvent requires the GuildPresence intent to be enabled. You enabled it in your code, but it has to also be enabled on the discord api website at https://discord.com/developers/applications -> Your Application -> Bot -> Enable Presence Intent
I have written the following methods and they both are not working. Anyone know why and how to fix it?
PS: The bot has admin perms.
public class GuildMemberJoin extends ListenerAdapter {
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
EmbedBuilder join = new EmbedBuilder();
join.setColor(Color.getHSBColor(227, 74, 64));
join.setTitle("SERVER UPDATE");
join.setDescription(event.getMember().getAsMention() + " has now joined The server!");
event.getGuild().getDefaultChannel().sendMessage(join.build()).queue();
}
public class GuildMemberLeave extends ListenerAdapter {
public void onGuildMemberLeave(GuildMemberLeaveEvent event) {
EmbedBuilder join = new EmbedBuilder();
TextChannel spamChannel = event.getGuild().getTextChannelById("713429117546135572");
join.setColor(Color.getHSBColor(227, 74, 64));
join.setTitle("SERVER UPDATE");
join.setDescription(event.getMember().getAsMention() + " has now left the server!");
spamChannel.sendMessage(join.build()).queue();
}
Default channel settings
To quote the JDA Wiki:
There are many reasons why your event listener might not be executed but here are the most common issues:
You are using the wrong login token?
If the token is for another bot which doesn't have access to the desired guilds then the event listener code cannot run.
Your bot is not actually in the guild?
Make sure your bot is online and has access to the resource you are trying to interact with.
You never registered your listener?
Use jda.addEventListener(new MyListener()) on either the JDABuilder or JDA instance
You did not override the correct method?
Use #Override and see if it fails. Your method has to use the correct name and parameter list defined in ListenerAdapter.
You don't actually extend EventListener or ListenerAdapter.
Your class should either use extends ListenerAdapter or implements EventListener.
You are missing a required GatewayIntent for this event.
Make sure that you enableIntents(...) on the JDABuilder to allow the events to be received.
The event has other requirements that might not be satisfied such as the cache not being enabled.
Please check the requirements on the event documentation.
If none of the above apply to you then you might have an issue in your listener's code, at that point you should use a debugger.
For clarification:
You can enable the GUILD_MEMBERS intent by doing builder.enableIntents(GatewayIntent.GUILD_MEMBERS) on JDABuilder.
For example:
JDABuilder builder = JDABuilder.createDefault(token);
builder.enableIntents(GatewayIntent.GUILD_MEMBERS);
builder.addEventListeners(myListener);
JDA jda = builder.build();
See also: Gateway Intents and Member Cache Policy