python调用钉钉的发送工作通知接口

python调用钉钉的发送工作通知接口

背景:公司用的另一个crm系统有一些未及时操作的内容需要钉钉提醒操作人及时处理
步骤:
1、获取accesstoken,正常获取,开发文档

def getToken():
    url = 'https://oapi.dingtalk.com/gettoken?appkey='+appkey+'&appsecret='+appsecret
    response = requests.get(url=url)
    result = response.json()
    errmsg = result['errmsg']
    print('获取密钥是否成功:',errmsg)
    try:
        access_token = result['access_token']
    except Exception as e:
        print(e)
        access_token = ''
    return access_token
access_token = getToken()

2、给用户发送工作通知,出现问题,如下为原代码,开放文档

#给用户发送工作通知
content = '测试消息,工作通知'
url = 'https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token='+access_token
_data = {
        'agent_id':AgentId,
        'userid_list':users,
        'msg':{
                'msgtype':'text',
                'text':{'content':content}}
        }
data = '%s'%_data
response = requests.post(url=url,data=data)
result = response.json()
print(result)

运行后提示:UnicodeEncodeError: 'latin-1' codec can't encode characters in position 109-121: Body ('这是一个测试的工作通知内容') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
在这里插入图片描述
将content内容换成英文就成功发送,根据提示加入了encode,却报另一个错误:{'errcode': 41, 'errmsg': 'Invalid arguments:parameter format is json , but parse error', 'request_id': '709mlrwdmfk5'}
在这里插入图片描述
最后感谢群里的小伙伴的提醒(@unknown),用json.dumps试了一下,并且自主的把encode去掉,竟然成功了。
以下是成功的代码:

#给用户发送工作通知
url = 'https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token='+access_token
_data = {
        'agent_id':AgentId,
        'userid_list':users,
        'msg':{
                'msgtype':'text',
                'text':{'content':content}}
        }
data = json.dumps(_data)
response = requests.post(url=url,data=data)
result = response.json()
print(result)

补充:
钉钉后台创建微应用,工作台-自建应用
在这里插入图片描述
填写应用名称-上传logo-填写简介-开发方式我这里企业内部自主开发,
在这里插入图片描述
下一步配置开发信息,开发模式为’开发应用‘,应用类型,微应用是电脑端,
服务器出口IP,我这里由于是本机调试,直接在搜索引擎上查到本地的上网IP。填入即可,接口调用时会验证请求IP,其他的根据实际情况了
在这里插入图片描述
创建好之后。在自建应用的位置右上角点击设置,进入应用详情
在这里插入图片描述
基础信息-查看详情
在这里插入图片描述
在这里插入图片描述
点击查看即可获取AppSecret

  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值