Dingding Operators

先决条件任务

要使用这些 operators,您必须做几件事
  • 在您想要发送消息的聊天群中添加自定义机器人。

  • 获取 钉钉自定义机器人 webhook token

  • 将访问令牌放入 dingding_default Connection 的 password 字段中。注意:您只需要令牌值而不是完整的 webhook 字符串。

基本用法

使用 DingdingOperator 通过 钉钉自定义机器人 发送消息

tests/system/dingding/example_dingding.py

text_msg_remind_none = DingdingOperator(
    task_id="text_msg_remind_none",
    message_type="text",
    message="Airflow dingding text message remind none",
    at_mobiles=None,
    at_all=False,
)

在消息中提醒用户

使用参数 at_mobilesat_all 在发送消息时提醒特定用户,当 at_all 设置为 True 时,at_mobiles 将被忽略。

tests/system/dingding/example_dingding.py

text_msg_remind_all = DingdingOperator(
    task_id="text_msg_remind_all",
    message_type="text",
    message="Airflow dingding text message remind all users in group",
    # list of user phone/email here in the group
    # when at_all is specific will cover at_mobiles
    at_mobiles=["156XXXXXXXX", "130XXXXXXXX"],
    at_all=True,
)

发送富文本消息

DingdingOperator 可以通过 钉钉自定义机器人 发送富文本消息,包括链接、Markdown、actionCard 和 feedCard。富文本消息无法提醒特定用户,除非使用 Markdown 类型的消息。

tests/system/dingding/example_dingding.py

markdown_msg = DingdingOperator(
    task_id="markdown_msg",
    message_type="markdown",
    message={
        "title": "Airflow dingding markdown message",
        "text": "# Markdown message title\n"
        "content content .. \n"
        "### sub-title\n"
        "![logo](https://airflow.org.cn/_images/pin_large.png)",
    },
    at_mobiles=["156XXXXXXXX"],
    at_all=False,
)

从任务回调函数发送消息

DingdingHook 可以通过编写回调函数并将其传递给 sla_miss_callbackon_success_callbackon_failure_callbackon_retry_callback 来处理任务回调。这里我们以 on_failure_callback 为例。

tests/system/dingding/example_dingding.py

def failure_callback(context):
    """
    The function that will be executed on failure.

    :param context: The context of the executed task.
    """
    message = f"The task {context['ti'].task_id} failed"
    DingdingHook(message_type="text", message=message, at_all=True).send()


如果需要,更改连接主机

DingdingOperator 使用默认主机 https://oapi.dingtalk.com 发送 HTTP 请求,如果需要更改使用的主机,可以在连接的 host 字段中进行设置。

此条目是否有帮助?