How to add reaction to an embed message JDA - java

I'm trying to send and embed message when I do the command ~verify and then it sends an embed message and I cant find how to add to there a reaction.
I did already the embed message and sent it but can add the reaction
import Main.Bot;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import java.awt.*;
public class Verify extends ListenerAdapter {
#Override
public void onGuildMessageReceived(GuildMessageReceivedEvent e){
if(e.getAuthor().isBot()) return;
if(e.getMessage().getContentRaw().equalsIgnoreCase(Bot.prefix+"verify")){
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setColor(Color.red);
embedBuilder.setTitle("Verify yourself!");
embedBuilder.addField("How?","Press the ✔ reaction to verify",false);
embedBuilder.setFooter("Created by SlayZBro#3501",e.getGuild().getIconUrl());
e.getChannel().sendTyping().queue();
e.getChannel().sendMessage(embedBuilder.build()).queue();
embedBuilder.clear();
}
}
}
I need to add the reaction to the embed message

You can access the sent message in the callback for queue() and add reactions there:
channel.sendMessage(embed).queue(message -> message.addReaction(reaction).queue());
To add multiple questions you can use a multiline lambda:
channel.sendMessage(embed).queue(message -> {
message.addReaction(reaction1).queue();
message.addReaction(reaction2).queue();
message.addReaction(reaction3).queue();
});
Also there is no reason to clear the EmbedBuilder because it won't be used again in your code. Builders are usually not resources that need to be closed/cleared unless you use them again and don't want the previous settings.

I understood how to do it. Just need to add this line
e.getChannel().sendMessage(embedBuilder.build()).complete().addReaction("✔").queue();

Related

Why I can't send embed messages to my discord bot?

I'm trying to make a simple discord bot. Unfortunately, I ran into a problem where I can't send embedded messages specifically "event.getChannel().sendMessage(embed.build()).queue();" this line of code is not working. Any help would be appreciated!
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class Commands extends ListenerAdapter {
public String prefix = "!";
#Override
public void onMessageReceived(MessageReceivedEvent event) {
String[] args = event.getMessage().getContentRaw().split(" ");
if(args[0].equalsIgnoreCase(prefix + "test")){
EmbedBuilder embed = new EmbedBuilder();
embed.setTitle("Title");
embed.setDescription("This is the Embed Description");
embed.addField("Embed Field 1", "Field", false);
embed.setFooter("Bot created by toMar?s");
//event.getMessage().reply("This bot is working!").queue();
event.getChannel().sendMessage("This bot is working!").queue();
event.getChannel().sendMessage(embed.build()).queue();
}
}
}
You have to change the .sendMessage() to .sendMessageEmbeds(). Probably because .sendMessage() needs some type of character sequence but I did not provide that.

How to send a DM to someone WITH response in JDA

