Send text to specific contact programmatically (whatsapp)
Asked Answered
P

28

81

I wanted to know how I can send text to a specific whatsapp contact. I found some code to view a specific contact, but not to send data.

Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
    new String[] { ContactsContract.Contacts.Data._ID }, ContactsContract.Data.DATA1 + "=?",
    new String[] { id }, null);
c.moveToFirst();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));

startActivity(i);
c.close();

This works fine for viewing a whatsapp-contact, but how can I add some text now? Or didn't the Whatsapp-developer implement such kind of an api?

Parvati answered 29/9, 2013 at 18:24 Comment(7)
Duplciate of #15463374Plot
No, in your link they use a chooser, which I don't want to use. I want to send text directly to a contactParvati
He wants to open the chat history, while I want to send text. This is very different.Parvati
@manu ..hey manu i have used your code for send message from my application to whatsup without open whatsup but i have error of getSherlockActivity() .I am new in android so i dont understand what is getsherlockactivity()Secret
@Manu are you solved this problem ?Lawerencelawes
It looks like messages can't be send programatically via WhatsApp, so I gave up...Parvati
@Manu You need have a look at new answer .Ekg
P
3

This is now possible through the WhatsApp Business API. Only businesses may apply to use it. This is the only way to directly send messages to phone numbers, without any human interaction.

Sending normal messages is free. It looks like you need to host a MySQL database and the WhatsApp Business Client on your server.

Parvati answered 28/8, 2018 at 6:59 Comment(1)
Where did you get the information saying that sending normal messages is free? I thought it was notYelmene
D
96

I've found the right way to do this:

Source code: phone and message are both String.

    PackageManager packageManager = context.getPackageManager();
    Intent i = new Intent(Intent.ACTION_VIEW);

    try {
        String url = "https://api.whatsapp.com/send?phone="+ phone +"&text=" + URLEncoder.encode(message, "UTF-8");
        i.setPackage("com.whatsapp");
        i.setData(Uri.parse(url));
        if (i.resolveActivity(packageManager) != null) {
            context.startActivity(i);
        }
    } catch (Exception e){
        e.printStackTrace();
    }

Enjoy yourself!

Dogleg answered 22/8, 2017 at 15:34 Comment(16)
how to use this link to send photo?Kerr
This one is the one, most upvoted did not work if the contact was not previously added to the phone.Scrutable
Here I have to tap the send button , is there any way to automate that as well??Ree
Not sending the text, just opens the chat with the message but its not sending the text.Hooge
@Hooge we can´t send text by pressing a button of another app so that´s not allowed by whatsapp app, it would be necessary to create specific intents from whatsapp staff to make it happen, then, for now users are the only ones that can perform these clicks.Dogleg
@Dogleg Then how google assistance is doing it? I think we can too do this but we are missing somethingHooge
@Dogleg and even the strange thing is google assistance is not even launching the whatsapp.Hooge
@Hooge for now Whatsapp staff has no released that specific intent to the public, maybe in the future, or maybe is just available for big apps as Google. Is hard to say. Btw, if you find something more, please let us know.Dogleg
u saved me, u god!!Smitherman
As @PabloQuemé says, if you don't have the contact previously added, there is a call out that says that you don't have this contact. So I was sending just de phone number, but as soon as I added the complete number with the Country Code this worked nice!Football
I have to add " Context context=view.getContext();" But worked for me.. +1Sundried
perfect answer.Hyaloid
Perfect Solution. Opened chat screen for given contact.Biyearly
Perfect Solution. Opened chat screen for given contact.Biyearly
Does this work, if the phone number not added to contact too? how to specify pdf attachment? can we any way use https:/wa.me/"number" from android app?Tandie
add country code before number e.g. +91, +1, +44 etc will open that person's chat screen.Amiamiable
A
75

I think the answer is a mix of your question and this answer here: https://mcmap.net/q/165564/-sending-message-through-whatsapp So I would try the following code:

  1. change ACTION_VIEW to ACTION_SENDTO
  2. set the Uri as you did
  3. set the package to whatsapp
Intent i = new Intent(Intent.ACTION_SENDTO, Uri.parse("content://com.android.contacts/data/" + c.getString(0)));
i.setType("text/plain");
i.setPackage("com.whatsapp");           // so that only Whatsapp reacts and not the chooser
i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
i.putExtra(Intent.EXTRA_TEXT, "I'm the body.");
startActivity(i);

