Response to someone which send his first DM to you in JDA - discord-jda

Could I response to someone who send his first DM to me in JDA?

This question will depend on what you need, you can use the
public void onPrivateMessageReceived(#Nonnull PrivateMessageReceivedEvent event) {
//code
}
method to get the private channel for DM's.
After that, you could check the history with the user. This would be example code, so you need to edit it to your needs:
#Override
public void onPrivateMessageReceived(#Nonnull PrivateMessageReceivedEvent event) {
if (event.getUser().isBot()) return; // Don't do anything if the user is bot (aka, self)
if (event.getChannel().getHistory().size() < 2) { //Made it <2 in case array starts with 0
event.getChannel().sendMessage("HI THIS IS THE MESSAGE I WANT TO SEND").queue();
}
}

Related

How can I have one page subscribe to messages from multiple different pages using Xamarin MessagingCenter?

Here's the situation that I have. On DeckPage, I subscribe to a message like this:
public void OnAppearing()
{
RefreshLables();
MessagingCenter.Subscribe<CardFormatPageViewModel>(
this,
"RefreshDeckConfigsLabels",
sender => { RefreshLables(); });
}
private void RefreshLables()
{
-- refresh code
}
public void OnDisappearing()
{
MessagingCenter.Unsubscribe<CardFormatPageViewModel>(this,"RefreshDeckConfigsLabels");
}
This works good and I am sending a message from the CardFormatPageViewModel like this:
MessagingCenter.Send(this, "RefreshDeckConfigsLabels");
I also want to be able to send messages to DeckPage from OptionPageViewModel:
MessagingCenter.Send(this, "RefreshDeckConfigsLabels");
Plus from more models.
Is there a way I can code the subscribe so I can subscribe to one common message that will be accepted if it comes from CardFormatPageViewModel, OptionPageViewModel or the other View Models that need to make it refresh or do I have to do a subscription for every one of them?
sure
MessagingCenter.Send<object>(this, "RefreshDeckConfigsLabels");
and
MessagingCenter.Subscribe<object>(
this,
"RefreshDeckConfigsLabels",
sender => { RefreshLables(); });

How to handle back button when at the starting destination of the navigation component

I've started working with the new navigation component and I'm really digging it! I do have one issue though - How am I supposed to handle the back button when I'm at the starting destination of the graph?
This is the code I'm using now:
findNavController(this, R.id.my_nav_host_fragment)
.navigateUp()
When I'm anywhere on my graph, it's working great, it send me back, but when I'm at the start of it - the app crashes since the backstack is empty.
This all makes sense to me, I'm just not sure how to handle it.
While I can check if the current fragment's ID is the same as the one that I know to be the root of the graph, I'm looking for a more elegant solution like some bool flag of wether or not the current location in the graph is the starting location or not.
Ideas?
I had a similar scenario where I wanted to finish the activity when I was at the start destination and do a regular 'navigateUp' when I was further down the navigation graph. I solved this through a simple extension function:
fun NavController.navigateUpOrFinish(activity: AppCompatActivity): Boolean {
return if (navigateUp()) {
true
} else {
activity.finish()
true
}
}
And then call it like:
override fun onSupportNavigateUp() =
findNavController(R.id.nav_fragment).navigateUpOrFinish(this)
However I was unable to use NavigationUI as this would hide the back arrow whenever I was at the start destination. So instead of:
NavigationUI.setupActionBarWithNavController(this, controller)
I manually controlled the home icon:
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_navigation_back)
Override onBackPressed in your activity and check if the current destination is the start destination or not.
Practically it looks like this:
#Override
public void onBackPressed() {
if (Navigation.findNavController(this,R.id.nav_host_fragment)
.getCurrentDestination().getId() == R.id.your_start_destination) {
// handle back button the way you want here
return;
}
super.onBackPressed();
}
You shouldn't override "onBackPressed", you should override "onSupportNavigateUp" and put there
findNavController(this, R.id.my_nav_host_fragment)
.navigateUp()
From the official documentation:
You will also overwrite AppCompatActivity.onSupportNavigateUp() and call NavController.navigateUp
https://developer.android.com/topic/libraries/architecture/navigation/navigation-implementing
In Jetpack Navigation Component, if you want to perform some operation when fragment is poped then you need to override following functions.
Add OnBackPressedCallback in fragment to run your special operation when back present in system navigation bar at bottom is pressed .
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
onBackPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
//perform your operation and call navigateUp
findNavController().navigateUp()
}
}
requireActivity().onBackPressedDispatcher.addCallback(onBackPressedCallback)
}
Add onOptionsItemMenu in fragment to handle back arrow press present at top left corner within the app.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
//perform your operation and call navigateUp
findNavController().navigateUp()
return true
}
return super.onOptionsItemSelected(item)
}
If there is no special code to be run when back is pressed on host fragment then use onSupportNavigateUp in Activity.
override fun onSupportNavigateUp(): Boolean {
if (navController.navigateUp() == false){
//navigateUp() returns false if there are no more fragments to pop
onBackPressed()
}
return navController.navigateUp()
}
Note that onSupportNavigateUp() is not called if the fragment contains onOptionsItemSelected()
As my back button works correctly, and using NavController.navigateUp() crashed on start destination back button. I have changed this code to something like this. Other possibility will be to just check if currentDestination == startDestination.id but I want to close Activity and go back to other Activity.
override fun onSupportNavigateUp() : Boolean {
//return findNavController(R.id.wizard_nav_host_fragment).navigateUp()
onBackPressed()
return true
}
/** in your activity **/
private boolean doubleBackToExitPressedOnce = false;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onBackPressed() {
int start = Navigation.findNavController(this, R.id.nav_host_fragment).getCurrentDestination().getId();
if (start == R.id.nav_home) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(MainActivity.this, "Press back again to exits", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
} else {
super.onBackPressed();
}
}
If you mean the start of your "root" navigation graph (just incase you have nested navigation graphs) then you shouldn't be showing an up button at all, at least according to the navigation principles.
Just call this in your back button Onclick
requireActivity().finish()

