栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python接入钉钉自定义机器人

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python接入钉钉自定义机器人

官网文档

自定义机器人接入

自定义机器人

需要在钉钉pc端进行操作,获得webhook地址及secret

import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse

class DingTalkBot:
    #text link markdown ActionCard FeedCard
    #https://developers.dingtalk.com/document/robots/custom-robot-access
    msgtype="text"
    headers={"Content-Type":"application/json;charset=UTF-8"}
    atMobiles=[]
    atUserIds=[]
    isAtAll=False
    verify=False


    def __init__(self, webhook, encryptionkey):
      self.webhook = webhook
      self.encryptionkey = encryptionkey

    def webhook_sign(self):
        '''
        加签
        '''
        timestamp = str(round(time.time() * 1000))
        secret_enc = self.encryptionkey.encode('utf-8')
        string_to_sign = '{}n{}'.format(timestamp, self.encryptionkey)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        url = self.webhook+'×tamp='+timestamp+'&sign='+sign
        return url
    
    def send_text(self,content):
        '''
        发送文本消息
        content:消息内容
        '''
        msg_body ={
            "msgtype": "text",
            "text": {
                "content": content
            },
            "at": {
                "atMobiles":self.atMobiles,
                "atUserIds":self.atUserIds,
                "isAtAll": self.isAtAll
            }
        }
        try:
            res = requests.post(self.webhook_sign(),data=json.dumps(msg_body),headers=self.headers,verify=False)
            return res
        except Exception as e:
            return {"errmsg":repr(e)}

    def send_link(self,title,text,picUrl,messageUrl):
        '''
        发送链接
        title:消息标题
        text:消息内容。如果太长只会部分展示
        messageUrl:点击消息跳转的URL
        picUrl:图片URL
        '''
        message = {
            "msgtype": "link",
            "link":{
                "text":text,
                "title":title,
                "picUrl":picUrl,
                "messageUrl":messageUrl
            },
            "at": {
                "atMobiles":self.atMobiles,
                "atUserIds":self.atUserIds,
                "isAtAll": self.isAtAll
            }
        }

        try:
            res = requests.post(self.webhook_sign(),data=json.dumps(message),headers=self.headers,verify=False)
            return res.content
        except Exception as e:
            return {"errmsg":repr(e)}

    def send_markdown(self,title,text):
        '''
        发送markdown
        title:首屏会话透出的展示内容
        text:markdown格式的消息
        '''
        message = {
            "msgtype":"markdown",
            "markdown":{
                "title":title,
                "text":text
            }
        }

        try:
            res = requests.post(self.webhook_sign(),data=json.dumps(message),headers=self.headers,verify=False)
            return res
        except Exception as e:
            return {"errmsg":repr(e)}

    def send_actionCard_entire(self,title,text,btnOrientation,singleTitle,singleURL):
        '''
        发送actionCard 整体跳转
        title:首屏会话透出的展示内容
        text:markdown格式的消息
        singleTitle:单个按钮的标题(设置此项和singleURL后,btns无效)
        singleURL:点击singleTitle按钮触发的URL
        btnOrientation:0:按钮竖直排列,1:按钮横向排列
        '''
        message = {
            "msgtype": "actionCard",
            "actionCard": {
                "title": title, 
                "text": text, 
                "btnOrientation": btnOrientation, 
                "singleTitle" : singleTitle,
                "singleURL" : singleURL
            }
        }

        try:
            res = requests.post(self.webhook_sign(),data=json.dumps(message),headers=self.headers,verify=False)
            return res
        except Exception as e:
            return {"errmsg":repr(e)}


    def send_actionCard_alone(self,title:str,text:str,btnOrientation:str,btns:list=[]):
        '''
        发送actionCard 独立跳转ActionCard类型
        title:首屏会话透出的展示内容
        text:markdown格式的消息
        btns:按钮 eg:[{"title":"YES","actionURL":"http://www.baidu.com"},{"title":"NO","actionURL":"http://www.baidu.com"}]
        title:按钮标题
        actionURL:点击按钮触发的URL
        btnOrientation:0:按钮竖直排列 1:按钮横向排列
        '''
        message = {
            "msgtype":"actionCard",
            "actionCard":{
                "title":title,
                "text":text,
                "btnOrientation":btnOrientation,
                "btns":btns
            }
        }

        try:
            res = requests.post(self.webhook_sign(),data=json.dumps(message),headers=self.headers,verify=False)
            return res
        except Exception as e:
            return {"errmsg":repr(e)}

    def send_feedCard(self,links:list=[]):
        '''
        发送feedCard类型
        links:链接组 eg:[{"title":"title1","messageURL":"http://www.baidu.com","picURL":"https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"}]
        '''
        message = {
            "msgtype":"feedCard",
            "feedCard":{
                "links":links
            }

        }

        try:
            res = requests.post(self.webhook_sign(),data=json.dumps(message),headers=self.headers,verify=False)
            return res
        except Exception as e:
            return {"errmsg":repr(e)}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/503669.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号