I looked into the Whatsapp manifest and saw that ACTION_SEND is registered to the activity ContactPicker, so that will not help you. However ACTION_SENDTO is registered to the activity com.whatsapp.Conversation which sounds more adequate for your problem.

Whatsapp can work as a replacement for sending SMS, so it should work like SMS. When you do not specify the desired application (via setPackage) Android displays the application picker. Thererfor you should just look at the code for sending SMS via intent and then provide the additional package information.

Uri uri = Uri.parse("smsto:" + smsNumber);
Intent i = new Intent(Intent.ACTION_SENDTO, uri);
i.putExtra("sms_body", smsText);  
i.setPackage("com.whatsapp");  
startActivity(i);

First try just to replace the intent ACTION_SEND to ACTION_SENDTO . If this does not work than provide the additional extra sms_body. If this does not work than try to change the uri.

Update I tried to solve this myself and was not able to find a solution. Whatsapp is opening the chat history, but doesn't take the text and send it. It seems that this functionality is just not implemented.

Apollinaire answered 4/10, 2013 at 10:36 Comment(19)
Only opens the contact, but no text passed to Whatsapp... Seems like Whatsapp doesn't recognise those extras (or doesn't want).Parvati
Thank you, but now it shows the chooser... seems like WhatsApp blocked this way of sending text...Parvati
Did you try all three variants? I will try to code it tomorrow.Apollinaire
Seems like Whatsapp blocked this way... Thank you for your helpParvati
Ok, I tried just this moment and was not able to solve it. Whatsapp is opening tha chat history, but doesn't take the text and send it. Sorry that I was not able to solve this and thanks for accepting my answer!Apollinaire
@Apollinaire manu's question code i have used but i have a error of getsherlockactivity . I do not understand what is this.And how to get whatsup id programatically.It is possible send message to whats without open whatsup from another applicationSecret
you can remove getsherlockactivity() , it is used when you add sherlock action barLawerencelawes
What if you want a chooser? If I add i.setPackage("com.whatsapp") it starts Whatsapp but when i don't add it it starts the sms app (hangouts in my case).Heliport
Than it seams you have registered the sms app as a default. If you remove this you will get the chooser again.Apollinaire
No apps can perform this action.Poppas
It tells me the phone number doesn't have WhatsApp, even though it has. Is there a way I should format it first?Lotetgaronne
For me 2nd one Worked. Sendto Intent was crashing. Saying this No Activity found to handle Intent { act=android.intent.action.SENDTO typ=text/plain pkg=com.whatsapp (has extras) }Cacomistle
@androiddeveloper i am getting the same error for Marshmallow, were you able to fix this issue? if yes, can you please help me out??Coating
@BasanthVerma As I wrote, the second solution worked for me : new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + whatsAppPhoneNumber)).setPackage("com.whatsapp")Lotetgaronne
How to send a zip file via intent to whatsapp to specific contactApothegm
Did anyone find solution for passing text using putExtra(), This only opens Chat screen, but not passing Message to display in message box. I tried with Intent.EXTRA_TEXT,Intent.EXTRA_HTML_TEXT,Intent.EXTRA_TITLE,Intent.EXTRA_SUBJECT Uri.parse("smsto: " + number + "?body=" + text), but none of them works.Alfie
Answer from BahaR works: https://mcmap.net/q/167950/-send-text-to-specific-contact-programmatically-whatsapp. Keep in mind the phone MUST be in the contact list, otherway it won't work!Erena
You made my day, Thank youSweptback
Please read my answer to this question, it works without having it in your contact list. Works perfectly.Dogleg
A
69

I have done it!

