前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python - 接入钉钉机器人

Python - 接入钉钉机器人

作者头像
小菠萝测试笔记
发布2021-11-18 14:50:20
8130
发布2021-11-18 14:50:20
举报

背景

想将 Python 爬下来的内容通知到钉钉

钉钉群聊机器人概述

  • 所谓群聊机器人,指可以在群内使用的机器人,目前主要为 webhook 机器人和企业自建机器人两大类,另外通过场景群模板的方式,也可以预先配置好机器人并通过启用模板的方式安装到群内
  • 如图所示,群主和群管理员,可以通过群助手的设置页,启用webhook机器人和企业自建机器人,或者在插件更多页面,通过启用群模板的方案,来启用群机器人

群机器人适用于以下场景:

  • 项目协同交
  • 互式服务

添加机器人到钉钉群

https://developers.dingtalk.com/document/robots/use-group-robots

自定义机器人安全设置

目前机器人一定要有安全设置,如果用 Python 脚本的话,推荐用加签方式

https://developers.dingtalk.com/document/robots/customize-robot-security-settings

一个小栗子

抓取网上 iphone13 的供货情况然后通过钉钉机器人通知我

import requests


# 获取手机供货信息
def get_phone():
    res = requests.get(
        "https://www.apple.com.cn/shop/fulfillment-messages?pl=true&parts.0=MLTE3CH/A&location=%E5%B9%BF%E4%B8%9C%20%E5%B9%BF%E5%B7%9E%20%E5%A4%A9%E6%B2%B3%E5%8C%BA",
        verify=False)
    res = res.json()["body"]["content"]["pickupMessage"]["stores"]

    for num, item in enumerate(res):
        phone = item["partsAvailability"]["MLTE3CH/A"]

        storeSelectionEnabled = phone["storeSelectionEnabled"]
        storePickupQuote = phone["storePickupQuote"]
        pickupSearchQuote = phone["pickupSearchQuote"]

        if storeSelectionEnabled:
            res = {
                "可取货": storeSelectionEnabled,
                "取货状态": storePickupQuote,
                "供应状态": pickupSearchQuote
            }
            yield res


# python 3.8
import time
import hmac
import hashlib
import base64
import urllib.parse

# 加签
timestamp = str(round(time.time() * 1000))
secret = '此处填写 webhook token'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(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()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))


def dingmessage():
    # 请求的URL,WebHook地址
    webhook = f"https://oapi.dingtalk.com/robot/send?access_token={token}&timestamp={timestamp}&sign={sign}"

    # 构建请求头部
    header = {"Content-Type": "application/json", "Charset": "UTF-8"}

    # 循环生成器并发送消息
    for phone in get_phone():
        message = {
            "msgtype": "text",
            "text": {"content": phone},
            "at": {
                # @ 所有人
                "isAtAll": True
            }
        }
        message_json = json.dumps(message)
        info = requests.post(url=webhook, data=message_json, headers=header, verify=False)  # 打印返回的结果
        print(info.text)


if __name__ == "__main__":
    dingmessage()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-11-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 背景
  • 钉钉群聊机器人概述
  • 添加机器人到钉钉群
  • 自定义机器人安全设置
  • 一个小栗子
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档