方法一:webhook方式。使用群机器人给企微群发消息
import requests
def qwxsendmessage(msg):
url='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6c598840-804a-4eb5-a999-a023313' #url换成自己群机器人的webhookurl
data={
'msgtype':'text',
'text':{
'content':msg
}
}
print(data)
res=requests.post(url,json=data)
消息发送频率限制:每个机器人发送的消息不能超过20条/分钟。
方法二:使用自建应用的方式
企微还可以用另一种自建应用的方式,然后通过接口实现单聊发消息,但是自建应用需要配置企业可信任ip。这个配置过程挡住了很多人,最后我也放弃了,没有和企微备案一致的域名。
下面是使用自建应用发送消息的代码
import requests
import json
#获取token
def qwxget_token():
corpid='wx38bbebfb0834' #corpid换成自己的
corpsecret='OfQLVaaCeJT9vrxini3EYrN71xO8PQzLGFnET' #corpsecret换成自己的
url='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='+corpid+'&corpsecret='+corpsecret
response=requests.get(url)
dict_response=response.json()
token=dict_response['access_token']
return token
#发送消息
def qwxmessage(token):
data={
'touser':'PengXuan', #成员编号换成自己的
'msgtype':'text',
'agentid':1000033, #应用id换成自己的
'text':{
'content':'我就试一下'
},
'safe':0
}
url='https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+token
res=requests.post(url,data=json.dumps(data,ensure_ascii=False).encode('utf-8')).json()
print(res)
#调用
token=qwxget_token()
qwxmessage(token)
执行调用后,返回错误代码
{'errcode': 60020, 'errmsg': 'not allow to access from your ip, hint: [1709260518618543373180730], from ip: 27.188.36.174, more info at https://open.work.weixin.qq.com/devtool/query?e=60020'}
经过查询企微开放平台的错误码:
错误码:60020
不安全的访问IP。请根据调用的应用类型分别按如下方法确认:
1)若调用者是企业自建应用或通讯录同步助手,请确认该IP是本企业服务器IP,并已经配置到应用详情的“企业可信IP”项目中。第三方服务商IP不能调用。
2)若调用者是第三方应用或服务商代开发应用,请确认该IP已经配置到“服务商管理后台”-“服务商信息”-“基本信息”-“IP白名单”。
3) 配置完可信IP之后,需要1分钟后才生效。
上面这个配置最后我也没有完成,后面有机会再试吧。