private void openWhatsApp() {
    String smsNumber = "7****"; // E164 format without '+' sign
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");
    sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
    sendIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
    sendIntent.setPackage("com.whatsapp");
    if (intent.resolveActivity(getActivity().getPackageManager()) == null) {
        Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
        return;    
    }
    startActivity(sendIntent);
}
Alisa answered 12/2, 2017 at 9:53 Comment(7)
I was sceptical of your solution because it did not have many upvotes. but it works!Cordless
It open particular contact number with particular chat text but not send it, user have to press send button for send message. +1 Up-vote for open particular activity.Bullington
works, but the phone number should be added to the device Contact ListCicala
This one actually works! Would have been also nice to find a way to use the app chooser and still include both message text and phone number so that the user can choose both SMS and Whatsapp options... Anyone?Obrien
This is working. Great. Thanks for the answer. The PROBLEM is, if the contact is not saved, it is not working. Can you do something to this?Unborn
Code working fine if the contact number is not saved in my contact listLobel
This is working for Android 10(My Phone), but few other phone in the wild gets stuck at contact selection screen. So for now, rolled back to WhatsApp Link of type wa.me/message***, I am using this URL and launching it via Intent: ` Intent(Intent.ACTION_VIEW, Uri.parse(Constants.WHATSAPP_URL)).run { startActivity(this) } `Anesthetist
R
23

This approach works with WhatsApp Business app as well!

Change package name as sendIntent.setPackage("com.whatsapp.w4b"); for WhatsApp Business.

Great hack Rishabh, thanks a lot, I was looking for this solution since last 3 years.

As per the Rishabh Maurya's answer above, I have implemented this code which is working fine for both text and image sharing on WhatsApp.

Note that in both the cases it opens a whatsapp conversation (if toNumber exists in users whatsapp contact list), but user have to click send button to complete the action. That means it helps in skipping contact selection step.

For text messages

String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
startActivity(sendIntent);

For sharing images

String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("image/png");
context.startActivity(sendIntent);

Enjoy WhatsApping!

Ramp answered 16/5, 2017 at 6:39 Comment(7)
not working for me. It is opening contact selection screen.Jello
@DeepakPandit check our app play.google.com/store/apps/details?id=com.wiwonders.billbook which is having share image working in it.Ramp
opening specific contact with the blank message.Tonsillectomy
For more then one number what will i do?Choosey
This only opens whatsapp but it does not repond automaticallyRocketry
those who are getting contact selection screen need to add 91 (country code) before number.Ha
any way to fil the message?Homebrew
E
16

Check out my answer : https://mcmap.net/q/169152/-how-can-i-send-message-to-specific-contact-through-whatsapp-from-my-android-app

 Intent sendIntent = new Intent("android.intent.action.MAIN");
 sendIntent.setComponent(new  ComponentName("com.whatsapp","com.whatsapp.Conversation"));
 sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators("YOUR_PHONE_NUMBER")+"@s.whatsapp.net");//phone number without "+" prefix

 startActivity(sendIntent);

Update:

