How to find senders Bitcoin Address in BitcoinJ after receiving a transaction - java

So in my app I have the following functionality for receiving bitcoins
kit.wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
#Override
public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
txtLog.append("-----> coins resceived: " + tx.getHashAsString() + "\n");
txtLog.append("received: " + tx.getValue(wallet) + "\n");
Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
#Override
public void onSuccess(TransactionConfidence result) {
txtLog.append("\nSuccess! Recieved: " + tx.getValue(wallet) + "\n");
//Find address of sender here
}
#Override
public void onFailure(Throwable t) {
throw new RuntimeException(t);
}
});
}
});
This works great, OnSuccess triggers properly once a transaction is confirmed and added to my wallet. txtLog is just a textArea in my java frame which displays some text output for me. What I need to do now is find the address of the sender at this point, can i do this with the Transaction object tx? Any help would be appreciated.

Found the solution! Unfortunately it uses a depreciated method. I just added the following in the appropriate spot.
String address = "";
for (TransactionInput txin : tx.getInputs()){
address = txin.getFromAddress().toString();
}

Related

How to assign roles with a Discord bot made in Java?

I'm trying to get my Meeseeks bot to assign and remove roles on discord for my personal server. I'm not all too familiar with the special methods and commands, and I've had no luck looking for it!
This is my code right now;
package discord.meeseeksBot;
import discord.meeseeksBot.Ref2;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
public class App extends ListenerAdapter
{
public static void main(String[] args) throws Exception
{
JDA jda = new
JDABuilder(AccountType.BOT).setToken(Ref2.token).buildBlocking();
jda.addEventListener(new App());
}
#Override
public void onMessageReceived(MessageReceivedEvent evt)
{
User objUser = evt.getAuthor();
MessageChannel objMsgCh = evt.getChannel();
Message objMsg = evt.getMessage();
//the prefix to which the bot responds to is "Mr.Meeseeks, "
if(objMsg.getContentRaw().equalsIgnoreCase(Ref2.prefix+"I need
help"))
{
objMsgCh.sendMessage("Hi, " + objUser.getAsMention() + ", " + "
I'm Mr.Meeseeks! Look at me! How can I help?").queue();
objMsgCh.sendMessage("You can tell me to **ADD** you to a role,
or **REMOVE** you from a role!").queue();
}
}
}
I'm working to get the bot to where he'll reply to "Mr.Meeseeks, I need help"
with a list of title roles (these roles serve no hierarchical purpose, nor do they appear separately from online members!) you can choose from, and apply to yourself. I'd also like him to be able to remove yourself from a role.
And example for what I had in mind was a role for gender pronouns, (i.e. "she/her" or "he/him") so that when a profile is clicked on in the server, you'd be able to see what they'd be called.
So you could say, "Mr.Meeseeks, add me to "she/her" pronouns!" and he'd do that for you, or "Mr.Meeseeks, remove me from "she/her" pronouns!".
I can't seem to figure it out for Java.
I am not too familiar with JDA, as Discord4J is better, but I can point you in the right direction.
You want to use regex to test for "Mr", "Meeseeks", "add", and "me" all in the same message. Then you can test for the gender pronouns:
#Override
public void onMessageReceived(MessageReceivedEvent evt) {
User objUser = evt.getAuthor();
MessageChannel objMsgCh = evt.getChannel();
Message objMsg = evt.getMessage();
String content = objMsg.getContentRaw();
Guild guild = evt.getGuild();
//the prefix to which the bot responds to is "Mr.Meeseeks, "
if (objMsg.getContentRaw().equalsIgnoreCase(Ref2.prefix + "I need help")) {
objMsgCh.sendMessage("Hi, " + objUser.getAsMention() + ", " + " I'm Mr.Meeseeks! Look at me! How can I help?").queue();
objMsgCh.sendMessage("You can tell me to **ADD** you to a role, or **REMOVE** you from a role!").queue();
// Test for "Mr", "Meeseeks", "add", and "me".
} else if (content.matches("^(?=.*\\badd\\b)(?=.*\\bme\\b)(?=.*\\bto\\b)(?=.*\\bMr\\b)(?=.*\\bMeeseeks\\b).+")) {
// Test for pronouns (Assuming your roles names are "he/him" and "she/her")
Role group = content.matches("((she)|(her))") ? guild.getRolesByName("she/her", true).get(0) :
content.matches("((he)|(him))") ? guild.getRolesByName("he/him", true).get(0) : null;
if (group == null) {
// Let the user know if they used an invalid pronoun.
objMsgCh.sendMessage("Sorry " + objUser.getAsMention() + ", I can't find that role!").queue();
} else {
// Assign the role.
guild.getController().addRolesToMember​(guild.getMember(objUser), group);
objMsgCh.sendMessage("Added " + objUser.getAsMention() + " to " + group.getName() + "!").queue();
}
}
}

Error with sending PushNotifications with OneSignal android

I am working on a Messaging Android App. Users should be notified with a push notification.
At the time I have this code:
public void notifyUser(String user_id, String message) {
try {
OneSignal.postNotification(new JSONObject("{'contents': {'en':['" + message + "']}, " +
"'include_player_ids': ['" + user_id + "'], " +
"'headings': {'en': 'Tag sub Title HI {{user_name}}'}, " +
"'data': {'openURL': 'https://imgur.com'}," +
"'buttons':[{'id': 'id1', 'text': 'Go to GreenActivity'}, {'id':'id2', 'text': 'Go to MainActivity'}]}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.d("LOL", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.d("LOL", "postNotification Failure: " + response.toString());
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
But I get an Error in Log:
D/LOL: postNotification Failure: {"errors":["Notification contents for each language must be a string"]}
I searched threw the Internet but didn't find a solution for my Problem.
I hope you can help me...
Thanks in advance.
I believe the error you're seeing is because you're sending up the message inside an array when it should just be a string.
"{'contents': {'en':['" + message + "']} should be "{'contents': {'en':'" + message + "'} (removed the brackets).

smack presence listener in multi user chat

smack presence listener in multi user chat not getting called. Used Smack Api to login and then added roster.addRosterListener(mRoasterListener); but could not get any success to listen when presence of other user of the chat room changes. I tried following code to get the presence listener to work :
connection.login(loginUser, passwordUser);
MultiUserChatManager manager =
MultiUserChatManager.getInstanceFor(connection);
muc = manager.getMultiUserChat(roomID + "#" +context.getString(R.string.group_chat_id));
Log.d("Join User: ", "Already Created");
muc.join(Utilities.getUserPhoneNo(context));
muc.addMessageListener(mGroupMessageListener);
Roster roster = Roster.getInstanceFor(connection);//luna
roster.addRosterListener(mRoasterListener);//roasterListener
Log.d("Joined User Phone: ", " " + Utilities.getUserPhoneNo(context));
and this class to listen for presence change...
public class RoasterListener implements RosterListener{
public RoasterListener(Context context){
}
#Override
public void entriesAdded(Collection<String> collection) {
}
#Override
public void entriesUpdated(Collection<String> collection) {
}
#Override
public void entriesDeleted(Collection<String> collection) {
}
#Override
public void presenceChanged(Presence presence) {
System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
}
}
I tried many links available by stackoverflow but could not get any success.
Please Help!
For Multi User Chat you don't have to use Roster, because it's normal to meet people you don't have in Roster.
To know who is in a muc, first ask for occupants:
muc.join(user,password);
List<String> occupantsAtJoinTime = muc.getOccupants();
for (String occupant : occupantsAtJoinTime)
{
System.out.println("occupant: "+occupant);
//actions
}
then, to keep Occupants list updated, register a DefaultParticipantStatusListener to your muc and define that Listner:
muc.addParticipantStatusListener(new CustomParticipantStatusListner());
definied as (there are many methods to implement if you need):
public class CustomParticipantStatusListner extends DefaultParticipantStatusListener
{
public void joined(String participant)
{
System.out.println(participant + "just joined MUC");
//actions (add occupantsRightNow)
}
public void left(String participant)
{
System.out.println(participant + " just left MUC");
//actions (remove occupantsRightNow)
}
}
All this with smack 4.1.7
It's about the Manage role modifications in Multi User Chat.
This example shows how to grant voice to a visitor and listen for the notification events:
// User1 creates a room
muc = new MultiUserChat(conn1, "myroom#conference.jabber.org");
muc.create("testbot");
// User1 (which is the room owner) configures the room as a moderated room
Form form = muc.getConfigurationForm();
Form answerForm = form.createAnswerForm();
answerForm.setAnswer("muc#roomconfig_moderatedroom", "1");
muc.sendConfigurationForm(answerForm);
// User2 joins the new room (as a visitor)
MultiUserChat muc2 = new MultiUserChat(conn2, "myroom#conference.jabber.org");
muc2.join("testbot2");
// User2 will listen for his own "voice" notification events
muc2.addUserStatusListener(new DefaultUserStatusListener() {
public void voiceGranted() {
super.voiceGranted();
...
}
public void voiceRevoked() {
super.voiceRevoked();
...
}
});
// User3 joins the new room (as a visitor)
MultiUserChat muc3 = new MultiUserChat(conn3, "myroom#conference.jabber.org");
muc3.join("testbot3");
// User3 will lister for other occupants "voice" notification events
muc3.addParticipantStatusListener(new DefaultParticipantStatusListener() {
public void voiceGranted(String participant) {
super.voiceGranted(participant);
...
}
public void voiceRevoked(String participant) {
super.voiceRevoked(participant);
...
}
});
// The room's owner grants voice to user2
muc.grantVoice("testbot2");
Details can be refered in http://web.mit.edu/svalente/lib/smack_3_0_4/documentation/extensions/muc.html .
Firstly, join a chat room:
public MultiUserChat joinMultiUserChat(String user, String roomsName,
String password) {
if (getConnection() == null)
return null;
try {
MultiUserChat muc = new MultiUserChat(getConnection(), roomsName
+ "#conference." + getConnection().getServiceName());
DiscussionHistory history = new DiscussionHistory();
history.setMaxChars(0);
// history.setSince(new Date());
muc.join(user, password, history,
SmackConfiguration.getPacketReplyTimeout());
Log.i("MultiUserChat", "Chat room【"+roomsName+"】joined........");
return muc;
} catch (XMPPException e) {
e.printStackTrace();
Log.i("MultiUserChat", "Chat room【"+roomsName+"】failed........");
return null;
}
}
Then, use MultiChatUser to send Message:
try {
multiUserChat.sendMessage(message);
} catch (XMPPException e) {
e.printStackTrace();
}
Add a Listener:
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
public class TaxiMultiListener implements PacketListener {
#Override
public void processPacket(Packet packet) {
Message message = (Message) packet;
String body = message.getBody();
}
}
Finally, call the Listener using MultiUserChat:
multiUserChat.addMessageListener(new TaxiMultiListener());

Get command Google now in my app

I would like to get back results in a variable of type String. The contents of what the user tells his smartphone via Google now that is: "OK google claptrap " I would like to do this so I could get back 'claptrap'. I have already searched but have been unsuccessful. I found how to return my selectable application in Google now like, for example write a note in my app but in this case the person has to say " OK google note at me claptrap " so that I can get back claptrap. It is not proceeding well … I am pretty sure that it is possible because the app "commandr" already makes it for commands as "turn on the torch".
Excuse my bad english.
Thank you in advance Good evening :D
i have create a AccessibilityService for get command google now but i should touch editText for receive the command. Help me please
public class NotificationService extends AccessibilityService {
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
System.out.println("******onAccessibilityEvent*******");
if(event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED || event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED) {
System.out.println(" NAME : " + event.getClassName());
System.out.println(" NAME PCK : " + event.getPackageName());
System.out.println(" SOURCE : " + event.getSource());
System.out.println(" TEXT : " + event.getText());
}
}
private String RecupCommandGoogle(AccessibilityEvent mEvent, AccessibilityNodeInfo mSource) {
if (mSource != null & mEvent.getClassName().equals("android.view.View")) {
return String.valueOf(mSource.performAction(AccessibilityNodeInfo.ACTION_SELECT));
}
return null;
}
#Override
protected void onServiceConnected() {
System.out.println("onServiceConnected");
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_WINDOWS_CHANGED | AccessibilityEvent.TYPE_VIEW_FOCUSED ;
info.packageNames = new String[] {"com.google.android.launcher" , "com.google.android.googlequicksearchbox"};
info.feedbackType = AccessibilityEvent.TYPES_ALL_MASK;
info.notificationTimeout = 100;
setServiceInfo(info);
}
#Override
public void onInterrupt() {
System.out.println("onInterrupt");
}
}

MultipleChatUser XMPP asmack join

I am new to this OpenFire and asmack, i want the user to have a functionality of Multi Users Chatting so i searched around and i found MUC i have implemented this for creating a room and sending invitation to other users these works, other user receives the invitation but the other user is not able to join the room.
I am doing this on other user invitation receiving
Here connection is the connection of this user and room is the room name that we getting in invitation.
MultiUserChat muc3 = new MultiUserChat(connection,room);
muc3.join("testbot3");
testbot3 is just some random name.
But this throws 404 error.
Do i need to join the user before sending the invitation i.e if A user sending invitation to B , before invitation sent do A needs to join these users by default to room and then it depends on B to decline or just keep quite.
What i am doing is B receives invitation from A in that InvitationListner of B i am trying to join with the above code.
I have been trying for long now i am not sure what is going wrong, some one can give a sample code of how to do this it would be great help for me.
Thanks
Here is more information on my issue
As i go and check on Openfire i can see the room created by the user and he has been added himself as an owner so i dont think so it would be an issue with room getting created.
May be this can be an issue with room getting locked, as i have read through the room is locked when the room is not completely created , i guess this is an issue with form filling when we create the room, i am not filling in the password in the form can this be an issue ?
Please see the following code below inside the handler i am calling a method "checkInvitation" which does the same as above code posted still i get 404. Can you please tell me what i wrong in my code.
Do the nickname that needs to be added can be anything or it needs to something user specific ?
public void createChatroom(){
MultiUserChat muc = null;
try {
muc = new MultiUserChat(connection, "myroom#conference.localhost");
muc.create("testbot");
// Get the the room's configuration form
Form form = muc.getConfigurationForm();
// Create a new form to submit based on the original form
Form submitForm = form.createAnswerForm();
// Add default answers to the form to submit
for (Iterator fields = form.getFields(); fields.hasNext();) {
FormField field = (FormField) fields.next();
if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) {
// Sets the default value as the answer
submitForm.setDefaultAnswer(field.getVariable());
}
}
// Sets the new owner of the room
List owners = new ArrayList();
owners.add("admin#localhost");
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
// Send the completed form (with default values) to the server to configure the room
muc.sendConfigurationForm(submitForm);
muc.join("d");
muc.invite("b#localhost", "Meet me in this excellent room");
muc.addInvitationRejectionListener(new InvitationRejectionListener() {
public void invitationDeclined(String invitee, String reason) {
// Do whatever you need here...
System.out.println("Initee "+invitee+" reason"+reason);
}
});
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setConnection(XMPPConnection connection) {
this.connection = connection;
if (connection != null) {
// Add a packet listener to get messages sent to us
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message
.getFrom());
Log.i("XMPPClient", "Got text [" + message.getBody()
+ "] from [" + fromName + "]");
messages.add(fromName + ":");
messages.add(message.getBody());
// Add the incoming message to the list view
mHandler.post(new Runnable() {
public void run() {
setListAdapter();
checkInvitation();
}
});
}
}
}, filter);
mHandler.post(new Runnable() {
public void run() {
checkInvitation();
}
});
}
}
The 404 error indicates that:
404 error can occur if the room does not exist or is locked
So, ensure that your room is not locked or existed! The code below is how I join the room when there's an in-comming invitation:
private void setChatRoomInvitationListener() {
MultiUserChat.addInvitationListener(mXmppConnection,
new InvitationListener() {
#Override
public void invitationReceived(Connection connection,
String room, String inviter, String reason,
String unKnown, Message message) {
//MultiUserChat.decline(mXmppConnection, room, inviter,
// "Don't bother me right now");
// MultiUserChat.decline(mXmppConnection, room, inviter,
// "Don't bother me right now");
try {
muc.join("test-nick-name");
Log.e("abc","join room successfully");
muc.sendMessage("I joined this room!! Bravo!!");
} catch (XMPPException e) {
e.printStackTrace();
Log.e("abc","join room failed!");
}
}
});
}
Hope this helps your error!
Edit:this is how I config the room:
/*
* Create room
*/
muc.create(roomName);
// muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
Form form = muc.getConfigurationForm();
Form submitForm = form.createAnswerForm();
for (Iterator fields = form.getFields(); fields.hasNext();) {
FormField field = (FormField) fields.next();
if (!FormField.TYPE_HIDDEN.equals(field.getType())
&& field.getVariable() != null) {
show("field: " + field.getVariable());
// Sets the default value as the answer
submitForm.setDefaultAnswer(field.getVariable());
}
}
List<String> owners = new ArrayList<String>();
owners.add(DataConfig.USERNAME + "#" + DataConfig.SERVICE);
submitForm.setAnswer("muc#roomconfig_roomowners", owners);
submitForm.setAnswer("muc#roomconfig_roomname", roomName);
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
muc.sendConfigurationForm(submitForm);
// submitForm.
show("created room!");
muc.addMessageListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
show(packet.toXML());
Message mess = (Message) packet;
showMessageToUI(mess.getFrom() + ": " + mess.getBody());
}
});
With this cofiguration, I can join a room easily without password.
You may use the code snippet to join the chat:
public void joinMultiUserChatRoom(String userName, String roomName) {
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Create a MultiUserChat using an XMPPConnection for a room
MultiUserChat multiUserChat = manager.getMultiUserChat(roomName + "#conference.localhost");
DiscussionHistory history = new DiscussionHistory();
history.setMaxStanzas(-1);
try {
multiUserChat.join(userName, "", history, connection.getPacketReplyTimeout());
} catch (Exception e) {
e.printStackTrace();
}
}
Invite a friend:
/**
* Invites another user to this room.
*
* #param userAddress the address of the user to invite to the room.(one
* may also invite users not on their contact list).
* #param reason a reason, subject, or welcome message that would tell
* the the user why they are being invited.
*/
public void invite(String userAddress, String reason)
{
multiUserChat.invite(userAddress, reason);
}

Categories