Discord API (JDA) Get a user from specific Guild - java

try {
final JDABuilder jdaBuilder = JDABuilder.createDefault(TOKEN_ID);
jdaBuilder.addEventListeners(new DiscordListener());
_jdaBuild = jdaBuilder.build();
} catch(final LoginException e) {
}
I tried use the
_jdaBuild.getUserById(userId);
But it always return null. I also tried do a for to all Guild then to all Text Channels and then to All members but in log it only show the ID of the Bot from all Text Channels. Not the other users.
How can i get user base on his ID or Name from a Guild and send him a private?

You need to use JDA#retrieveUserById​(long) because JDA#getUserById(long) only works if the user is cached:
try {
final JDABuilder jdaBuilder = JDABuilder.createDefault(TOKEN_ID);
jdaBuilder.addEventListeners(new DiscordListener());
_jdaBuild = jdaBuilder.build();
} catch(final LoginException e) {
//...
}
//...
User user = _jdaBuild.retrieveUserById("...").complete();

Related

Programmatically create a user in Cognito with email and password (permanent password)

I currently have some code that creates a new user with temporary password. I get an email with a temporary password to my account, but instead I want to get a verification code. to confirm my email.
here is the code:
public static void registerUser(String email) {
String userPoolId = "eu-central-1_xxx";
AWSCognitoIdentityProvider cognitoClient = setUpCognitoClient();
String password = "123456789";
try {
AdminCreateUserRequest userRequest =
new AdminCreateUserRequest().withUserPoolId(userPoolId).withUsername(email);
cognitoClient.adminCreateUser(userRequest);
AdminSetUserPasswordRequest adminSetUserPasswordRequest =
new AdminSetUserPasswordRequest().withUsername(email)
.withUserPoolId(userPoolId).withPassword(password).withPermanent(true);
cognitoClient.adminSetUserPassword(adminSetUserPasswordRequest);
} catch (AWSCognitoIdentityProviderException e) {
System.out.println(e.getErrorMessage());
} catch (Exception e) {
System.out.println(e);
}
}
Seems like .withPermanent(true) doesn't work.
Also currently I am creating a user with one call and setting the password (AdminSetUserPasswordRequest()) with another. Is there a simpler way of doing it?
I was surprised how long it took me to actually find a solution to something quite trivial as creating a user without a temporary password.
public static void signUpUser(String email, String password) {
AWSCognitoIdentityProvider cognitoClient = setUpCognitoClient();
try {
SignUpRequest signUpRequest = new SignUpRequest().withUsername(email).withPassword(password).withClientId("xxx");
cognitoClient.signUp(signUpRequest);
} catch (AWSCognitoIdentityProviderException e) {
System.out.println(e.getErrorMessage());
} catch (Exception e) {
System.out.println(e);
}
}
So the difference is stead instead of .adminCreateUser I'm using .signUp.
In this case you will need your clientId (which is not your pool id!) - .withClientId("xxx").
Tip: switch to the old view of Cognito console to find the client id faster - if will be under App Clients tab on the left side menu.
After sign up the user will be not confirmed and not verified and will receive an email with the code to verify email (not temporary password).
btw, my verification email landed in spam - so look there if you got no email.

How to use Guild.kick()?

I'm trying to implement a kick command for my bot, but Guild.kick(Member member) doesn't actually kick the specified user. IntelliJ simply says "Result of Guild.kick(Member member) is ignored". Here's my implementation (with non-relevant code removed):
public void onGuildMessageReceived(#Nonnull GuildMessageReceivedEvent e) {
// other code
g = e.getGuild();
// other code
if (args[0].equalsIgnoreCase("kick")) {
// other code
String target = getConnectedName(args, 1, 0); // gets name of target from message
List<Member> nameList = g.getMembersByEffectiveName(target, true);
try {
target = nameList.get(0).getAsMention();
c.sendMessage("Target: "+target).queue();
} catch (IndexOutOfBoundsException e) {
c.sendMessage("No user found with the name \"target\" in this guild.").queue();
}
Member targetM = null;
if (!nameList.isEmpty()) {
targetM = nameList.get(0);
c.sendMessage(targetM.toString()).queue();
try {
g.kick(targetM);
} catch (HierarchyException e) {
error403MissingPermission(); // sends a message that user is missing permission to use !kick
}
}
}
}
Does anyone know why this won't work / what's wrong with my implementation?
SOLVED:
Guild.kick(Member member) has to be queued like TextChannel.sendMessage(String text) , so the correct usage is g.kick(Member member).queue();. Credit to #Minn

send message to single device using Firebase cloud with Java

