python实现企业微信应用发送长消息并将发送情况返回
以下是Python实现企业微信应用发送长消息的代码示例:
import requests
import json
# 设置企业微信应用的相关信息
corp_id = 'your_corp_id'
app_secret = 'your_app_secret'
agent_id = 'your_agent_id'
access_token_url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={app_secret}'
# 获取access_token
response = requests.get(access_token_url)
access_token = json.loads(response.text)['access_token']
# 构造发送消息的请求体
message_content = {
"msgtype": "text",
"text": {
"content": "这是一条长消息,需要换行符才能换行:\n第一行\n第二行\n第三行\n第四行\n第五行"
},
"safe": 0
}
# 发送消息
send_message_url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}'
response = requests.post(send_message_url, data=json.dumps(message_content))
send_result = json.loads(response.text)
# 输出发送结果
if send_result['errcode'] == 0:
print('消息发送成功')
else:
print(f'消息发送失败,错误码:{send_result["errcode"]},错误信息:{send_result["errmsg"]}')
以上代码会发送一条包含多行文字的长消息,并将发送结果返回。其中,需要注意以下几点:
- 消息内容需要通过换行符
\n来实现换行。 - 发送消息需要先获取
access_token,可以通过调用企业微信的gettoken接口来获取。 - 发送消息需要使用
POST方法,并将请求体中的msgtype设置为text,text节点中的content为消息内容。 - 发送结果中的
errcode为0表示发送成功,非0表示发送失败
原文地址: https://www.cveoy.top/t/topic/eEUw 著作权归作者所有。请勿转载和采集!