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.发送企业微信 信息
企业微信 官方有 相关文档,直接按照文档开发即可。
注意点:
应用的 部门一定要选根目录,否则报错 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)