The aforementioned hack cannot be used to add any particular message, so here is the new approach. Pass the user mobile in international format here without any brackets, dashes or plus sign. Example: If the user is of India and his mobile number is 94xxxxxxxx , then international format will be 9194xxxxxxxx. Don't miss appending country code as a prefix in mobile number.

  private fun sendMsg(mobile: String, msg: String){
    try {
        val packageManager = requireContext().packageManager
        val i = Intent(Intent.ACTION_VIEW)
        val url =
            "https://wa.me/$mobile" + "?text=" + URLEncoder.encode(msg, "utf-8")
        i.setPackage("com.whatsapp")
        i.data = Uri.parse(url)
        if (i.resolveActivity(packageManager) != null) {
            requireContext().startActivity(i)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

Note: This approach works only with contacts added in user's Whatsapp account.

Ekg answered 27/10, 2016 at 13:9 Comment(2)
You should use "com.whatsapp.ContactPicker" in place of "com.whatsapp.Conversation".Knotting
@RishabhMaurya How to also include a bitmap with this?Jeffrey
R
12

Whatsapp have its own API

    Intent sendIntent = new Intent("android.intent.action.MAIN");
                        sendIntent.setAction(Intent.ACTION_VIEW);
                        sendIntent.setPackage("com.whatsapp");
                        String url = "https://api.whatsapp.com/send?phone=" + "Phone with international format" + "&text=" + "your message";
                        sendIntent.setData(Uri.parse(url));
                        if(sendIntent.resolveActivity(context.getPackageManager()) != null){
                             startActivity(sendIntent);
                        }

Code updated check added for Activity is available or not.

See this documentation

Rickrickard answered 27/11, 2017 at 9:11 Comment(2)
Working for me on whatsapp version 2.18.380Soybean
working fine for meTriquetrous
G
6

This will first search for the specified contact and then open a chat window. And if WhatsApp is not installed then try-catch block handle this.

    String digits = "\\d+";
    String mob_num = "987654321";     
    if (mob_num.matches(digits)) 
            {
        try {
              //linking for whatsapp
              Uri uri = Uri.parse("whatsapp://send?phone=+91" + mob_num);
              Intent i = new Intent(Intent.ACTION_VIEW, uri);
              startActivity(i);
            }
            catch (ActivityNotFoundException e){
                    e.printStackTrace();
                    //if you're in anonymous class pass context like "YourActivity.this"
                    Toast.makeText(this, "WhatsApp not installed.", Toast.LENGTH_SHORT).show();
            }
        }
Grampus answered 24/1, 2018 at 9:44 Comment(0)
R
6

Here am trying to send a text message in WhatsApp with another application.

Assume that we have a button, on button click ur calling below method.

sendTextMsgOnWhatsApp("+91 9876543210", "Hello, this my test message");

public void sendTextMsgOnWhatsApp(String sContactNo, String sMessage) {
        String toNumber = sContactNo; // contains spaces, i.e., example +91 98765 43210
        toNumber = toNumber.replace("+", "").replace(" ", "");

        /*this method contactIdByPhoneNumber() will get unique id for given contact,
        if this return's null then it means that you don't have any contact save with this mobile no.*/
        String sContactId = contactIdByPhoneNumber(toNumber);

        if (sContactId != null && sContactId.length() > 0) {

            /*
             * Once We get the contact id, we check whether contact has a registered with WhatsApp or not.
             * this hasWhatsApp(hasWhatsApp) method will return null,
             * if contact doesn't associate with whatsApp services.
             * */
            String sWhatsAppNo = hasWhatsApp(sContactId);

            if (sWhatsAppNo != null && sWhatsAppNo.length() > 0) {
                Intent sendIntent = new Intent("android.intent.action.MAIN");
                sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
                sendIntent.putExtra(Intent.EXTRA_TEXT, sMessage);
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.setPackage("com.whatsapp");
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
            } else {
                // this contact does not exist in any WhatsApp application
                Toast.makeText(this, "Contact not found in WhatsApp !!", Toast.LENGTH_SHORT).show();
            }
        } else {
            // this contact does not exist in your contact
            Toast.makeText(this, "create contact for " + toNumber, Toast.LENGTH_SHORT).show();
        }
    }

    private String contactIdByPhoneNumber(String phoneNumber) {
        String contactId = null;
        if (phoneNumber != null && phoneNumber.length() > 0) {
            ContentResolver contentResolver = getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            String[] projection = new String[]{ContactsContract.PhoneLookup._ID};

            Cursor cursor = contentResolver.query(uri, projection, null, null, null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
                }
                cursor.close();
            }
        }
        return contactId;
    }

    public String hasWhatsApp(String contactID) {
        String rowContactId = null;
        boolean hasWhatsApp;

        String[] projection = new String[]{ContactsContract.RawContacts._ID};
        String selection = ContactsContract.RawContacts.CONTACT_ID + " = ? AND " + ContactsContract.RawContacts.ACCOUNT_TYPE + " = ?";
        String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
        Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
        if (cursor != null) {
            hasWhatsApp = cursor.moveToNext();
            if (hasWhatsApp) {
                rowContactId = cursor.getString(0);
            }
            cursor.close();
        }
        return rowContactId;
    }

Add this below permission in AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
Reichstag answered 14/10, 2019 at 12:26 Comment(2)
This work, no need for contact id, or check whatsapp for me, i could send directly to number.Holmberg
great this helped you, actually this the best way to proceed, you can ignore, which ever part of logic is not required in your case.Reichstag
C
4

This is the shortest way

    String mPhoneNumber = "+972505555555";
    mPhoneNumber = mPhoneNumber.replaceAll("+", "").replaceAll(" ", "").replaceAll("-","");
    String mMessage = "Hello world";
    String mSendToWhatsApp = "https://wa.me/" + mPhoneNumber + "?text="+mMessage;
    startActivity(new Intent(Intent.ACTION_VIEW,
            Uri.parse(
                    mSendToWhatsApp
            )));

See also the documentation of WhatsApp

Coif answered 27/8, 2018 at 17:50 Comment(0)
E
4
try {
                    String text = "Hello, Admin sir";// Replace with your message.

                    String toNumber = "xxxxxxxxxxxx"; // Replace with mobile phone number without +Sign or leading zeros, but with country code
                    //Suppose your country is India and your phone number is “xxxxxxxxxx”, then you need to send “91xxxxxxxxxx”.


                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + toNumber + "&text=" + text));
                    context.startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));

                }
