Discord java bot verify user by name - java

in my current Discord (java) bot im trying to apply a command to a user name. how can i make sure this is an actual existing user ?
in psuedo code:
if User "A" exists {
User "A" types something at all
send message "hello"+ user "A"
}
else
{
this is no valid user;
}
i can't figure out how to write the 'check if exist code'.

This is from JDA-Utilities which is a really useful tool when building discord bots.
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
public class Example extends Command {
public Example() {
this.name = "'isBot";
this.help = "Tells you if the user is a bot!";
}
#Override
protected void execute(CommandEvent e) {
if (e.getAuthor().isBot()) {
e.reply("Hey you're not a person!!");
} else {
e.reply("Hey " + e.getAuthor().getName() + ", you're not a bot!");
}
}
}

Related

How to edit an Embed in JDA

So I was wondering if I send an Embed for something with my Bot, can I edit it with the Bot afterwards?
If that's possible, then show me how to do it please.
This is my Code that I`ve got so far, but idk how to edit that EmbedBuilder afterwards:
public class Giveaway extends ListenerAdapter {
#Override
public void onMessageReceived(MessageReceivedEvent event) {
if (event.getMessage().getContentDisplay().startsWith("+giveaway")) {
if (event.getMessage().getContentDisplay().substring(10, 11) != null) {
long msgid = event.getMessageIdLong();
String count = event.getMessage().getContentDisplay().substring(10, 11);
EmbedBuilder eb = new EmbedBuilder();
eb.setTitle("It's GIVEAWAY-TIME!");
eb.setDescription("Prize: " + "\n Winners: " + count);
eb.setColor(Color.BLUE);
event.getTextChannel().sendMessage(eb.build()).queue();
}
}
}
}
So to be clear, what I want to do is add a footer to the message afterwards and change the description in some cases.
I have tried some things but I've not come up with a solution yet.
Would be nice if you answer.
Kind regards,
lxxrxtz
You can keep the embed builder and create a new embed:
eb.setFooter(...);
MessageEmbed embed = eb.build();
Then all you have to do is call message.editMessage(embed).queue() with the message you want to edit. You can access the message from the callback in your sendMessage:
channel.sendMessage(embed).queue(message -> {
eb.setFooter(...);
message.editMessage(eb.build()).queue();
});

How can I create a new user in Parse, without changing the current user?

I am currently making a friend request module. The user clicks "Approve" the program adds the friend to the _User class on Parse Server. I believed the code below would do it, and it does, but the problem is that is changes the current user to the new friend that has been added. So if the current user is "Bob", and Bob adds "Mike" the new current user is Mike.
I've been experimenting with signUp(), signUpInBackground(), but neither seem to work.
ParseUser newFriend = new ParseUser();
newFriend.setUsername(friendRequestFrom); //friendRequestFrom is a String that carries a name
newFriend.setPassword("12345");
newFriend.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if(e == null){
Log.i("Parse Result","Succesful!");
Log.i("Current User",ParseUser.getCurrentUser().getUsername());
}
else{
Log.i("Parse Result","Failed " + e.toString());
}
}
});
In order to create a new Parse user in Parse using client side code, you have to use a cloud code function hosted in your app backend.
In fact, for security reasons, client librararies are not permitted to directly add users.
In your server side, create a file (main.js) containing the following code:
Parse.Cloud.define("createNewUser", function(request, response) {
var User = Parse.Object.extend("User");
var us = new User();
us.set("username", request.params.username);
us.set("name", request.params.name);
us.set("email", request.params.email);
us.set("password", request.params.password);
us.save(null, {
useMasterKey: true,
success: function(obj) {
response.success("user added");
},
error:function(err){
response.error(err);
}
});
});
Then, you can test this function in your javascript client code as following:
var params = { username: "userEmailAddress#yahoo.fr",
email: "userEmailAddress#yahoo.fr",
name:"Here write the user name",
password:"TheUserPasswordHere"};
Parse.Cloud.run("createNewUser", params).then(function(response){console.log("response: "+response);}).catch(function (err) {
console.log("error: "+err);
});

Running cucumber with bdd in eclipse

I am having problem running this cucumber projects belows. It showing errors on line 7, 8, 20 and 32.
package stepDefinition;
import cucumber.api.java.en.Given;
public class aptitudeTest {
#Given ("I have successfully ([^\"]*)")
public void I have (String str)
{
if (str.equals("registered"))
{
System.out.println("registered Automation");
}
{
System.out.println("unregistered Automation");
}
}
#When ("I enter my valid ([^\"]*)")
public void I enter (String str)
{
if (str.equals("credentials"))
{
System.out.println("credentials Automation");
}
{
System.out.println("details Automation");
}
}
#Then ("I should see the welcome ([^\"]*) him")
public void I should (String str)
{
if (str.equals("welcome"))
{
System.out.println("welcome to your account");
}
{
System.out.println("please enter the correct credential");
}
}
}
Below is the Feature File
Scenario:I should see a message when i successfully logged in
Given I have successfully registered
When I enter my valid credentials
Then I should see the welcome message
There are many 2 issues with the feature file and how the Given, When & Then are used.
The method name should not have any spaces.
If you're passing the argument in to the method, it should be in quotes.
ex. I have successfully registered should be as 'I have successfully "registered"'. Also the corresponding method should be annotated as "I have successfully \"([^\"]*)\" - You should have an escape character there. The registered will be the string that's passed.

Java program won't write to firebase [duplicate]

I'm trying to write a simple test of the Firebase user creation and authentication routines so that I can test my Firebase security settings. The code runs smoothly but the callbacks are not invoked and no users are created on the Firebase side.
The output of below with the print statements is:
Begin process
Start Create User
Creating User
End Creating User
End process
Process finished with exit code 0
The code is using the firebase-client-android-2.2.3.jar file for the Firebase classes though I'm just running my test as a java application on a Mac OS. Later this will go into an Android app but I'd like to be able to run it inside my IDE for now. Any insights from experienced Firebase coders much appreciated.
import com.firebase.client.Firebase;
import com.firebase.client.AuthData;
import com.firebase.client.FirebaseError;
import java.util.*;
public class FireRulesTest {
static String firebase_baseUrl = "https://<myfirebase>.firebaseio.com/";
public static void main(String[] args)
throws FirebaseException {
System.out.println("Begin process");
FireRulesTest tester = new FireRulesTest();
tester.createUser();
System.out.println("End process");
}
private void createUser()
throws FirebaseException {
try {
System.out.println("Start Create User");
final String mEmail = "me#email.com";
final String mPassword = "password";
final Firebase ref = new Firebase(firebase_baseUrl);
System.out.println("Creating User");
ref.createUser(mEmail, mPassword,
new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
ref.authWithPassword(mEmail, mPassword, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
//success, save auth data
HashMap<String, Object> authMap = new HashMap<String, Object>();
authMap.put("uid", authData.getUid());
authMap.put("token", authData.getToken());
authMap.put("email", mEmail);
authMap.put("password", mPassword);
Firebase currentUserRef = new Firebase(firebase_baseUrl + "movo/users/" + authData.getUid());
authMap.put("currentUser", currentUserRef);
System.out.println("User ID: " + authData.getUid() +
", Provider: " + authData.getProvider() +
", Expires:" + authData.getExpires());
System.out.println("Authentication complete");
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
System.out.println("Authentication Error authenticating newly created user. This could be an issue. ");
System.out.println(firebaseError.getMessage());
}
});
}
#Override
public void onError(FirebaseError firebaseError) {
System.out.println("On Error authenticating newly created user. This could be an issue. ");
System.out.println(firebaseError.getMessage());
}
});
System.out.println("End Creating User");
} catch (Exception fbe) {
System.out.println("Exception: " + fbe.getMessage());
fbe.printStackTrace();
}
}
}
You'll want to add a Thread.sleep at the end of the program. Likely your program exits before Firebase gets a chance to send anything to the server.
A more proper solution would be to introduce actual lifecycle management into your app, e.g. waiting for the createUser call to finish. But given that you'll be migrating this to Android (which handles app lifecycle completely different anyway) that might not be worth the effort.

How to display the login information in different layout?

I have created an application which needs sign in from Facebook/Twitter/Google to get started. In a layout I have created three switches each for Facebook, Twitter and Google which has options ON and OFF. I want to make the switch of the particular account as 'ON' if the user is logged in from that corresponding account. Example if the user is logged in from Facebook, only the switch beside Facebook should be ON. How can I do that?
Any suggestions would be appreciated, and also if somebody know then please refer me to any tutorial related to this.
Below is my code for the login page. I have shown the login for Facebook part:
Thanx :)
private OnClickListener loginButtonListener = new OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick( View v ) {
String[] permissions = { "offline_access", "publish_stream", "user_photos", "publish_checkins","photo_upload" };
if(v.getId() == R.id.button1 )
{
facebookSwitch = true;
twitterSwitch = false;
googleSwitch = false;
if( !mFacebook.isSessionValid() ) {
Toast.makeText(Login.this, "Authorizing", Toast.LENGTH_SHORT).show();
mFacebook.authorize(Login.this, permissions, new LoginDialogListener());
}
else {
Toast.makeText( Login.this, "Has valid session", Toast.LENGTH_SHORT).show();
try {
JSONObject json = Util.parseJson(mFacebook.request("me"));
//Log.d("Login", "11111111111111111");
String facebookID = json.getString("id");
//Log.d("Login", "22222222222222");
String firstName = json.getString("first_name");
//Log.d("Login", "3333333333333333333");
String lastName = json.getString("last_name");
//Log.d("Login", "4444444444444444444444");
Toast.makeText(Login.this, "You already have a valid session, " + firstName + " " + lastName + ". No need to re-authorize.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Login.this,MainActivity.class);
startActivity(intent);
}
catch( Exception error ) {
Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show();
}
catch( FacebookError error ) {
Toast.makeText( Login.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}
}
Try it this way....
- First create a Singleton Class with 3 booleanvariables for 3 logins info, and thereGetter-Setter`. Singleton is needed over here so that only One object of that class is formed no matter from where that class is called in the whole application. So now you have a single point of info.
- Always check Singleton Class's variables in the beginning of another Activity or when needed by you, to know that whether the user is logged into one or two or all the social networking sites.
////////////////////////////////Edited Part/////////////////////////////
A simple way of creating a Singleton is below, thought there are few more:
public class Test{
public static Test uniqueInstance = new Test();
private Test(){}
public static Test getInstance(){
return uniqueInstance;
// No matter what but always u will get the same instance.
}
}
Now To call this object in another class do as below...
public class Main{
Test t = Test.getInstance(); // Now use t to call the fields and methods of class T.
}

Categories

Resources