微信群发功能

微信的群发功能个人觉得比较复杂一点
1.如果是纯文字的群发比较简单
2.如果是图片的,需要获取thumb_media_id
3.如果是图文信息,需要获取thumb_media_id

获取thumb_media_id,需要先上传媒体资源到服务器,且必须是永久的,调用的接口如下所示:
这里写图片描述

其中media类型共有5种
图片(image): 2M,支持bmp/png/jpeg/jpg/gif格式
语音(voice):2M,播放长度不超过60s,mp3/wma/wav/amr格式
视频(video):10MB,支持MP4格式
缩略图(thumb):64KB,支持JPG格式
代码演示:

public static void  getMediaId(String appId,String appSecret) {
        String addImage = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";

        //上传临时素材
        String addImage2 = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=thumb";

        //上传永久素材
        String addImage3 = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=thumb";

        String filepath ="src/main/webapp/image/1.jpg";

        AccessToken at = WeixinUtil.getAccessToken(appId, appSecret);
        String token = at.getToken();
        //临时素材上传
       /* String url = addImage2.replace("ACCESS_TOKEN",token);
        UploadFile.postFile(url,filepath,"Hello World","shshsuhsushsh");*/
        //上传永久素材
        String url2 = addImage3.replace("ACCESS_TOKEN",token);
        UploadFile.postImgFile(url2,filepath);
        File file = new File("src/main/webapp/image/1.jpg");
        System.out.print(file.exists());
    }
public class UploadFile {
public static String postFile(String url, String filePath,
                                  String title,String introduction) {
        File file = new File(filePath);
        if(!file.exists())
            return null;
        String result = null;
        try {
            URL url1 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            String boundary = "-----------------------------"+System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);

            OutputStream output = conn.getOutputStream();
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName()).getBytes());
            output.write("Content-Type: video/mp4 \r\n\r\n".getBytes());
            byte[] data = new byte[1024];
            int len =0;
            FileInputStream input = new FileInputStream(file);
            while((len=input.read(data))>-1){
                output.write(data, 0, len);
            }
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
            output.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}",title,introduction).getBytes());
            output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
            output.flush();
            output.close();
            input.close();
            InputStream resp = conn.getInputStream();
            StringBuffer sb = new StringBuffer();
            while((len= resp.read(data))>-1)
                sb.append(new String(data,0,len,"utf-8"));
            resp.close();
            result = sb.toString();
            System.out.println(result);
        } catch (ClientProtocolException e) {
            logger.error("postFile,不支持http协议",e);
        } catch (IOException e) {
            logger.error("postFile数据传输失败",e);
        }
        logger.info("{}: result={}",url,result);
        return result;
    }

    //上传图片
    public static String postImgFile(String url, String filePath) {
        File file = new File(filePath);
        if (!file.exists())
            return null;
        String result = null;
        try {
            URL url1 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            String boundary = "-----------------------------" + System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            OutputStream output = conn.getOutputStream();
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(
                    String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName())
                            .getBytes());
            output.write("Content-Type: image/jpeg \r\n\r\n".getBytes());
            byte[] data = new byte[1024];
            int len = 0;
            FileInputStream input = new FileInputStream(file);
            while ((len = input.read(data)) > -1) {
                output.write(data, 0, len);
            }
            output.write(("\r\n--" + boundary + "\r\n\r\n").getBytes());
            output.flush();
            output.close();
            input.close();
            InputStream resp = conn.getInputStream();
            StringBuffer sb = new StringBuffer();
            while ((len = resp.read(data)) > -1)
                sb.append(new String(data, 0, len, "utf-8"));
            resp.close();
            result = sb.toString();
            System.out.println(result);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;
    }

这样就可以获取到thumb_media_id,接下来就是群发的功能了。

说到群发的话,这里我用测试号测试了只有文本的可以进行群发,其他的都不成功,官网写着根据标签进行群发【订阅号与服务号认证后均可用】,没交钱没办法,只能试试阉割版的咯。

public static String sendGroupMessage(String token){
        String groupUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN";//ACCESS_TOKEN是获取到的access_token,根据分组id发群发消息地址
        String groupUrl1 = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN";
        String url = groupUrl1.replace("ACCESS_TOKEN",token);
        String openid1data = "{\"touser\":[\"oBLL2wL5GlPE5wo3ihbmU0VxE7qs\",\"oBLL2wGrduSANLkm4BheKclWCcKQ\"],\"msgtype\": \"text\",\"text\": {\"content\": \"测试文本666消息\"}}";
        String group1data = "{\"filter\":{\"is_to_all\":false,\"group_id\":\"3\"},\"text\":{\"content\":\"群发消息测试\"},\"msgtype\":\"text\"}";
        JSONObject json = CommUtil.httpRequest(url, "POST", openid1data);
        return json.toString();
    }


    /** 
     * 发起https请求并获取结果 
     *  
     * @param requestUrl 请求地址 
     * @param requestMethod 请求方式(GET、POST) 
     * @param outputStr 提交的数据 
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 
     */  
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;  
        StringBuffer buffer = new StringBuffer();  
        try {  
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化  
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象  
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);  

            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式(GET/POST)  
            httpUrlConn.setRequestMethod(requestMethod);  

            if ("GET".equalsIgnoreCase(requestMethod))  
                httpUrlConn.connect();  

            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  

            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
          ce.printStackTrace();
        } catch (Exception e) {  
           e.printStackTrace();
        }  
        return jsonObject;  
    }  

以上代码仅供参考,未在真实环境测过,不知性能如何

参考资料
http://blog.youkuaiyun.com/oarsman/article/details/51538078
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729
http://blog.youkuaiyun.com/heboy19/article/details/49815611
http://www.cnblogs.com/h–d/p/5638092.html
http://lib.youkuaiyun.com/article/wechat/55774

下载地址
http://download.youkuaiyun.com/download/ooiuy450/9957982

### 使用 Python 和 wxauto 实现微信群发功能 #### 导入必要的库 为了实现微信群发功能,首先需要导入 `wxauto` 库中的 `WeChat` 类以及其他可能需要用到的库。 ```python from wxauto import WeChat import time ``` #### 初始化微信实例并登录 创建一个微信实例,并确保已经成功登录微信客户端。这一步骤非常重要,因为后续的操作都将基于此实例进行。 ```python wechat = WeChat() time.sleep(2) # 等待两秒让微信加载完成 ``` #### 获取目标聊天对象 可以通过多种方式获取要发送消息的目标聊天对象,比如通过群聊名称或者好友昵称查找对应的会话窗口。 ```python group_names = ["测试群", "学习交流"] # 替换为您自己的群组名字列表 for group_name in group_names: wechat.ChatWith(group_name) time.sleep(1) # 切换聊天框时稍作停顿以保证稳定性 ``` #### 发送消息给多个群聊 一旦选定了具体的聊天对象之后就可以向其发送预设的消息内容了。这里假设有一个事先准备好的字符串变量存储着想要发出的信息文本。 ```python message_text = "这是今天的每日一句:生活最大的危险在于一个空虚的心。" for _ in range(len(group_names)): wechat.SendMsg(message_text) time.sleep(1) # 每次发送后等待一秒再继续下一个 ``` 以上代码片段展示了如何使用 `wxauto` 库来执行基本的微信群发任务[^2]。需要注意的是,在实际应用过程中应当谨慎处理频率限制等问题以免触发平台的安全机制而被封禁账号。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值