Python第三方包之DingDingBot钉钉机器人


Posted in Python onApril 09, 2020

这个是作者自己封装的一个钉钉机器人的包,目前只支持发文本格式、链接格式、markdown格式的消息,我们可以在很多场景用到这个,比如告警通知等

安装

pip install DingDingBot

使用方法

from DingDingBot.DDBOT import DingDing
# 初始话DingDingBOt webhook是钉钉机器人所必须的
dd = DingDing(webhook='https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxx')
# 发送文本消息
print(dd.Send_Text_Msg(Content='test:测试数据'))
# 发送链接消息
print(dd.Send_Link_Msg(Content='test',Title='测试数据',MsgUrl='https://www.baidu.com',PicUrl='https://cn.bing.com/images/search?q=outgoing%e6%9c%ba%e5%99%a8%e4%ba%ba&id=FEE700371845D9386738AAAA51DCC43DC54911AA&FORM=IQFRBA'))
# 发送Markdown格式的消息
print(dd.Send_MardDown_Msg(Content="# 测试数据\n" + "> testone", Title='测试数据'))

源码

#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''
  @@@@@@@@   @@@@@@@@@   @@@@@@@@@  @@@@@@@@@   @@@@@@@@@@@@
  @@   @@  @@   @@  @@   @@  @@   @@     @@
  @@    @@ @@    @@  @@  @@  @@    @@    @@
  @@    @@ @@    @@  @@  @@   @@    @@    @@
  @@    @@ @@    @@  @@ @@   @@    @@    @@
  @@   @@  @@   @@  @@ @@    @@    @@    @@
  @@   @@  @@   @@   @@ @@   @@    @@    @@
  @@  @@   @@  @@   @@  @@   @@    @@    @@
  @@  @@   @@  @@    @@ @@    @@   @@     @@
  @@ @@    @@ @@     @@      @@@@@@@@@     @@

