通过编程向特定联系人发送文本消息(WhatsApp)

80

我想知道如何向特定的WhatsApp联系人发送文本。我找到了一些代码来查看特定的联系人,但没有发送数据的代码。

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();

这对于查看WhatsApp联系人很好用,但现在我如何添加一些文本呢?或者Whatsapp开发人员没有实现这种API吗?


重复的问题,参考链接:https://dev59.com/6WUp5IYBdhLWcg3wLVKn - rds
5
不,你提供的链接使用了一个选择器,而我不想用它。我想直接将文本发送给一个联系人。 - Manuel Allenspach
他想要打开聊天记录,而我想要发送文本。这是非常不同的。 - Manuel Allenspach
1
@manu 你好,我在我的应用程序中使用了你的代码来向Whatsapp发送消息,而不必打开Whatsapp,但是我遇到了getSherlockActivity()的错误。由于我是Android新手,所以我不理解getSherlockActivity()是什么意思。 - Mahi
似乎无法通过WhatsApp程序化地发送消息,所以我放弃了... - Manuel Allenspach
显示剩余2条评论
29个回答

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")));

                }

3
现在,通过WhatsApp商业API就可以实现。只有企业才能申请使用它。这是直接向电话号码发送消息的唯一方式,无需任何人工干预。 发送普通消息是免费的。看起来您需要在服务器上托管MySQL数据库和WhatsApp Business客户端。

1
你从哪里得到的信息说发送普通消息是免费的?我认为不是这样的。 - v8rs

3

您还可以选择 WhatsApp Business 和 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();
  }

如何查找具有商业账户或普通WhatsApp账户的号码。请提供您的函数(useWhatsAppBusiness)代码。 - Saurabh Gaddelpalliwar

2

尝试这个方法,我用过很有效!只需要使用意图(intent)

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

构建 WhatsApp URL。在 WhatsApp 电话号码中添加国家代码。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;
}

但它只显示发送屏幕并要求您单击“发送”按钮。难道不能自动化,而无需按下“发送”按钮吗?我尝试了很多方法,但只能获得屏幕,而不能自动发送。 - Simple Fellow
对我很有效,完美!谢谢 :) - NightFury
可以工作,但如何在WhatsApp聊天中自动发送而无需点击发送按钮? - shodiqul muzaki
我认为WhatsApp API没有发送自动消息的功能,除非先打开WhatsApp聊天室。请阅读此链接以获取更多详细信息:https://faq.whatsapp.com/en/android/26000030/ - Taufiq Suryanto
这个按照我的预期工作了。即使联系人未保存,也会打开聊天线程。 - Reddy Raaz

2
以编程方式向特定联系人发送短信(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)
}

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+"")    ;    }
    }

1
以下将打开WhatsApp的对话(与联系人)页面,并填充提供的文本。注意:这不会自动将文本发送到WhatsApp服务器。它只会打开对话页面。用户需要明确按下“发送”按钮才能将文本发送到服务器。
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);

1
以下代码行已添加,可以正常工作: sendIntent.putExtra("jid", recipient+"@s.whatsapp.net"); sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - Zumbarlal Saindane

1
在Python中,您可以像处理移动应用程序一样进行操作。
 web.open('https://web.whatsapp.com/send?phone='+phone_no+'&text='+message)

这将为给定的手机号预填文本(将phone_no输入为国家代码和号码,例如+918888888888) 然后使用pyautogui,您可以按Enter键进入whatsapp.web
工作代码:
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')

我从这个仓库中获取了这个 - Github repo


1
使用这个函数。在触发函数之前,不要忘记将WhatsApp号码保存到您的手机上。
private void openWhatsApp() {
        Uri uri = Uri.parse("smsto:"+ "12345");
        Intent i = new Intent(Intent.ACTION_SENDTO,uri);
        i.setPackage("com.whatsapp");
        startActivity(i);
    }

1

以下是使用KOTLIN发送WhatsApp消息的方法:

    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()
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接