Python | PHP | JAVA 发送消息到企业微信机器人
企业微信群机器人说明文档:https://developer.work.weixin.qq.com/document/path/91770。利用群机器人有个优点,在程序哪里经常抛出异常,就可以在第一时间知道。
Python3:
import json import requests from datetime import datetime def send_wecom_msg(content, webhook_url=""): data = {"msgtype": "text", "text": {"content": content}} r = requests.post(url=webhook_url, data=json.dumps(data, ensure_ascii=False).encode('utf-8')) return r.text, r.status_code wecom_robot = '你的机器人webhook地址' print(send_wecom_msg(f"现在是{str(datetime.now())}", wecom_robot))
PHP7:
<?php class WecomRobot{ private string $webhookUrl; public function __construct($webhookUrl) { $this->webhookUrl = $webhookUrl; } /** * PHP发送Json对象数据 * @param $url string 请求url * @param $jsonStr string 发送的json字符串 * @param array $header * @return string */ static function httpPostJson(string $url, string $jsonStr,array $header=[]) :string { $header = array_filter($header); $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge([ 'Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($jsonStr) ], $header) ); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $response = curl_exec($ch); curl_close($ch); return $response; } /** * 发送到机器人 * @param string $content 消息 * @return string */ public function sendWecomMsg(string $content): string { $params = [ 'msgtype' => 'text', 'text' => [ 'content' => $content ] ]; return self::httpPostJson($this->webhookUrl, json_encode($params)); } } $wecomRobot = new WecomRobot('你的机器人webhook地址'); $response = $wecomRobot->sendWecomMsg('现在是' . date('Y-m-d H:i:s')); echo $response;
JAVA:
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * http请求工具类 * * @author zhangyong */ public class HttpUtils { private static class DefaultTrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } /** * 以application/json; charset=utf-8方式传输 * * @param url URL * @param jsonContent JSON字符串 * @throws SocketTimeoutException 抛出异常 * @throws IOException 抛出异常 */ public void postJson(String url, String jsonContent) throws IOException { String CTYPE_JSON = "application/json; charset=utf-8"; doRequest(url, jsonContent, CTYPE_JSON ); } private void doRequest(String url, String requestContent, String ctype) throws IOException { HttpURLConnection conn = null; OutputStream out = null; String rsp = null; try { conn = getConnection(new URL(url), ctype); conn.setConnectTimeout(15000); conn.setReadTimeout(15000); if (!requestContent.isEmpty()) { out = conn.getOutputStream(); String charset = "utf-8"; out.write(requestContent.getBytes(charset)); } rsp = getResponseAsString(conn); } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } conn = null; } } private HttpURLConnection getConnection(URL url, String ctype) throws IOException { HttpURLConnection conn; if ("https".equals(url.getProtocol())) { SSLContext ctx; try { ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom()); } catch (Exception e) { throw new IOException(e); } HttpsURLConnection connHttps = (HttpsURLConnection) url .openConnection(); connHttps.setSSLSocketFactory(ctx.getSocketFactory()); connHttps.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); conn = connHttps; } else { conn = (HttpURLConnection) url.openConnection(); } conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html,application/json"); conn.setRequestProperty("Content-Type", ctype); return conn; } private String getResponseAsString(HttpURLConnection conn) throws IOException { InputStream es = conn.getErrorStream(); if (es == null) { return getStreamAsString(conn.getInputStream(), conn); } else { String msg = getStreamAsString(es, conn); if (msg.isEmpty()) { throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage()); } else { return msg; } } } private String getStreamAsString(InputStream stream, HttpURLConnection conn) throws IOException { try { Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); StringBuilder response = new StringBuilder(); final char[] buff = new char[1024]; int read = 0; while ((read = reader.read(buff)) > 0) { response.append(buff, 0, read); } return response.toString(); } finally { if (stream != null) { stream.close(); } } } }
public class App { public static void main(String[] args) throws java.io.IOException { HttpUtils utils = new HttpUtils(); utils.postJson("你的机器人webhook地址", "{\"msgtype\": \"text\", \"text\": {\"content\": 123456}"); } }