I'm trying to send messages to single devices using their token from a Java application. I'm using the Firebase Admin SDK. Below is what I have
FileInputStream serviceAccount = null;
try {
serviceAccount = new FileInputStream("google-services.json");
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
FirebaseOptions options = null;
try {
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://MYPROJECTID.firebaseio.com/")
.build();
} catch (IOException e1) {
e1.printStackTrace();
}
FirebaseApp.initializeApp(options);
String registrationToken = "MYDEVICETOKEN";
// See documentation on defining a message payload.
Message message = Message.builder().putData("time", "2:45").setToken(registrationToken)
.build();
// Send a message to the device corresponding to the provided
// registration token.
String response = null;
try {
response = FirebaseMessaging.getInstance().sendAsync(message).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
But I get the following exception
java.io.IOException: Error reading credentials from stream, 'type' field not specified.
What am I doing wrong here?
Click on Generate new private key button.
The error means that your google-services.json file contains invalid data. GoogleCredentials class expects your file to have a type property, but it's not there.
Brief googling gave me this post regarding very similar problem. It says:
From the API Manager, just create select "Create credentials" >
"Service Account key" and generate a new key for the Service
that is associated to your Google Play account.

how to get payer_id programmatically in my java code?

In my code, I am trying to send to Paypal REST API the needed information and Paypal is giving me an "APPROVED" status but in order to finalize the payment, I need to execute the payment.
payment.execute(accesstoken,paymentExecution)... but I couldn't get the payer_id from the response.
Here is my code for further information and thanks for your help in advance!
public class PaypalPaymentWithCreditCardServlet {
// private static final long serialVersionUID = 734220724945040319L;
// #Override
public void init () throws Exception {
InputStream is = PaypalPaymentWithCreditCardServlet.class.getResourceAsStream("/sdk_config.properties");
try {
PayPalResource.initConfig(is);
} catch (PayPalRESTException e) {
// goto failure page. can't do anything without configuration file
e.printStackTrace();
}
}
public boolean doPost (PaymentPojo paymentpojo) throws Exception {
try {
String accessToken = GenerateAccessToken.getAccessToken();
APIContext apiContext = new APIContext(accessToken);
final Payment payment = new PaymentBuilder().setBillingAddress(paymentpojo.getBillingAddress())
.setCreditCard(paymentpojo.getCreditCard())
.setPaymentDetail(paymentpojo.getDetails())
.setTransactionAmount(paymentpojo.getAmount())
.build();
Payment createdPayment = payment.create(apiContext);
System.out.println(Payment.getLastResponse());
System.out.println(String.format("created payment with id [%s] and status=[%s]", createdPayment.getId(), createdPayment.getState()));
if(!createdPayment.getState().toLowerCase().equalsIgnoreCase(PaypalState.APPROVED.getStatus())) {
// payment is not created. throw an exception
System.out.println("Payment handshake did not go through!!!");
return false;
}
// if it is not created throw exception
// payment.execute(accessToken, paymentExecution);
return true;
} catch (PayPalRESTException e) {
}
return false;
}
}
For credit card payments, payer_id is the unique attribute (e.g email address) that you use to identify the user in your system and you would provide that for payment each time in payerID.
If you are not aware of the user's information, such as a guest checkout, you should not need to provide a payerID.
For paypal payments, payer_id always needs to be provided and is appended to redirect_url once the user approves the payment. Full docs are at https://developer.paypal.com/webapps/developer/docs/integration/web/accept-paypal-payment/

getFailedLoginAttempts() function doesn't make any sense in appfoundation in Vaadin

How to get failed login attempts using appfoundation? It has a function getFailedLoginAttempts() but it doesn't make any sense. I am using Vaadin 6 (6.8.12)
My code is here:
NativeButton login = new NativeButton(Lang.getMessage("login"), new ClickListener() {
private static final long serialVersionUID = -5577423546946890721L;
public void buttonClick(ClickEvent event) {
username = (String) usernameField.getValue();
String password = (String) passwordField.getValue();
try {
AuthenticationUtil.authenticate(username, password);
startApp();
} catch (InvalidCredentialsException e) {
/* I need to get failed login attempts here but how can I do that?
I just can by doing this: AuthenticationUtil.authenticate(username, password).
getFailedLoginAttempts(), but I need to write try and catch blocks
(so try and catch blocks in catch block) for authenticate method and this
function will never work, because user won't be authenticated and all
the time you will go to the other catch block; */
feedbackLabel.setValue(Lang.getMessage("usernameOrPasswordIncorect"));
} catch (AccountLockedException e) {
feedbackLabel.setValue(Lang.getMessage("accountBlocked"));
}
}
});
I wrote all the problem in the comment. I want to print a number of failed login attempts but can't get this number. Any suggestions?
Why the code AuthenticationUtil.authenticate(username, password).
getFailedLoginAttempts() compiles is that the authenticate method returns a User object upon successful authentication and this method can then be accessed. However if an exception is throws then you do not have the User object. In their unit tests then use a FactoryFacade to retrieve the user object and check it that way. I do not know the API well so I can not tell you whether you can get the user some other way.
see https://code.google.com/p/vaadin-appfoundation/source/browse/src/org/vaadin/appfoundation/authentication/util/AuthenticationUtil.java
I wrote a function for getting user in my own class.
private User getUserForUsername(String username) {
String query = "SELECT u FROM User u WHERE u.username = :username";
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("username", username);
return (User) FacadeFactory.getFacade().find(query, parameters);
}
And call this method in catch block.
try {
AuthenticationUtil.authenticate(username, password);
startApp();
} catch (InvalidCredentialsException e) {
User user = getUserForUsername(username);
feedbackLabel.setValue(Lang.getMessage("usernameOrPasswordIncorect"));
attemptsLeftLabel.setValue(Lang.getMessage("attemptsLeft", 5 - user.getFailedLoginAttempts()));
} catch (AccountLockedException e) {
feedbackLabel.setValue(Lang.getMessage("accountBlocked"));
}
All works fine.

Categories

Resources