Entry answered 22/5, 2019 at 15:26 Comment(0)
P
3

This is now possible through the WhatsApp Business API. Only businesses may apply to use it. This is the only way to directly send messages to phone numbers, without any human interaction.

Sending normal messages is free. It looks like you need to host a MySQL database and the WhatsApp Business Client on your server.

Parvati answered 28/8, 2018 at 6:59 Comment(1)
Where did you get the information saying that sending normal messages is free? I thought it was notYelmene
T
3

you can also select WhatsApp business vs WhatsApp

String url = "https://api.whatsapp.com/send?phone=" + phoneNumber + "&text=" + 
  URLEncoder.encode(messageText, "UTF-8");
  if(useWhatsAppBusiness){
    intent.setPackage("com.whatsapp.w4b");
  } else {
    intent.setPackage("com.whatsapp");
  }
  URLEncoder.encode(messageText, "UTF-8");
  intent.setData(Uri.parse(url));

  if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent);
  } else {
    Toast.makeText(this, "WhatsApp application not found", Toast.LENGTH_SHORT).show();
  }
Tarbox answered 8/10, 2020 at 17:30 Comment(1)
How to find number having business account or normal whatsapp account . please give a code of (useWhatsAppBusiness) your function.Maintenance
P
2

try this, worked for me ! . Just use intent

   Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(whatsappUrl()));
   startActivity(intent);

Build whatsapp url. add country code in whatsapp phone number https://countrycode.org/

public static String whatsappUrl(){

    final String BASE_URL = "https://api.whatsapp.com/";
    final String WHATSAPP_PHONE_NUMBER = "628123232323";    //'62' is country code for Indonesia
    final String PARAM_PHONE_NUMBER = "phone";
    final String PARAM_TEXT = "text";
    final String TEXT_VALUE = "Hello, How are you ?";

    String newUrl = BASE_URL + "send";

    Uri builtUri = Uri.parse(newUrl).buildUpon()
            .appendQueryParameter(PARAM_PHONE_NUMBER, WHATSAPP_PHONE_NUMBER)
            .appendQueryParameter(PARAM_TEXT, TEXT_VALUE)
            .build();

    return buildUrl(builtUri).toString();
}

public static URL buildUrl(Uri myUri){

    URL finalUrl = null;
    try {
        finalUrl = new URL(myUri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();

    }
    return finalUrl;
}
Phrasal answered 24/8, 2017 at 9:51 Comment(5)
but it just shows the send screen and requires you to click send button. can't it be automated that i don't have to press the send button? i tried many things all i got to was the screen but not send it automaticallyPavlish
Worked for me.. perfect! Thank you :)Frolicsome
yes work, but how to send automatic without click send button on whatsapp chat ?Lucia
I think whatsapp api doesn't have features to send automatic messange without opening whatsapp chat room before. Please read this for more details faq.whatsapp.com/en/android/26000030Phrasal
This worked as I expected. Opens the chat thread even the contact is not savedUnborn
V
2

Send a text to specific contact programmatically (Whatsapp)

try {
    val i = Intent(Intent.ACTION_VIEW)
    val url = "https://api.whatsapp.com/send?phone=91XXXXXXXXXX&text=yourmessage"
    i.setPackage("com.whatsapp")
    i.data = Uri.parse(url)
    startActivity(i)
} catch (e: Exception) {
   e.printStackTrace()
   val uri = Uri.parse("market://details?id=com.whatsapp")
   val goToMarket = Intent(Intent.ACTION_VIEW, uri)
   startActivity(goToMarket)
}
Vomiturition answered 15/2, 2021 at 6:40 Comment(0)
E
1
 private void openWhatsApp() {
       //without '+'
        try {
            Intent sendIntent = new Intent("android.intent.action.MAIN");

            //sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.setType("text/plain");
            sendIntent.putExtra("jid",whatsappId);
            sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            sendIntent.setPackage("com.whatsapp");
            startActivity(sendIntent);
        } catch(Exception e) {
            Toast.makeText(this, "Error/n" + e.toString(), Toast.LENGTH_SHORT).show();
            Log.e("Error",e+"")    ;    }
    }
