首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python发送微信及企业微信消息

python发送微信及企业微信消息

作者头像
用户1558882
发布2019-06-21 13:02:32
9.6K0
发布2019-06-21 13:02:32
举报
文章被收录于专栏:RgcRgc

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": "测试:你的快递已到\n请携带工卡前往邮件中心领取"
                           },
                           "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": "你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。"
                           },
                           "safe": 0
                       }
                       ))
print(result.text)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-06-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档