JDA Send DM to pinged roles - java

package com.commands;
import com.company.Main;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;
public class MassDM extends ListenerAdapter {
#Override
public void onGuildMessageReceived(#NotNull GuildMessageReceivedEvent event) {
super.onGuildMessageReceived(event);
String[] args = event.getMessage().getContentRaw().split(" ");
if(args[0].equalsIgnoreCase(Main.BOT_PREFIX+"massdm")){
Role role = event.getMessage().getMentionedRoles().get(0);
for(Member member: event.getGuild().getMembersWithRoles(role)){
System.out.println(member);
try{
System.out.println(member.toString());
member.getUser().openPrivateChannel()
.flatMap(channel -> channel.sendMessage("Hello sir"))
.queue();
}catch (Exception e){
}
}
}
}
}
Hello, So I am writing a discord bot to dm people with a specific role. In my code, however, didn't work, what did i miss? I am using JDA 4.3

Related

JDA Will not register my event(Discord Bot Java)

I've been having a problem with registering JDA events. Everytime I start the bot, it shows this. Can someone help me with this please?
Here's my Main code:
import Events.Information;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import javax.security.auth.login.LoginException;
public class Main {
public static String prefix = "!";
public static void main(String[] args) throws LoginException {
JDABuilder jda = JDABuilder.createDefault("I inserted bot key here");
jda.setActivity(Activity.watching("baldness"));
jda.addEventListeners(new Information());
jda.build();
}
}
Here's my Information class code:
package Events;
import com.sun.tools.javac.Main;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
public class Information {
public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
String[] args = e.getMessage().getContentRaw().split("\\s+");
if (args[0].equals("!commands")) {
EmbedBuilder info = new EmbedBuilder();
info.setTitle("Commands");
info.setDescription("!info - Pops up with this!");
info.setColor(0xf45642);
info.setFooter("Bot created by Jason", e.getMember().getUser().getAvatarUrl());
e.getChannel().sendTyping().queue();
e.getChannel().sendMessage(info.build()).queue();
}
}
}
Here's my layering of classes and packages:
Image

Cannot read email body with Spring: javax.mail.FolderClosedException

