8. Python 钉钉消息

# https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxxxxxxxxxx

# 加签验证方式:加签的方式是钉钉机器人与开发者双向进行安全认证,以此来验证安全性。具体加签计算步骤如下:
# 将时间戳 timestamp 和密钥 secret 当做签名字符串,使用HmacSHA256算法计算签名,然后进行Base64 encode,最后再把签名参数再进行urlEncode,得到最终的签名(需要使用UTF-8字符集)。
# timestamp:开发者服务内当前系统时间戳,单位是毫秒,与请求调用时间误差不能超过1小时。
# secret:密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串。
# 签名计算代码示例(Python)
import requests
import json

class DingTalk_Base():
    def __init__(self):
        self.__headers = {'Content-Type': 'application/json;charset=utf-8'}
        self.access_url = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
        self.secret = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
        self.timestamp = ''
        self.sign = ''
        self.url = ''

    def get_bot_url(self):
        import time
        import hmac
        import hashlib
        import base64
        import urllib.parse

        self.timestamp = str(round(time.time() * 1000))
        secret = self.secret
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(self.timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc,
                             digestmod=hashlib.sha256).digest()
        self.sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        # print(timestamp)
        # print(sign)
        # 拿到开发服务内当前系统 timestamp 和加密 sign 签名值,将 timestamp 和 sign 拼接到 URL 中。
        self.url = self.access_url + \
            f"&timestamp={self.timestamp}&sign={self.sign}"
        # print(self.url)
        return self.url

    def send_msg(self, text):
        self.url = self.get_bot_url()

        json_text = {
            "msgtype": "text",
            "text": {
                "content": text  # 写入要传送的内容
            },
            "at": {
                "atMobiles": [""],
                "isAtAll": False
            }
        }
        return requests.post(self.url, json.dumps(json_text), headers=self.__headers).content

    def curl_msg(self):
        import subprocess

        # 钉钉机器人的Webhook地址
        webhook_url = self.get_bot_url()

        # 要发送的消息内容
        message = {
            "msgtype": "text",
            "text": {
                "content": "你好,这是一个 subprocess 测试消息。"
            }
        }

        # 将消息转换为JSON字符串
        import json
        message_json = json.dumps(message)

        # 使用curl命令通过subprocess发送POST请求
        completed_process = subprocess.run(
            ['curl', '-H', 'Content-Type: application/json',
                '-d', f'{message_json}', webhook_url],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )

        # 输出curl命令的输出或错误信息
        print(completed_process.stdout)
        if completed_process.stderr:
            print(completed_process.stderr)

        # curl -X POST https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxxxxxxxxxx&timestamp=1715315095935&sign=xxxxxxxxxxxxxxxxxxxxxx -H 'Content-Type: application/json' -d '{'msgtype': 'text', 'text': {'content': '这是一条测试信息'}}'

    def ding_talk(self):
        # pip install dingtalkchatbot
        from dingtalkchatbot.chatbot import DingtalkChatbot
        bot = DingtalkChatbot(self.access_url, self.secret)

        bot.send_text('dingtalkchatbot 发送消息', at_mobiles=['xxxxxxxx'])
        bot.send_text('dingtalkchatbot 发送消息给所有人', is_at_all=True)

    def ding_talk_img(self):
        from dingtalkchatbot.chatbot import DingtalkChatbot
        bot = DingtalkChatbot(self.access_url, self.secret)

        bot.send_image(
            pic_url='https://p.qqan.com/up/2024-5/17150658853540006.jpg')

    def ding_talk_link(self):
        from dingtalkchatbot.chatbot import DingtalkChatbot
        bot = DingtalkChatbot(self.access_url, self.secret)

        bot.send_link(title="Python", text="测试", message_url='https://www.baidu.com',
                      pic_url='https://p.qqan.com/up/2024-5/17150658853540006.jpg')

    def ding_talk_md(self):
        from dingtalkchatbot.chatbot import DingtalkChatbot
        bot = DingtalkChatbot(self.access_url, self.secret)

        bot.send_markdown(title="Python Markdown",
                          text="> ### MarkDown 测试"
                          '内容: xxxxxxxxxxxxx'
                          '![Python](https://p.qqan.com/up/2024-5/17150658853540006.jpg)')

    def ding_talk_card(self):
        from dingtalkchatbot.chatbot import DingtalkChatbot, CardItem
        bot = DingtalkChatbot(self.access_url, self.secret)
        card1 = CardItem(title="猫猫", url="https://www.baidu.com",
                         pic_url="https://p.qqan.com/up/2024-5/17150658853540006.jpg")
        card2 = CardItem(title="猫猫", url="https://www.baidu.com",
                         pic_url="https://p.qqan.com/up/2024-5/17150658853540006.jpg")
        card3 = CardItem(title="猫猫", url="https://www.baidu.com",
                         pic_url="https://p.qqan.com/up/2024-5/17150658853540006.jpg")
        cards = [card1, card2, card3]
        bot.send_feed_card(cards)

    def ding_talk_action_card(self):
        from dingtalkchatbot.chatbot import DingtalkChatbot, CardItem, ActionCard
        bot = DingtalkChatbot(self.access_url, self.secret)

        # Link消息
        # ActionCard整体跳转消息类型
        btns1 = [CardItem(title="猫猫", url="https://www.baidu.com")]
        actioncard1 = ActionCard(title="震惊!竟然。。。",
                                 text='![选择](https://p.qqan.com/up/2024-5/17150658853540006.jpg) \n ### 这猫好白!',
                                 btns=btns1,
                                 btn_orientation=1,
                                 hide_avatar=1
                                 )

        bot.send_action_card(actioncard1)

    def ding_talk_action_card2(self):
        from dingtalkchatbot.chatbot import DingtalkChatbot, CardItem, ActionCard
        bot = DingtalkChatbot(self.access_url, self.secret)

        # Link消息
        # ActionCard整体跳转消息类型多选项
        btns2 = [CardItem(title="猫猫", url="https://www.tmall.com"), CardItem(title="狗狗", url="https://www.jd.com")]
        actioncard2 = ActionCard(title="震惊!竟然。。。",
                                 text='![选择](https://pic.rmb.bdstatic.com/bjh/487c0d7dba3e735aee35ebedde1e37b8.jpeg) \n ### 这狗好白!',
                                 btns=btns2,
                                 btn_orientation=0,
                                 hide_avatar=0
                                 )

        bot.send_action_card(actioncard2)

if __name__ == '__main__':
    ding = DingTalk_Base()
    # ding.get_bot_url()
    # print(ding.send_msg("This is Python message"))   # b'{"errcode":0,"errmsg":"ok"}'
    # ding.curl_msg()
    # ding.ding_talk()
    # ding.ding_talk_img()
    # ding.ding_talk_link()
    # ding.ding_talk_md()
    # ding.ding_talk_card()
    # ding.ding_talk_action_card()
    ding.ding_talk_action_card2()