Esta answered 6/11, 2017 at 13:2 Comment(0)
M
1

In Python, you can do it the same way we do it with mobile application

 web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)

This will prepopulate the text for given mobile number(Enter the phone_no as CountryCode and the number eg +918888888888) Then using pyautogui you can press enter onto whatsapp.web

Working code :

def sendwhatmsg(phone_no, message, time_hour, time_min):
     '''Sends whatsapp message to a particulal number at given time'''
     if time_hour == 0:
         time_hour = 24
     callsec = (time_hour*3600)+(time_min*60)

     curr = time.localtime()
     currhr = curr.tm_hour
     currmin = curr.tm_min
     currsec = curr.tm_sec

     currtotsec = (currhr*3600)+(currmin*60)+(currsec)
     lefttm = callsec-currtotsec

     if lefttm <= 0:
         lefttm = 86400+lefttm

     if lefttm < 60:
         raise Exception("Call time must be greater than one minute")

     else:
         sleeptm = lefttm-60
         time.sleep(sleeptm)
         web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)
         time.sleep(60)
         pg.press('enter')

I've taken this from this repository - Github repo

Munafo answered 15/12, 2019 at 3:7 Comment(0)
A
1

This code is implemented with Kotlin.

I have 2 versions:

1) For known contacts

private fun openWhatsApp(dato: WhatsApp) {
    val isAppInstalled = appInstalledOrNot("com.whatsapp")
    if (isAppInstalled) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://api.whatsapp.com/send?phone=${dato.whatsapp}"))
        startActivity(intent)
    } else {
        // WhatsApp not installed show toast or dialog
    }
}

private fun appInstalledOrNot(uri: String): Boolean {
    val pm = requireActivity().packageManager
    return try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES)
        true
    } catch (e: PackageManager.NameNotFoundException) {
        false
    }
}

In the case of being an unknown contact WhatsApp shows the following message

enter image description here

2) For unknown contacts

private fun openWhatsApp(dato: WhatsApp) {
    val isAppInstalled = appInstalledOrNot("com.whatsapp")
    if (isAppInstalled) {
        val sendIntent = Intent("android.intent.action.MAIN")
        sendIntent.setType("text/plain")
        sendIntent.setComponent(ComponentName("com.whatsapp", "com.whatsapp.Conversation"))
        sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(dato.whatsapp) + "@s.whatsapp.net")
        startActivity(sendIntent)
    } else {
        // WhatsApp not installed show toast or dialog
    }
}

private fun appInstalledOrNot(uri: String): Boolean {
    val pm = requireActivity().packageManager
    return try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES)
        true
    } catch (e: PackageManager.NameNotFoundException) {
        false
    }
}
Anguilliform answered 8/1, 2020 at 18:25 Comment(0)
B
1