I am coding a feedback feature in my Discord Bot, when someone leaves, they should be DMed a message asking why they left.
event.getUser().openPrivateChannel()
.flatMap(channel -> channel.sendMessage("Hello, we are sorry you're leaving "+event.getGuild().getName()+", if you don't mind, please tell us why you left or leave any other feedback here, it'll help us improve the server and improve experience for you if you re-join again in the future.\n\nThank you ❤."))
.queue();
The code above is responsible for sending it, I tried to create a state machine in a private channel but it didn't work:
import bot.Main;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class Feedback extends ListenerAdapter {
private final long channelId, authorId;
public Feedback(MessageChannel channel, User author) {
this.channelId = channel.getIdLong();
this.authorId = author.getIdLong();
}
#Override
public void onMessageReceived(MessageReceivedEvent event) {
if (event.getAuthor().isBot()) return;
if (event.getAuthor().getIdLong() != authorId) return;
if (event.getChannel().getIdLong() != channelId) return;
MessageChannel channel = event.getChannel();
String content = event.getMessage().getContentRaw();
event.getChannel().sendMessage("Thanks for your feedback!").queue();
EmbedBuilder feedback = new EmbedBuilder();
feedback.setTitle("Automated System Operations - Leaving Feedback");
feedback.addField("Feedback", content, false);
feedback.setColor(0xC90004);
feedback.setAuthor(event.getAuthor().getAsTag()+" - "+event.getAuthor().getId(), "https://support.discord.com/hc/en-us/articles/209572128-How-do-I-log-out-", event.getAuthor().getAvatarUrl());
feedback.setImage("https://media.discordapp.net/attachments/894913784823566428/896323821336948736/unknown.png?width=384&height=192");
Main.jda.getGuildById("894913620868202506").getTextChannelById("896322509874540545").sendMessage(feedback.build()).queue();
}
}
I got this event state-machine channel but I don't know how to addListener to it in DMs.
Any help is accepted <3
You can add the state machine event listener with JDA#addEventListener:
event.getUser().openPrivateChannel().flatMap(channel -> {
event.getJDA().addEventListener(new Feedback(channel, event.getUser()));
return channel.sendMessage("hello");
}).queue();
I would recommend to remove your event listener after you received that response with event.getJDA().removeEventListener(this);
You never have to guess how to use a library - that's what documentation is for. Any library worth its salt has documentation listing every single class, method, and the property you need to worry about.
A quick google search for "discord-jda docs" takes us to the JavaDoc: https://ci.dv8tion.net/job/JDA/javadoc/index.html
You want to send a message to a user, right? So let's use the search bar and find User. First result under Types is net.dv8tion.jda.API.entities.User. We're now at https://ci.dv8tion.net/job/JDA/javadoc/net/dv8tion/jda/api/entities/User.html
If you want to know how to do something with a user, we look at the Methods every User has. Two catch my eye right away: User.hasPrivateChannel() and User.openPrivateChannel(). We'll click the second one since it looks relevant.
Lo and behold, the docs have example usage! I'll quote it below:
// Send message without response handling
public void sendMessage(User user, String content) {
user.openPrivateChannel()
.flatMap(channel -> channel.sendMessage(content))
.queue();
}
This seems pretty straightforward. So the basic usage you're looking for (assuming event is a MessageReceivedEvent) is this:
event.getAuthor().openPrivateChannel().flatMap(channel -> channel.sendMessage("hello")).queue();

/me in minecraft isnt disabled by the plugin I wrote

So in my server /me is an enabled command. I wanted to disable this because I don't want people to be able to do this.
I'm learning java, so I decided to code something that disabled /me myself.
So I wrote the following code:
package com.ste999.disableme;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class Main extends JavaPlugin implements Listener
#Override
public void onEnable() {
getLogger().info("disable me enabled");
PluginManager pm = this.getServer().getPluginManager();
pm.registerEvents(this, (this));
}
#Override
public void onDisable() {
getLogger().info("disable me disabled");
}
#EventHandler
public void OnMe(AsyncPlayerChatEvent event)
{
Player p = event.getPlayer();
if(!p.hasPermission("ste999.me")) {
if (event.getMessage().startsWith("/me")) {
event.setCancelled(true);
p.sendMessage("§4Dont me me!");
}
}
}
}
with the following plugin.yml file:
name: Disable_Me
main: com.ste999.disableme.Main
version: 1.0
load: startup
description: this is should disable me
commands:
Now if someone without op would run /me hello it shouldn't output to the chat and the user should get a message like Dont me me!
But it doesn't. the user is still able to do /me hello without op and the code should prevent that
As I'm fairly new to java this error is probably easy to find, and any help would be much appreciated.
The problem is that AsyncPlayerChatEvent only gets called when actually typing chat messages (not commands). For commands you have to use PlayerCommandPreprocessEvent as wonderfully explained by Mischa in the comments. Changing the event will make it work:
#EventHandler
public void disableMeCommand(PlayerCommandPreprocessEvent event) {
Player p = event.getPlayer();
if(!p.hasPermission("ste999.me")) {
if(event.getMessage().startsWith("/me")) {
event.setCancelled(true);
p.sendMessage("§4Dont me me!");
}
}
}
However, note that PlayerCommandPreprocessEvent should be avoided. Luckily there is another way to disable a command completely in a bukkit server. You should have a commands.yml file located in your server folder. Simply add the "me" alias and set it to null inside the file:
aliases:
me:
- null

Unable to change system string resource