I'm trying to listen my Gmail inbox for incoming mails. Every time new mail arrives, I want to see it's subject and content.
So far, I have this:
import java.io.IOException;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.mail.util.MimeMessageParser;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mail.transformer.MailToStringTransformer;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
public class GmailInboundImapIdleAdapterTestApp {
private static Log logger = LogFactory.getLog(GmailInboundImapIdleAdapterTestApp.class);
public static void main (String[] args) throws Exception {
#SuppressWarnings("resource")
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("/META-INF/spring/integration/gmail-imap-idle-config.xml");
DirectChannel inputChannel = ac.getBean("receiveChannel", DirectChannel.class);
inputChannel.subscribe(new MessageHandler() {
public void handleMessage(Message<?> message){
MimeMessage mm = (MimeMessage) message.getPayload();
try {
System.out.println("Subject: "+mm.getSubject());
System.out.println("Body: "+readPlainContent(mm));
}
catch (javax.mail.MessagingException e) {
System.out.println("MessagingException: "+e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
e.printStackTrace();
}
}
});
}
private static String readHtmlContent(MimeMessage message) throws Exception {
return new MimeMessageParser(message).parse().getHtmlContent();
}
private static String readPlainContent(MimeMessage message) throws Exception {
return new MimeMessageParser(message).parse().getPlainContent();
}
}
It can read the mail subject correctly. But no luck with mail body.javax.mail.FolderClosedException hit me. How to fix this?
As Gary said: simple-content="true" or since recently autoCloseFolder = false: https://docs.spring.io/spring-integration/docs/5.2.0.RELEASE/reference/html/mail.html#mail-inbound
Starting with version 5.2, the autoCloseFolder option is provided on the mail receiver. Setting it to false doesn’t close the folder automatically after a fetch, but instead an IntegrationMessageHeaderAccessor.CLOSEABLE_RESOURCE header (see MessageHeaderAccessor API for more information) is populated into every message to producer from the channel adapter. It is the target application’s responsibility to call the close() on this header whenever it is necessary in the downstream flow:

How to get the email-verification link inside my custom SPI in keycloak

I have my code below, this is inside my notification-spi project, which get triggered when a new user is created. I am able to receive the email. However i don't know how i can get the email-verification link when RequiredActions verify-email is selected by the admin who created the account in keycloak admin ui.
public void onEvent(AdminEvent adminEvent, boolean includeRepresentation) {
EmailSenderProvider emailSender = session.getProvider(EmailSenderProvider.class);
RealmModel realm = session.realms().getRealm(adminEvent.getRealmId());
UserModel user = session.userCache().getUserById(adminEvent.getAuthDetails().getUserId(),
realm);
if (OperationType.CREATE.equals(adminEvent.getOperationType())) {
LOGGER.info("OPERATION CREATE USER");
LOGGER.info("Representation : " + adminEvent.getRepresentation());
try {
LOGGER.info("Sending email...");
emailSender.send(realm.getSmtpConfig(), user, "Account Enrollment",
"A new account has been created using your email.",
"<h1>Account Enrollment</h1> <br/>"
+ "<p>A new account has been created using your email</p>");
LOGGER.info("Email has been sent.");
} catch (EmailException e) {
LOGGER.info(e.getMessage());
}
}
}
}
Any help is appreciated.
You probably don't need this anymore, but this thread was the first result when I searched for how to get verification link in SPI. I guess other people can find it useful. After some time i came up with smth like this:
import org.jboss.logging.Logger;
import org.keycloak.authentication.actiontoken.execactions.ExecuteActionsActionToken;
import org.keycloak.authentication.actiontoken.verifyemail.VerifyEmailActionToken;
import org.keycloak.common.util.Time;
import org.keycloak.email.EmailException;
import org.keycloak.email.EmailTemplateProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.services.Urls;
import org.keycloak.services.resource.RealmResourceProvider;
import org.keycloak.services.resources.LoginActionsService;
import org.keycloak.sessions.AuthenticationSessionCompoundId;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.util.*;
import java.util.stream.Collectors;
public class CustomResourceProvider implements RealmResourceProvider {
private static final Logger log = Logger.getLogger(CustomResourceProvider.class);
private final KeycloakSession session;
public CustomResourceProvider(KeycloakSession session) {
this.session = session;
}
#GET
#Path("users/test2")
#Produces({MediaType.APPLICATION_JSON})
public Response sendVerificationLink() throws EmailException {
RealmModel realm = session.getContext().getRealm();
final Map<String, String> searchParams = new HashMap<String, String>() {{
put("emailVerified", "false");
}};
final List<UserModel> users = session
.users()
.searchForUserStream(realm, searchParams)
.collect(Collectors.toList());
EmailTemplateProvider emailTemplateProvider = session.getProvider(EmailTemplateProvider.class);
for (UserModel user : users) {
int expiration = Time.currentTime() + 1000000;
VerifyEmailActionToken token = new VerifyEmailActionToken(
user.getId(),
expiration,
"oasid",
user.getEmail(),
"localdev"
);
UriBuilder builder = LoginActionsService.actionTokenProcessor(session.getContext().getUri());
builder.queryParam("key", token.serialize(session, realm, session.getContext().getUri()));
String verificationLink = builder.build(realm.getName()).toString();
emailTemplateProvider
.setRealm(realm)
.setUser(user)
.sendVerifyEmail(verificationLink, 100000);
}
return Response
.status(Response.Status.OK)
.entity(users.size())
.build();
}
#Override
public Object getResource() {
return this;
}
#Override
public void close() {
}
}

SpringWebSockets does not send message from server

