Showing posts with label whatsapp. Show all posts
Showing posts with label whatsapp. Show all posts

Friday, December 15, 2017

How to change the active chat in web whatsapp via selenium or javascript with Python 3

Leave a Comment

I am steering web whatsapp via selenium via Python, i was wondering if it is possible to change the active (top chat. If a message is recieved, the chat won't be set as active, it will always remain in the background.

In Javascript, one can see a list of all chat in the consoles via:

Store.chat.models 

The active chat is stored at position zero, however overwriting the position zero with another chat will not make the chat active.

I have found out that there is a variable called "x_active" which changes if a chat is clicked on and view to true (and all others have it as false).

e.g.:

Store.Chat.models[0].__x_active 

However setting the variable or true or false in the chrome Console tab did not change anything in the UI, so how can I achieve such behaviour?

3 Answers

Answers 1

You'll need to use selenium to click on the contact in the left pane to make it active. You can easily find the place to click using the CSS selector like this:

driver.find_element_by_css_selector('span[title="Contact Name"]').click() 

To easily identify which contacts have unread messages, you can use your JavaScript Store.chat.models list, and find objects in the list with the variable __x_hasUnread = True, and the value of the variable __x_formattedTitle to find the contact name to use for the find above.

Answers 2

in whatsapp web if you inspect you can see that contact name resides in div with class '.chat'.

you can add listener to contacts in left side in whatsapp web by executing the following script in your whatsapp_login function. Following is the whatsapp_login function:

def whatsapp-login(request):     global driver      profile = webdriver.FirefoxProfile()     profile.accept_untrusted_certs = True     driver = webdriver.Firefox(firefox_profile=profile)      driver.get('https://web.whatsapp.com/')      script_path = os.path.dirname(os.path.abspath(__file__))     script = open(os.path.join(script_path, "add_eventlistener.js"), "r").read()      driver.execute_script(script) 

following is the add_listener script which uses MutationObserver:

var observer = new MutationObserver(function(mutations) {             mutations.forEach(function(mutation) {                 if(mutation.attributeName === 'class') {                      var attributeValue = $(mutation.target).prop(mutation.attributeName);                     console.log("attributeValue: "+attributeValue);                     if(attributeValue.indexOf('hover') > -1) {                          var user = $(mutation.target).find('.chat-title').find('span').attr('title');                         console.log('Class attribute changed to:', attributeValue);                          $.ajax({                             url: 'url of change active chat function',                             type: "POST",                             data: {"user": user},                             headers: {"Access-Control-Allow-Origin": "*"},                             success: function(data) {                                 console.log(data);                             },                             error: function(data) {                                 console.log(data);                             }                         });                     }                 }             });         });          Array.prototype.forEach.call(document.querySelectorAll('.chat'), function(element, index) {             console.log(element);             observer.observe(element, {                 attributes: true             });         }); 

inside your change active chat function you can do the following to change active chat. Here you will get the user from ajax call and iterate through the contact list:

def change_active_chat(user):     recentList = driver.find_elements_by_xpath("//span[@class='emojitext ellipsify']")         for head in recentList:             if head.text == user:                 head.click() 

head.click() will change the active chat.

Answers 3

However setting the variable or true or false in the chrome Console tab did not change anything in the UI

You are changing the Boolean value but the request is not submitted as a result you wont see any change. My suggestion is to Click on the webElement using Xpath or CSS or any other convenient locator techniques first.

Read More

Saturday, November 4, 2017

WhatsApp VoIP Push non-delivery and iOS 11

Leave a Comment

There's lots of problems with push in general in iOS 11.0n. I have two apps, one uses silent pushes and I can reproduce problems with the pushes not being delivered. Theres nothing I can do to fix it, its an Apple issue, they have changed the behavior of silent pushes and also introduced a bug with iOS 11.0.

However I also have another app which uses VoIP push. WhatsApp uses VoIP push and their users have been experiencing lots of notification issues with iOS 11.0n too: https://whatsappen.com/news/5465/many-complaints-whatsapp-notifications-ios-11-update-solution

That link above (and WhatsApp web site states something sililar)

It’s indeed an iOS 11 bug. It is affecting users who habitually force close their app.

I'm unable to reproduce any similar issue with my app which uses VoIP push (tried force quitting it several times). And that's my problem - the fact that I can't reproduce it. Just because I can't reproduce it doesn't mean it doesn't affect my app.

If there is a problem with VoIP push and therefore potentially with my app's behavior I would like to reproduce it, and fix it. WhatsApp claim they fixed their issue without waiting for a new release from Apple, so it must be something they can work around.

I would like to know if anybody knows what this VoIP push problem is with WhatsApp and what they did to fix it.

0 Answers

Read More

Friday, July 21, 2017

Xamarin Android: How to Share PDF File From Assets Folder? Via Whatsapp I get message, the file you picked was not a document

Leave a Comment

I use Xamarin Android. I have a PDF File storaged in Assest folder from Xamarin Android.

enter image description here

I want to share this file in whatsapp, but I recive a message: "the file you picked was not a document"

enter image description here

I tried two ways:

This is the first way

var SendButton = FindViewById<Button>(Resource.Id.SendButton); SendButton.Click += (s, e) =>                  {                 ////Create a new file in the exteranl storage and copy the file from assets folder to external storage folder                 Java.IO.File dstFile = new Java.IO.File(Environment.ExternalStorageDirectory.Path + "/my-pdf-File--2017.pdf");                 dstFile.CreateNewFile();                  var inputStream = new FileInputStream(Assets.OpenFd("my-pdf-File--2017.pdf").FileDescriptor);                 var outputStream = new FileOutputStream(dstFile);                 CopyFile(inputStream, outputStream);                  //to let system scan the audio file and detect it                 Intent intent = new Intent(Intent.ActionMediaScannerScanFile);                 intent.SetData(Uri.FromFile(dstFile));                 this.SendBroadcast(intent);                  //share the Uri of the file                 var sharingIntent = new Intent();                 sharingIntent.SetAction(Intent.ActionSend);                 sharingIntent.PutExtra(Intent.ExtraStream, Uri.FromFile(dstFile));                 sharingIntent.SetType("application/pdf");                  this.StartActivity(Intent.CreateChooser(sharingIntent, "@string/QuotationShare"));             }; 

This is the second

//Other way              var SendButton2 = FindViewById<Button>(Resource.Id.SendButton2);             SendButton2.Click += (s, e) =>             {                  Intent intent = new Intent(Intent.ActionSend);                 intent.SetType("application/pdf");                  Uri uri = Uri.Parse(Environment.ExternalStorageDirectory.Path + "/my-pdf-File--2017.pdf");                 intent.PutExtra(Intent.ExtraStream, uri);                  try                 {                     StartActivity(Intent.CreateChooser(intent, "Share PDF file"));                 }                 catch (System.Exception ex)                 {                     Toast.MakeText(this, "Error: Cannot open or share created PDF report. " + ex.Message, ToastLength.Short).Show();                 }             }; 

In other way, when I share via email the pdf file is sent empty, "corrupt file"

What can I do?

2 Answers

Answers 1

The solution is copying de .pdf file from assets folder to a local storage. Then We able to share de file.

First copy the file:

string fileName = "my-pdf-File--2017.pdf";  var localFolder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath; var MyFilePath = System.IO.Path.Combine(localFolder, fileName);  using (var streamReader = new StreamReader(Assets.Open(fileName))) {        using (var memstream = new MemoryStream())        {               streamReader.BaseStream.CopyTo(memstream);               var bytes = memstream.ToArray();               //write to local storage               System.IO.File.WriteAllBytes(MyFilePath, bytes);                MyFilePath = $"file://{localFolder}/{fileName}";       } } 

Then share the file, from local storage:

var fileUri = Android.Net.Uri.Parse(MyFilePath);  var intent = new Intent(); intent.SetFlags(ActivityFlags.ClearTop); intent.SetFlags(ActivityFlags.NewTask); intent.SetAction(Intent.ActionSend); intent.SetType("*/*"); intent.PutExtra(Intent.ExtraStream, fileUri); intent.AddFlags(ActivityFlags.GrantReadUriPermission);  var chooserIntent = Intent.CreateChooser(intent, title); chooserIntent.SetFlags(ActivityFlags.ClearTop); chooserIntent.SetFlags(ActivityFlags.NewTask); Android.App.Application.Context.StartActivity(chooserIntent); 

Answers 2

the file you picked was not a document

I had this issue when I trying to share a .pdf file via WhatsApp from assets folder, but it gives me the same error as your question :

the file you picked was not a document 

Finally I got a solution that copy the .pdf file in assets folder to Download folder, it works fine :

var pathFile = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);  Java.IO.File dstFile = new Java.IO.File(pathFile.AbsolutePath + "/my-pdf-File--2017.pdf"); 

Effect like this.

Read More

Tuesday, March 21, 2017

I want to get whatsApp profilepicture but only getting name and contactnumber?

Leave a Comment

I want to get WhatsApp profile picture and number but using contentResolver I will getting only name and number using following snippet code.

private void showContactWhatsApp(){      ContentResolver cr = getContentResolver();      Cursor contactCursor = cr.query(             ContactsContract.RawContacts.CONTENT_URI,             new String[]{ContactsContract.RawContacts._ID,                     ContactsContract.RawContacts.CONTACT_ID},             ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",             new String[]{"com.whatsapp"},             null);       ArrayList<String> myWhatsappContacts = new ArrayList<>();      if (contactCursor != null) {         if (contactCursor.getCount() > 0) {             if (contactCursor.moveToFirst()) {                 do {                     //whatsappContactId for get Number,Name,Id ect... from  ContactsContract.CommonDataKinds.Phone                     String whatsappContactId = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID));                      if (whatsappContactId != null) {                         //Get Data from ContactsContract.CommonDataKinds.Phone of Specific CONTACT_ID                         Cursor whatsAppContactCursor = cr.query(                                 ContactsContract.CommonDataKinds.Phone.CONTENT_URI,                                 new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,                                         ContactsContract.CommonDataKinds.Phone.NUMBER,                                         ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},                                 ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",                                 new String[]{whatsappContactId}, null);                          if (whatsAppContactCursor != null) {                             whatsAppContactCursor.moveToFirst();                             String id = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));                             String name = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));                             String number = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));                              whatsAppContactCursor.close();                              //Add Number to ArrayList                             myWhatsappContacts.add(number);                              Log.e(TAG, " WhatsApp contact id  :  " + id);                             Log.e(TAG, " WhatsApp contact name :  " + name);                             Log.e(TAG, " WhatsApp contact number :  " + number);                         }                     }                 } while (contactCursor.moveToNext());                 contactCursor.close();             }         }     }      Log.e(TAG, " WhatsApp contact size :  " + myWhatsappContacts.size()); } 