Here is a way how to send message in WhatsApp in KOTLIN

    private fun sendMessage(phone: String, message: String) {
        val pm = requireActivity().packageManager
        val i = Intent(Intent.ACTION_VIEW)
        try {
            val url = "https://api.whatsapp.com/send?phone=$phone&text=" + URLEncoder.encode(
                message,
                "UTF-8"
            )
            i.setPackage("com.whatsapp")
            i.data = Uri.parse(url)
            if (i.resolveActivity(pm) != null) {
                context?.startActivity(i)
            }
        } catch (e: PackageManager.NameNotFoundException) {
            Toast.makeText(requireContext(), "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
        }
    }
Bash answered 25/6, 2020 at 8:0 Comment(0)
K
1

Use this function. Don't forget to save the WhatsApp Number on your mobile before sending trigger the function.

private void openWhatsApp() {
        Uri uri = Uri.parse("smsto:"+ "12345");
        Intent i = new Intent(Intent.ACTION_SENDTO,uri);
        i.setPackage("com.whatsapp");
        startActivity(i);
    }
Kenaz answered 20/7, 2020 at 11:51 Comment(0)
F
1

Update 2020

     String number="+91 7*********";
            String url="https://api.whatsapp.com/send?phone="+number + "&text=" + "Your text here";
            Intent i=new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
Finalism answered 18/11, 2020 at 7:57 Comment(0)
B
1

The following will open up the Whatsapp conversation (with a contact) page and prefill it with the text provided. Note: This is not going to automatically send the text off to the Whatsapp servers. It will only open the conversation page. The user needs to explicitly press the "Send" button to actually have the text sent to the servers.

String phoneId = "+1415xxxyyyy"; // the (Whatsapp) phone number of contact 
String text = "text to send";

Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
sendIntent.putExtra("jid", phoneId);
sendIntent.setPackage("com.whatsapp"); 
startActivity(sendIntent);
Berezina answered 19/6, 2021 at 18:10 Comment(1)
Added below lines and work for me. sendIntent.putExtra("jid", recipient+"@s.whatsapp.net"); sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ThanksHedberg
B
0

Check this answer. Here your number start with "91**********".

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_SEND);

sendIntent.setType("text/plain");                    
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");                   sendIntent.putExtra("jid",PhoneNumberUtils.stripSeparators("91**********")                   + "@s.whatsapp.net");                    
sendIntent.setPackage("com.whatsapp");                    
startActivity(sendIntent);
Busybody answered 3/6, 2017 at 10:58 Comment(0)
C
0

This will first search for the specified contact and then open a chat window.

Note: phone_number and str are variables.

Uri mUri = Uri.parse("https://api.whatsapp.com/send?
phone=" + phone_no + "&text=" + str);
Intent mIntent = new Intent("android.intent.action.VIEW", mUri);
mIntent.setPackage("com.whatsapp");
startActivity(mIntent);
Cadel answered 21/9, 2017 at 20:18 Comment(0)
I
0
Bitmap bmp = null;
            bmp = ((BitmapDrawable) tmpimg.getDrawable()).getBitmap();
            Uri bmpUri = null;
            try {
                File file = new File(getBaseContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".jpg");
                FileOutputStream out = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.close();
                bmpUri = Uri.fromFile(file);

            } catch (IOException e) {
                e.printStackTrace();
            }

            String toNumber = "+919999999999"; 
            toNumber = toNumber.replace("+", "").replace(" ", "");
            Intent shareIntent =new Intent("android.intent.action.MAIN");
            shareIntent.setAction(Intent.ACTION_SEND);
            String ExtraText;
            ExtraText =  "Share Text";
            shareIntent.putExtra(Intent.EXTRA_TEXT, ExtraText);
            shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            shareIntent.setType("image/jpg");
            shareIntent.setPackage("com.whatsapp");
            shareIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {

                startActivity(shareIntent);
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(getBaseContext(), "Sharing tools have not been installed.", Toast.LENGTH_SHORT).show();
            }

        }
Ivanna answered 2/6, 2018 at 3:19 Comment(1)
At present, this code does not have WhatsApp select the specific contact - it just shows the contact listSynecious
M
0
private void sendToContactUs() {
     String phoneNo="+918000874386";

    Intent sendIntent = new Intent("android.intent.action.MAIN");
    sendIntent.setAction(Intent.ACTION_VIEW);
    sendIntent.setPackage("com.whatsapp");
    String url = "https://api.whatsapp.com/send?phone=" + phoneNo + "&text=" + "Unique Code - "+CommonUtils.getMacAddress();
    sendIntent.setDataAndType(Uri.parse(url),"text/plain");


    if(sendIntent.resolveActivity(getPackageManager()) != null){
        startActivity(sendIntent);
    }else{
        Toast.makeText(getApplicationContext(),"Please Install Whatsapp Massnger App in your Devices",Toast.LENGTH_LONG).show();
    }
}
Madea answered 15/3, 2019 at 17:15 Comment(0)
T
0

 public void shareWhatsup(String text) {


        String smsNumber = "91+" + "9879098469"; // E164 format without '+' sign

        Intent intent = new Intent(Intent.ACTION_VIEW);

        try {
            String url = "https://api.whatsapp.com/send?phone=" + smsNumber + "&text=" + URLEncoder.encode(text, "UTF-8");
            intent.setPackage("com.whatsapp");
            intent.setData(Uri.parse(url));
        } catch (Exception e) {
            e.printStackTrace();
        }

        //    intent.setAction(Intent.ACTION_SEND);
        //   intent.setType("image/jpeg");
        //   intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUriArray);
        startActivity(intent);


    }