Hi i have an issue with spring websockets, this is the scenario:
a standalone application is sending (remote) some data like date Date, procedence String, and weight BigDecimal this data is sending via TCP to socket,
after that this data is saving into database at this point all is fine, but in the next step (websocket) i cannot show this information in a webpage, the weight data must be showed (live) in the screen
this is my websocket configuration:
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver;
import org.springframework.messaging.handler.invocation.HandlerMethodReturnValueHandler;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
#Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
registry.addEndpoint("/indicator").withSockJS();
}
#Override
public void configureClientInboundChannel(final ChannelRegistration registration) {
}
#Override
public void configureClientOutboundChannel(final ChannelRegistration registration) {
}
#Override
public void configureMessageBroker(final MessageBrokerRegistry registry) {
}
#Override
public void configureWebSocketTransport(WebSocketTransportRegistration wstr) {
}
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {
}
#Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> list) {
}
#Override
public boolean configureMessageConverters(List<MessageConverter> list) {
return Boolean.TRUE;
}
}
this is my another class that receive data form socket and process information and send to websocket:
import com.mcss.mcontrols.helper.ByteHelper;
import com.spc.basweb.Constants;
import com.spc.basweb.transmissor.dto.Transmission;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.core.MessageSendingOperations;
import org.springframework.messaging.simp.broker.BrokerAvailabilityEvent;
import com.spc.basweb.service.BroadcastingService;
import com.spc.basweb.service.DataProcessorService;
import java.io.IOException;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
#MessageEndpoint
public class BroadcastingServiceImpl implements BroadcastingService, ApplicationListener<BrokerAvailabilityEvent> {
private static final Logger LOGGER = Logger.getLogger(BroadcastingServiceImpl.class);
private final MessageSendingOperations<String> messagingTemplate;
private String processedData;
#Autowired
DataProcessorService dataProcessorService;
#Autowired
public BroadcastingServiceImpl(final MessageSendingOperations<String> messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
#Override
public String getProcessedData() {
return processedData;
}
#Override
#ServiceActivator(inputChannel = "broadcaster")
public String broadcast(byte[] bytes) {
try {
Transmission t = (Transmission) ByteHelper.toObject(bytes);
LOGGER.debug(t.getProcedence() + " " + t.getDate() + " " + t.getWeight());
String rm = this.dataProcessorService.processData(t);
this.messagingTemplate.convertAndSend(Constants.END_POINT_READ, this.dataProcessorService.getWeighing().getWeight().toString());
return rm;
} catch (IOException | ClassNotFoundException ex) {
LOGGER.error("Error de transmision de objetos", ex);
}
return DataProcessorService.NOT_OK_RESPONSE;
}
#Override
public void onApplicationEvent(BrokerAvailabilityEvent e) {
LOGGER.debug("Application event");
}
#Transformer(outputChannel = "broadcaster")
public String convert(String response) {
return response;
}
}
in the debbuger i'm getting this information:
30-03-2016 15:07:20 DEBUG SimpleBrokerMessageHandler:277 - Processing MESSAGE destination=/read session=null payload=3003
in another class (Controller) i'm using the same method:
this.messagingTemplate.convertAndSend(Constants.END_POINT_READ, "3500");
and sending "manually" the information an is showing correctly. and i'm getting in debbuger this message:
30-03-2016 15:05:18 DEBUG SimpleBrokerMessageHandler:277 - Processing MESSAGE destination=/read session=dfR45V77 payload=3500
the difference is in session value but i don't know what this session is having null in the process, what am i doing wrong some clarification o help is welcome
First of all I don't see the configureMessageBroker implementation, so it isn't clear how that may work at all...
From other hand if you see such a difference, try to debug the code in the SimpMessagingTemplate.
I only see headerAccessor.setSessionId(sessionId); in the SimpleBrokerMessageHandler when it does
logger.debug("Broadcasting to " + subscriptions.size() + " sessions.");

Using a Session interface in another class

I have a web application I am making using a websocket API to handle the websockets, here is the code for that part
package comm2.hello;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.catalina.session.*;
#ServerEndpoint(value = "/echo")
public class wschat {
private static ArrayList<Session> sessionList = new ArrayList<Session>();
#OnOpen
public void onOpen(Session session) {
try {
sessionList.add(session);
// asynchronous communication
session.getBasicRemote().sendText("hello");
} catch (IOException e) {
}
}
public void send(String text, Session session) throws IOException {
session.getBasicRemote().sendText(text);
}
}
I am trying to have another java class then call into the send method to send messages, using the following code.
package comms;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.Session;
import javax.websocket.Session;
import comm2.hello.*;
public class main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
wschat h = new wschat();
String text = "hello";
//session shouldn't be null but not sure what to make it
Session session = null;
h.send(text,session);
}
}
As you can see, I have the session variable in the main.java class set to null which will thus always produce a null pointer error. This is because I am not sure what to make session equal to, does anyone have any idea what to initialize the session variable to in main.java?

Categories