I want to get WhatsApp profile picture like SyncMe app.

I wait to get WhatsApp contact list with name, number, and thumbnail.

1 Answers

Answers 1

Firstly I just want to reiterate the difference between a RawContact and a Contact. The latter being an aggregation (representing a person) of the former (representing an account).

Depending on what use you have for the image, it may be better to fetch the aggregate Contact and use the Profile image selected there which can be achieved via the Photo contract.

Uri photoUri; Cursor photoCur = cr.query(     ContactsContract.Data.CONTENT_URI, null,     ContactsContract.Data.CONTACT_ID + "=" + aggregateContactId + " AND " +      ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'",      null, null ); if (photoCur != null && photoCur.moveToFirst()) {     Uri photoId = ContentUris.withAppendedId(Contacts.CONTENT_URI, aggregateContactId);     photoUri = Uri.withAppendedPath(person, Contacts.Photo.CONTENT_DIRECTORY); } 

If you have use specifically for the WhatsApp photo, first make sure the photo is cached on the device (just to avoid false flags while testing - open the contacts full image in WhatsApp and you can be sure it's cached) then you'll have to do a separate lookup for the image (from API 14):

Uri photoId = ContentUris.withAppendedId(RawContacts.CONTENT_URI, whatsappContactId); Uri photoUri = Uri.withAppendedPath(photoId, RawContacts.DisplayPhoto.CONTENT_DIRECTORY); 
Read More

Tuesday, March 7, 2017

whatsapp button sharing different url than actual

Leave a Comment

I have a working whatsapp <a> tag in this way:

<a class="whatsapp share-local-button    data-action="share/whatsapp/share"    target="_blank" href="whatsapp://send?text=link#withMark" >    <i class="fa fa-whatsapp"></i> </a> 

This works, but what is in href is simply the shared text, not the url, which is the current....

I tried with

data-href="link#withMark"  

But no different results...

How can I share my customized url and not the current one?

2 Answers

Answers 1

Try adding something like a bit of PHP if you are able to. if you want to keep it clean html then just ignore this.

in php u define the link u want to set in a variable, then just add <?php $yourvariable ?> to the whatsapp://send?text= INSERT HERE

Answers 2

Add a JavaScript code as I did to dynamically add the link.

Also it is reusable and can be used in any page.

Here, we set the href of the element having class=whatsapp to it's href+ the site link.

Try running the code

document.getElementsByClassName('whatsapp')[0].href+=window.self.location;
<a class="whatsapp share-local-button     data-action="share/whatsapp/share"     target="_blank" href="whatsapp://send?text=">     <i class="fa fa-whatsapp">whatsapp</i>  </a>

Read More

Monday, September 12, 2016

Send messages with whatsapi.net?

Leave a Comment

I want to send messages using whatsapi and this was my try

string nickname = "Test"; string sender = "xxxxxxxxxxxxxx";          //My Phone Number tryed with 049xxxxxxxxxxxx, 0049xxxxxxxxxxxxxx, 49xxxxxxxxxxxxxxx, xxxxxxxxxxxxxx string imei = "xxxxxxxxxxxxxxxxxxxxxxxxx";//My IMEI  WhatsApp me = new WhatsApp(sender,imei ,nickname,true); me.Connect(); Console.WriteLine(me.ConnectionStatus);// I get a Connection! Console.ReadLine(); me.SendMessage("xxxxxxxxxx", "This is a Test!");// Send Message //No Message received :( me.Disconnect(); Console.WriteLine(me.ConnectionStatus); Console.ReadLine(); 

Now where is my mistake? and how I'm doing it right?

I'm using this version: https://github.com/perezdidac/WhatsAPINet.

First I just want to send messages. When I try to get a request from the WART, I just get this message:

Could not request code using either sms or voice. SMS: {"status":"fail","reason":"no routes","retry_after": 3600} Voice: {"status":"fail","reason":"no routes","retry_after": 3600} 

4 Answers

Answers 1

download installer for generate password https://github.com/mgp25/WART from this link

after that pass your mobile no and password which you got. and pass user detail like his no or msg in constructor in whatsapp object.

it will work for you. try with it.

Answers 2

    WhatsApp wa = new WhatsApp("your number", "your password", "pankaj", false, false);     wa.OnConnectSuccess += () =>     {         Response.Write("connect");         wa.OnLoginSuccess += (phno,data) =>         {             wa.SendMessage("to", "msg");         };          wa.OnLoginFailed += (data) =>         {             Response.Write("login failed"+data);         };         wa.Login();     };     wa.OnConnectFailed+= (ex)=>     {         Response.Write("connection failed");     } 

Answers 3

Use this fork https://github.com/andregsilv/WhatsAPINet
It works and you will also be able to obtain your password with it. Here is the link to the Nuget package for it
https://www.nuget.org/packages/WhatsAppAPI/

Answers 4

After the connect put the command to Login. I resolved this way:

me.connect();  me.login(null); 
Read More

Sunday, April 17, 2016

share videos to whats app without showing ActionSheet

Leave a Comment

I need to share videos from my app to WhatsApp. I currently can do this by using an UIActivityViewController but the user experience is not good.

(The user presses a "send to WhatsApp" button and then has to select WhatsApp in the Action Sheet displayed by the UIActivityViewController).

I know it's possible to open the WhatsApp application and to share videos. For example, the application TuneMoji does it very well :

  • The user presses the "send to WhatsApp"
  • The WhatsApp application opens, asking for a destination user.

I'd like to do exactly the same.

Please, don't tell me to have a look at https://www.whatsapp.com/faq/en/iphone/23559013 , or to use a UIDocumentInteractionController : I want to avoid presenting an ActionSheet to the user.

4 Answers

Answers 1

Try this on the button action:

func sendVideo(videoName: String, senderView: UIView) {         if UIApplication.sharedApplication().canOpenURL(NSURL(string: "whatsapp://app")!) {         let savePath: String = NSBundle.mainBundle().pathForResource(videoName, ofType: "mov")!        let documentInteractionController = UIDocumentInteractionController(URL: NSURL.fileURLWithPath(savePath))         documentInteractionController.UTI = "net.whatsapp.movie"         documentInteractionController.delegate = self         documentInteractionController.presentOpenInMenuFromRect(CGRectMake(0, 0, 0, 0), inView: senderView, animated: true)     }     else {          let alertController = UIAlertController(title: "Error occured", message: "WhatsApp is not installed on your device.", preferredStyle: .Alert)         let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)         alertController.addAction(defaultAction)         presentViewController(alertController, animated: true, completion: nil)     } } 

For more information you can check ref: https://www.whatsapp.com/faq/en/iphone/23559013

Be sure to include WhatsApp URL scheme in your application's Info.plist under LSApplicationQueriesSchemes key if you want to query presence of WhatsApp on user's iPhone using 'canOpenURL'

Answers 2

You can open whatsapp like this.

NSURL *urlOfWhatsApp = [NSURL URLWithString:@"whatsapp://"];  if ([[UIApplication sharedApplication] canOpenURL:urlOfWhatsApp]) { //check app can open whatsapp or not.      [[UIApplication sharedApplication] openURL:urlOfWhatsApp];  } else {     NSLog(@"You device do not have whatsapp."); } 

Answers 3

You can send text messages using WhatsApp URL Scheme like this:

NSURL *whatsappURL = [NSURL URLWithString:@"whatsapp://send?text=Hello%2C%20World!"]; if ([[UIApplication sharedApplication] canOpenURL: whatsappURL]) {     [[UIApplication sharedApplication] openURL: whatsappURL]; } 

This will open the application and ask for destination to send Hello World!.

To send images or videos, you can use the UIActivityViewController like you already noticed, or use UIDocumentInteractionController, that may be closer to what you are looking for:

_documentController = [UIDocumentInteractionController interactionControllerWithURL:_imageFileURL]; _documentController.delegate = self; _documentController.UTI = @"net.whatsapp.image"; [_documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES]; 

To show only whatsapp in the application list, use the private whatsapp file extension or UTI:

Alternatively, if you want to show only WhatsApp in the application list (instead of WhatsApp plus any other public/*-conforming apps) you can specify a file of one of aforementioned types saved with the extension that is exclusive to WhatsApp:

  • images - «.wai» which is of type net.whatsapp.image
  • videos - «.wam» which is of type net.whatsapp.movie
  • audio files - «.waa» which is of type net.whatsapp.audio

When triggered, WhatsApp will immediately present the user with the contact/group picker screen. The media will be automatically sent to a selected contact/group.

More information in this WhatsApp FAQ.

Answers 4

Here you have all you need:

https://www.whatsapp.com/faq/en/iphone/23559013

Edit: and you can see example at this SO to send text / images directly to whats app -

Share image/text through WhatsApp in an iOS app

(see Wagner Sales' answer)

Read More

Wednesday, March 16, 2016

Android Whatsapp Call Start Broadcast Receiver

Leave a Comment

I am working on an application that needs to get some sort of notification/ Receiver when the WhatsApp call is being started (Both on the Caller and Receiver end) or ended. Is it possible to get Incoming/Outgoing WhatsApp call information within my application?

I have tried to use Accessibility Service

Using package name as "com.whatsapp", I'm unable to fulfil my requirement. Will anyone suggest me what should I do? Or Can this actually be done? IF yes, Then please explain how.

1 Answers

Answers 1

Let's solve the query.... Accessibility Service will help you to get notified that when you will receive the notifications against your required package name. for example "com.whatsapp".

Now good thing is that you can parse the notification message within since Android 4.2 within Accessibility Service by a little effort. Unluckily for you, There was a github project that was exactly doing your desired thing but it is currently unavailable.

Read More