Rendering the Google Recaptcha in Android Studio 3

I am using Android Studio 3
I am following this article to learn how to use Google Recaptcha in Android Studio.
Installed the package using this: implementation 'com.google.android.gms:play-services-safetynet:12.0.1'
API keys are also registered.
I saw there is onClick event handler but where is it mentioned about rendering the recaptcha?
Update 1
When I wrote the button click code as mentioned in the link...I got a complication error: inconvertible types cannot cast anonymous android.view.view.onclicklistener to java.util.concurrent.executor
Code as asked in comment
btn_Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
SafetyNet.getClient(this).verifyWithRecaptcha("")
.addOnSuccessListener((Executor) this,
new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
#Override
public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
// Indicates communication with reCAPTCHA service was
// successful.
String userResponseToken = response.getTokenResult();
if (!userResponseToken.isEmpty()) {
// Validate the user response token using the
// reCAPTCHA siteverify API.
}
}
})
.addOnFailureListener((Executor) this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException) {
// An error occurred when communicating with the
// reCAPTCHA service. Refer to the status code to
// handle the error appropriately.
ApiException apiException = (ApiException) e;
int statusCode = apiException.getStatusCode();
} else {
}
}
});
}
});
I used below code and everything is work fine now.
Make sure to implement Executor in the activity
btn_Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
SafetyNet.getClient(Activity.this).verifyWithRecaptcha("")
.addOnSuccessListener((Activity) MyActivity.this,
new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() {
#Override
public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {
// Indicates communication with reCAPTCHA service was
// successful.
String userResponseToken = response.getTokenResult();
if (!userResponseToken.isEmpty()) {
// Validate the user response token using the
// reCAPTCHA siteverify API.
}
}
})
.addOnFailureListener((Activity) MyActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException) {
// An error occurred when communicating with the
// reCAPTCHA service. Refer to the status code to
// handle the error appropriately.
ApiException apiException = (ApiException) e;
int statusCode = apiException.getStatusCode();
} else {
}
}
});
}
});
According to the article, in your button click handler you must call the method SafetyNet.getClient(this).verifyWithRecaptcha(...) to show reCAPTCHA and handle success or error. Passing this, you give the SDK handle to your current view which should be shown after solving reCAPTCHA. Most probably the rendering will be done by the SDK itself given that it’s a part of the OS. And most probably it will be full-screen in a separate top-level view blocking access to your app before solving the riddle.
You should try to implement it in your app as described in the article and see how it goes. Then you can ask a more specific question.
EDIT: You combined 2 techniques in your code: copy-pasting the code from Google and implementing anonymous class from it. So the problem you asked in the comment is that using (Executor) this in line 5 refers now not to your View (as it was there in the original tutorial) but to the instance of the anonymous interface implementation new View.OnClickListener() that you created. Ypu can refer to this answer to see how it can be implemented not interfering with already complex reCAPTCHA code.

Xamarin "Sorry, this video cannot be played"

How can i handle this error?
please help me out of this situation.
private void previewVideo(){
try{
var path = Android.Net.Uri.Parse(App._file.AbsolutePath);
preview.SetVideoURI (path);
preview.Start ();
}
catch(Exception e){
e.GetBaseException ();
}
}
Your'e lucky that I was following your previous question. Please try to have your questions as detailed as possible so it's easier for us to analyze and possible replicate the error.
To be able to set an error listener on the VideoView, the VideoView needs an object that implements the Android.Media.MediaPlayer.IOnErrorListener interface.
You can accomblish that by letting your Activity implement the previous mentioned interface, and setting the Activity as the ErrorListener for the VideoView
public class MainActivity : Activity, Android.Media.MediaPlayer.IOnErrorListener
{
...
protected override void OnCreate(Bundle bundle)
{
...
preview = FindViewById<VideoView> (Resource.Id.SampleVideoView);
preview.SetOnErrorListener(this); // <- Set the error listener
...
}
...
//The implementation of MediaPlayer.IOnErrorListener
public bool OnError(MediaPlayer player, MediaError error, int extra)
{
// Do Something here because error happened
}
...
}
By doing this, when error occurs in the VideoView the VideoView will call the public OnError method.
From the Android Docs of OnErrorListener you can see what the OnError method should return.
Returns:
True if the method handled the error, false if it didn't. Returning false, or not having an OnErrorListener at all, will cause the OnCompletionListener to be called.

How can I close the websocket from server?

I am using Play framework 2.1.
I am work with web-socket and I need to find way to close them from server.
is there way do do it ?
Example from docs Handling WebSockets:
Let’s write another example that totally discards the input data and closes the socket just after sending the Hello! message:
public static WebSocket<String> index() {
return new WebSocket<String>() {
public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out) {
out.write("Hello!");
out.close()
}
}
}
ScalaWebSockets:
def index = WebSocket.using[String] { request =>
// Just consume and ignore the input
val in = Iteratee.consume[String]()
// Send a single 'Hello!' message and close
val out = Enumerator("Hello!") >>> Enumerator.eof
(in, out)
}

Resources