I am making a Xposed Module that would allow users to modify the message displayed on the lock screen when Wrong pattern, pin or password is entered.
I am following this tutorial.
After digging into the android source code on GitHub, I found out the method that displays the message on the lock screen, that was onPatternChecked() in the class com.android.keyguard.KeyguardPatternView.java. The method uses the kg_wrong_pattern string resource which has the value Wrong Pattern when wrong pattern is drawn.
This is how my class looks like:-
package com.batrashubham.customlockscreenerrormessage;
import android.content.res.XResources;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_InitPackageResources;
/**
* Created by shubham on 19/7/16.
*/
public class CustomErrorMessage implements IXposedHookInitPackageResources,IXposedHookZygoteInit {
#Override
public void initZygote(StartupParam startupParam) throws Throwable {
XResources.setSystemWideReplacement("android","bool","config_unplugTurnsOnScreen",false);
}
#Override
public void handleInitPackageResources(XC_InitPackageResources.InitPackageResourcesParam resparam) throws Throwable {
if(!resparam.packageName.equals("com.android.keyguard")){
return;
}
XposedBridge.log("I just got into your lock screen");
resparam.res.setReplacement("com.android.keyguard", "string", "kg_wrong_pattern", "Nice try.!!");
}
}
The module is showing up in the Xposed Installer app and is successful activated, but still the original message is showing up on the lock screen when I draw a wrong pattern.
I am currently testing it on Android 6.0.1 (CyanogenMod 13).
What am I doing wrong?

Intellij Completion Contributor

I am developing a plugin for intellij and I want to add custom suggestions to xml editor based on a xsd. Up to now I can get required suggestions from xsd file.
I have implemented a completion contributor for xml as follows
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.xml.XmlElementType;
import com.intellij.util.ProcessingContext;
import com.intellij.lang.xml.*;
import org.jetbrains.annotations.NotNull;
public class SimpleCompletionContributor extends CompletionContributor {
public SimpleCompletionContributor() {
extend(CompletionType.BASIC,PlatformPatterns.psiElement(XmlElementType.XML_ATTRIBUTE_VALUE).withLanguage(XMLLanguage.INSTANCE),
new CompletionProvider<CompletionParameters>() {
public void addCompletions(#NotNull CompletionParameters parameters,
ProcessingContext context,
#NotNull CompletionResultSet resultSet) {
resultSet.addElement(LookupElementBuilder.create("Hello"));
}
}
);
}
}
but this did not provide any suggestion. but when I implement custom language it works. My objective is to view the context of the cursor position and provide suggestion based on it. as an example when user starts a tag on xml file plugin should provide attributes as code completion. I'm new to this Custom language.
So can anyone help me with this completion contributor?
finally i found a way to solve this problem
here is my code
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NotNull;
public class ScalaXMLCompletionContributor extends CompletionContributor {
public ScalaXMLCompletionContributor() {
final RelativeNodes rlt = new RelativeNodes();//this is a class to get siblings and children from a sample xml file generated by a given xsd
/*if the parameter position is an xml attribute provide attributes using given xsd*/
extend(CompletionType.BASIC,
PlatformPatterns.psiElement(), new CompletionProvider<CompletionParameters>() {
public void addCompletions(#NotNull CompletionParameters parameters,//completion parameters contain details of the curser position
ProcessingContext context,
#NotNull CompletionResultSet resultSet) {//result set contains completion details to suggest
if (parameters.getPosition().getContext().toString() == "XmlAttribute") {//check whether scala text editors position is an xml attribute position eg: <name |
try {
String[] suggestions = rlt.getAttribute(parameters.getPosition().getParent().getParent().getFirstChild().getNextSibling().getText().replaceFirst("IntellijIdeaRulezzz", ""));//extract text from completion parameter and get required suggestions from RelativeNodes
int i = 0;
do {
resultSet.addElement(LookupElementBuilder.create(suggestions[i]));//add suggestions to resultset to suggest in editor
i++;
} while (suggestions[i] != null);
} catch (NullPointerException e) {
}
}
}
}
);
}
}
in this case we can obtain cursor position and tokens related to curser position by completion parameters and we can inject suggestions using cpmpletion resultset. this can be implemented in scala language too.
to register completion contributor in plugin xml
<extensions defaultExtensionNs="com.intellij">
<completion.contributor language="Scala" implementationClass="com.hsr.ScalaXMLCompletionContributor"/>
</extensions>
JavaDoc for com.intellij.codeInsight.completion.CompletionContributor contains FAQ.
The last question addresses debugging not working completion.
In my case issue was language="Java", whereas all caps expected.

Categories