'''

import requests, json


class DingDing():
  """
  # 钉钉官方文档
  Refer to official documentation: https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
  """
  # 初始化
  def __init__(self, webhook):
    self.webhook = webhook
    self.session = requests.session()
    self.session.headers = {"Content-Type": "application/json;charset=utf-8"}

  def Send_Text_Msg(self, Content: str, atMobiles: list = [], isAtAll: bool = False) -> dict:
    """
    :param content: 要发送的内容
    :param atMobiles: @指定的人,这里必须是列表,且参数为手机号
    :param isAtAll: @全体成员
    :return:
    """
    try:
      data = {
        "msgtype": "text",
        "text": {
          "content": Content
        },
        "at": {
          "atMobiles": atMobiles,
          "isAtAll": isAtAll
        }
      }
      response = self.session.post(self.webhook, data=json.dumps(data))
      if response.status_code == '200':
        result = {"status": True, "message": "Message has been sent"}
        return result
      else:
        return response.text
    except Exception as error:
      result = {"status": False, "message": f"Failed to send message,Error stack:{error}"}
      return result

  def Send_Link_Msg(self, Content: str, Title: str, MsgUrl: str, PicUrl: str = ''):
    """
    :param Content: 链接的内容
    :param title: 链接的标题
    :param MsgUrl: 待跳转页面的url
    :param PicUrl: 消息所展示的图片
    :return:
    """
    try:
      data = {
        "msgtype": "link",
        "link": {
          "text": Content,
          "title": Title,
          "picUrl": PicUrl,
          "messageUrl": MsgUrl
        }
      }
      response = self.session.post(self.webhook, data=json.dumps(data))
      if response.status_code == '200':
        result = {"status": True, "message": "Message has been sent"}
        return result
      else:
        return response.text
    except Exception as error:
      result = {"status": False, "message": f"Failed to send message,Error stack:{error}"}
      return result

  def Send_MardDown_Msg(self, Content: str, Title: str, atMobiles: list = [], isAtAll: bool = False):
    """
    :param Content: Markdown格式的文本,仅支持下面的格式
    '''
    标题
      # 一级标题
      ## 二级标题
      ### 三级标题
      #### 四级标题
      ##### 五级标题
      ###### 六级标题

      引用
      > A man who stands for nothing will fall for anything.

      文字加粗、斜体
      **bold**
      *italic*

      链接
      [this is a link](http://name.com)

      图片
      ![](http://name.com/pic.jpg)

      无序列表
      - item1
      - item2

      有序列表
      1. item1
      2. item2
    '''
    :param Title: 这个Markdown的标题
    :param atMobiles: @指定的人,这里必须是列表,且参数为手机号
    :param isAtAll: @全体成员
    :return:
    """
    try:
      data = {
        "msgtype": "markdown",
        "markdown": {
          "title": Title,
          "text": Content
        },
        "at": {
          "atMobiles": atMobiles,
          "isAtAll": isAtAll
        }
      }
      response = self.session.post(self.webhook, data=json.dumps(data))
      if response.status_code == '200':
        result = {"status": True, "message": "Message has been sent"}
        return result
      else:
        return response.text
    except Exception as error:
      result = {"status": False, "message": f"Failed to send message,Error stack:{error}"}
      return result

到此这篇关于Python第三方包之DingDingBot钉钉机器人的文章就介绍到这了,更多相关Python DingDingBot内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Django框架下在URLconf中指定视图缓存的方法
Jul 23 Python
Python实现字典依据value排序
Feb 24 Python
Django 添加静态文件的两种实现方法(必看篇)
Jul 14 Python
python处理数据,存进hive表的方法
Jul 04 Python
Python中 map()函数的用法详解
Jul 10 Python
python 数字类型和字符串类型的相互转换实例
Jul 17 Python
python实现三次样条插值
Dec 17 Python
python pandas时序处理相关功能详解
Jul 03 Python
Python学习笔记之字符串和字符串方法实例详解
Aug 22 Python
wxpython绘制音频效果
Nov 18 Python
django在保存图像的同时压缩图像示例代码详解
Feb 11 Python
python爬虫之selenium库的安装及使用教程
May 23 Python
python实现简单学生信息管理系统
Apr 09 #Python
Pycharm pyuic5实现将ui文件转为py文件,让UI界面成功显示
Apr 08 #Python
pycharm的python_stubs问题
Apr 08 #Python
Pycharm中安装Pygal并使用Pygal模拟掷骰子(推荐)
Apr 08 #Python
解决pycharm下pyuic工具使用的问题
Apr 08 #Python
解决pyqt5异常退出无提示信息的问题
Apr 08 #Python
python由已知数组快速生成新数组的方法
Apr 08 #Python
You might like
某大型网络公司应聘时的笔试题目附答案
2008/03/27 PHP
浅谈php serialize()与unserialize()的用法
2013/06/05 PHP
php的sso单点登录实现方法
2015/01/08 PHP
Yii2.0实现的批量更新及批量插入功能示例
2019/01/29 PHP
解决遍历时Array.indexOf产生的性能问题
2012/07/03 Javascript
hover的用法及live的用法介绍(鼠标悬停效果)
2013/03/29 Javascript
JS判断网页广告是否被浏览器拦截过滤的代码
2015/04/05 Javascript
JavaScript创建对象的方式小结(4种方式)
2015/12/17 Javascript
JavaScript中字符串与Unicode编码互相转换的实现方法
2015/12/18 Javascript
Javascript之String对象详解
2016/06/08 Javascript
bootstrap select插件封装成Vue2.0组件
2017/04/17 Javascript
Vue+axios 实现http拦截及路由拦截实例
2017/04/25 Javascript
vue父子组件的嵌套的示例代码
2017/09/08 Javascript
AngularJS双向数据绑定原理之$watch、$apply和$digest的应用
2018/01/30 Javascript
解决vue中post方式提交数据后台无法接收的问题
2018/08/11 Javascript
vue项目引入Iconfont图标库的教程图解
2018/10/24 Javascript
详解如何为你的angular app构建一个第三方库
2018/12/07 Javascript
详解jQuery-each()方法
2019/03/13 jQuery
vue-cli4.0多环境配置变量与模式详解
2020/12/30 Vue.js
实例探究Python以并发方式编写高性能端口扫描器的方法
2016/06/14 Python
详解Python3除法之真除法、截断除法和下取整对比
2019/05/23 Python
python实现月食效果实例代码
2019/06/18 Python
python GUI库图形界面开发之PyQt5拖放控件实例详解
2020/02/25 Python
如何使用python的ctypes调用医保中心的dll动态库下载医保中心的账单
2020/05/24 Python
使用tensorflow实现VGG网络,训练mnist数据集方式
2020/05/26 Python
Why we need EJB
2016/10/20 面试题
大学生最常用的自我评价
2013/12/07 职场文书
《哪吒闹海》教学反思
2014/02/28 职场文书
开工仪式主持词
2014/03/20 职场文书
竞争与合作演讲稿
2014/05/12 职场文书
2014年客户经理工作总结
2014/11/20 职场文书
小学新教师个人总结
2015/02/05 职场文书
2015年街道除四害工作总结
2015/05/15 职场文书
趣味运动会新闻稿
2015/07/17 职场文书
创业计划书之冷饮店
2019/09/27 职场文书
面试中老生常谈的MySQL问答集锦夯实基础
2022/03/13 MySQL