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 相关文章推荐
如何高效使用Python字典的方法详解
Aug 31 Python
Python实现在tkinter中使用matplotlib绘制图形的方法示例
Jan 18 Python
浅析python协程相关概念
Jan 20 Python
浅析python3中的os.path.dirname(__file__)的使用
Aug 30 Python
python3 unicode列表转换为中文的实例
Oct 26 Python
Python设计模式之备忘录模式原理与用法详解
Jan 15 Python
Python 微信爬虫完整实例【单线程与多线程】
Jul 06 Python
django多个APP的urls设置方法(views重复问题解决)
Jul 19 Python
如何利用python给图片添加半透明水印
Sep 06 Python
python 实现视频 图像帧提取
Dec 10 Python
python 爬虫如何正确的使用cookie
Oct 27 Python
python 利用 PIL 将数组值转成图片的实现
Apr 12 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
PHP 超链接 抓取实现代码
2009/06/29 PHP
一步一步学习PHP(2)――PHP类型
2010/02/15 PHP
PHP 编写大型网站问题集
2010/05/07 PHP
PHP 简易输出CSV表格文件的方法详解
2013/06/20 PHP
解析php中eclipse 用空格替换 tab键
2013/06/24 PHP
php中实现记住密码下次自动登录的例子
2014/11/06 PHP
PHP 9 大缓存技术总结
2015/09/17 PHP
Yii2.0中使用js异步删除示例
2017/03/10 PHP
Laravel5.* 打印出执行的sql语句的方法
2017/07/24 PHP
判断多个元素(RADIO,CHECKBOX等)是否被选择的原理说明
2009/02/18 Javascript
JS关闭窗口或JS关闭页面的几种代码分享
2013/10/25 Javascript
利用js实现前台动态添加文本框,后台获取文本框内容(示例代码)
2013/11/25 Javascript
AngularJS基础 ng-keydown 指令简单示例
2016/08/02 Javascript
Vue.js每天必学之过渡与动画
2016/09/06 Javascript
AngularJs ng-repeat 嵌套如何获取外层$index
2016/09/21 Javascript
Nodejs 复制文件/文件夹的方法
2017/08/24 NodeJs
如何让你的JS代码更好看易读
2017/12/01 Javascript
vue使用vue-i18n实现国际化的实现代码
2018/04/08 Javascript
JQuery实现简单的复选框树形结构图示例【附源码下载】
2019/07/16 jQuery
NodeJs实现简易WEB上传下载服务器
2019/08/10 NodeJs
Python multiprocessing多进程原理与应用示例
2019/02/28 Python
python3 中的字符串(单引号、双引号、三引号)以及字符串与数字的运算
2019/07/18 Python
使用APScheduler3.0.1 实现定时任务的方法
2019/07/22 Python
python requests使用socks5的例子
2019/07/25 Python
python tkinter实现屏保程序
2019/07/30 Python
python实现身份证实名认证的方法实例
2019/11/08 Python
Django实现图片上传功能步骤解析
2020/04/22 Python
Python datetime模块使用方法小结
2020/06/18 Python
解决tensorflow/keras时出现数组维度不匹配问题
2020/06/29 Python
以色列的身体护理及家居香薰品牌:Sabon NYC
2018/02/23 全球购物
FORZIERI福喜利中国官网:奢侈品购物梦工厂
2019/05/03 全球购物
在C++ 程序中调用被C 编译器编译后的函数,为什么要加extern "C"
2014/08/09 面试题
党员干部作风建设思想汇报范文
2014/10/25 职场文书
学子宴致辞大全
2015/07/27 职场文书
MySQL 逻辑备份与恢复测试的相关总结
2021/05/14 MySQL
正则表达式基础与常用验证表达式
2022/06/16 Javascript