Tycoon answered 1/4, 2019 at 11:4 Comment(0)
S
0

Instead of biasing to share the content to whats app.

Following code is a generic code that will give a simple solution using "ShareCompact" that android opens the list of apps that supports the sharing the content.

Here I am sharing the data of mime-type text/plain.

    String mimeType = "text/plain"
    String Message  = "Hi How are you doing?"

    ShareCompact.IntentBuilder
                .from(this)
                .setType(mimeType)
                .setText(Message)
                .startChooser()
Straighten answered 19/8, 2019 at 9:23 Comment(0)
B
0

Whatsapp and most other apps that integrate into the Android core components (like Contacts) use a mime-type based intent to launch a certain Activity within the application. Whatsapp uses 3 separate mimetypes - text messages (vnd.android.cursor.item/vnd.com.whatsapp.profile), voip calls (vnd.android.cursor.item/vnd.com.whatsapp.voip.call) and video calls(vnd.android.cursor.item/vnd.com.whatsapp.video.call). For each of these mimetypes, a separate activity is mapped inside the Manifest of the application. For ex: the mimetype (...whatsapp.profile) maps to an Activity (com.whatsapp.Conversation). You can see these in detail if you dump out all the Data rows that maps to any Whatsapp Raw_Contact in your Contacts database.

This is also how the Android Contacts app shows 3 separate rows of user action inside a "Whatsapp contact", and clicking either of these rows launches a separate function inside Whatsapp.

To launch a Conversation (chat) Activity for a certain contact in Whatsapp, you need to fire an intent containing MIME_TYPE and DATA_URL. The mimetype points to the mimetype corresponding to your action as defined inside Whatsapp's Raw Contact in Contacts database. The DATA_URL is the URI of the Raw_Contact in the Android contacts database.

String whatsAppMimeType = Uri.parse("vnd.android.cursor.item").buildUpon()
                                    .appendEncodedPath("vnd.com.whatsapp.profile").build().toString();

Uri uri = ContactsContract.RawContacts.CONTENT_URI.buildUpon()
        .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.whatsapp")
        .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, "WhatsApp")
        .build();

Cursor cursor = getContentResolver().query(uri, null, null, null);
if (cursor==null || cursor.getCount()==0) continue;

cursor.moveToNext();
int rawContactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.RawContacts._ID));
cursor.close();

// now search for the Data row entry that matches the mimetype and also points to this RawContact
Cursor dataCursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
        null,
        ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.Data.RAW_CONTACT_ID + "=?",
        new String[]{whatsAppMimeType, String.valueOf(rawContactId)}, null);
if (dataCursor==null || dataCursor.getCount()==0) continue;

dataCursor.moveToNext();
int dataRowId = dataCursor.getInt(dataCursor.getColumnIndex(ContactsContract.Data._ID));

Uri userRowUri = ContactsContract.Data.CONTENT_URI.buildUpon()
                        .appendPath(String.valueOf(dataRowId)).build();


// launch the whatsapp user chat activity
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(userRowUri, whatsAppMimeType);
startActivity(intent);

dataCursor.close();

This is the same way that all Contacts app use to launch a chat Activity for a Whatsapp contact. Inside this Activity, the application (Whatsapp) reads in the .getData() to get the DATA_URI which was passed to this Activity. The Android Contacts app uses a standard mechanism to use the URI of the Raw Contact in Whatsapp. Unfortunately, I am not aware of a way by which the .Conversation ativity in Whatsapp reads in any text / data information from the caller of the intent. This basically means that its possible (using a very standard technique) to launch a certain "user action" inside Whatsapp. Or for that matter, any similar app.

Berezina answered 26/9, 2019 at 22:52 Comment(1)
This only opens the contact page in Whatsapp but does not include a Text. How do you send the text?Merrilee

© 2022 - 2024 — McMap. All rights reserved.