zoukankan      html  css  js  c++  java
  • python发送微信及企业微信消息

    1.发送微信消息

    直接使用第三方库 itchat,其文档中有详细使用方式; https://itchat.readthedocs.io/zh/latest/

    如下实例为 发送群聊信息

    # -*- coding: utf-8 -*-
    # (C) Guangcai Ren, 2019
    # All rights reserved
    import logging
    
    import itchat
    
    log = logging.getLogger(__name__)
    
    # itchat 微信官方教程:https://itchat.readthedocs.io/zh/latest/
    # 微信登录
    # 登录时如果断网,则此程序直接停止
    # 启动热登录,并且生成 命令行 登录二维码
    itchat.auto_login(hotReload=True, enableCmdQR=2)
    # 保持心跳状态,防止自动退出登录
    itchat.start_receiving()
    
    # 获取群聊,注意群 必须保持到通讯录,否则可能会找不到群
    itchat.get_chatrooms(update=True)
    room = itchat.search_chatrooms('python')
    if len(room) == 0:
        log.error('没有找到群信息')
    else:
        try:
            iRoom = room[0]['UserName']
            # 发送消息
            result = itchat.send('send message', iRoom)
            try:
                if result['BaseResponse']['ErrMsg'] == '请求成功':
                    log.info('send wechat success')
            except Exception as e:
                print('resolve wechat result fail,result is :{},error is {}'.format(result, e))
        except Exception as e:
            print('wechat send message fail,reason is :{} '.format(e))

    2.发送企业微信 信息

    企业微信 官方有 相关文档,直接按照文档开发即可。

    注意点:

    • 先开通企业微信 
    • 登录网页版 企业微信 https://work.weixin.qq.com/  从中查找相关 id(在获取访问token时需要)
    • 接口一般 流程为 先 获取 token,再用 token访问其他接口
    • 发送群聊信息时,群id 只能通过 接口创建群聊的才有群id
    • 创建群聊时的 获取token的参数 corpsecret必须 从 应用的 部门一定要选根目录,否则报错 86006;
    • 如果开发过程中有任何问题(错误提示有一定的误导性) 可以通过 企业微信客服 进行沟通解决,他们非常有耐心,谢谢他们。 

    如下代码 做到了 获取token,创建群聊,发送群聊信息,发送个人信息

    # -*- coding: utf-8 -*-
    # (C) Guangcai Ren <renguangcai@jiaaocap.com>
    # All rights reserved
    # create time '2019/6/13 17:17'
    import json
    
    import requests
    
    result = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken",
                          params={'corpid': 'fg',
                                  'corpsecret': '45'})
    access_token = None
    if result.status_code != 200:
        print('连接到服务器失败')
    else:
        result_json = json.loads(result.text)
        if result_json['errcode'] != 0:
            print('响应结果不正确')
        else:
            access_token = result_json['access_token']
            print(access_token)
    
    # 创建群聊
    result = requests.post('https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token={}'.format(access_token),
                           data=json.dumps({
                               "name": "通知群",
                               "owner": "user_name",
                               "userlist": ["user_name", "user_name1", "user_name2"],
                               "chatid": "secid"
                           }))
    print(result.text)
    
    # 推送群聊信息
    result = requests.post('https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={}'.format(access_token),
                           data=json.dumps({
                               "chatid": "secid",
                               "msgtype": "text",
                               "text": {
                                   "content": "测试:你的快递已到
    请携带工卡前往邮件中心领取"
                               },
                               "safe": 0
                           }))
    print(result.text)
    
    # 发送个人消息
    result = requests.post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}'.format(access_token),
                           data=json.dumps({
                               "touser": "user_name",
                               "msgtype": "text",
                               "agentid": 23,
                               "text": {
                                   "content": "你的快递已到,请携带工卡前往邮件中心领取。
    出发前可查看<a href="http://work.weixin.qq.com">邮件中心视频实况</a>,聪明避开排队。"
                               },
                               "safe": 0
                           }
                           ))
    print(result.text)
  • 相关阅读:
    mysql之alter 字段的修改、添加、删除
    mysql之Percona-XtraDB-Cluster prohibits without an explicit primary key with pxc_strict_mode = ENFORCING or MASTER报错
    mysql之常用操作,创建库、表,删除库、表
    Spring Boot的消息之旅(一)
    Spring Boot的日志之旅(一)
    Spring Boot的缓存之旅(二)
    Spring Boot的缓存之旅(一)
    使用Druid数据库连接池
    Spring Boot的数据库之旅(二)
    Spring Boot的安全之旅(一)
  • 原文地址:https://www.cnblogs.com/rgcLOVEyaya/p/RGC_LOVE_YAYA_1075days.html
Copyright © 2011-2022 走看看