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爬取读者并制作成PDF
Mar 10 Python
Python的Django框架中设置日期和字段可选的方法
Jul 17 Python
python实现简单聊天应用 python群聊和点对点均实现
Sep 14 Python
python kmeans聚类简单介绍和实现代码
Feb 23 Python
利用Pandas 创建空的DataFrame方法
Apr 08 Python
从DataFrame中提取出Series或DataFrame对象的方法
Nov 10 Python
不到20行代码用Python做一个智能聊天机器人
Apr 19 Python
使用apiDoc实现python接口文档编写
Nov 19 Python
python 实现仿微信聊天时间格式化显示的代码
Apr 17 Python
浅析python 动态库m.so.1.0错误问题
May 09 Python
如何利用Python识别图片中的文字
May 31 Python
Pygame Draw绘图函数的具体使用
Nov 17 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实现二维数组按某列进行排序的方法
2016/11/18 PHP
thinkPHP5项目中实现QQ第三方登录功能
2017/10/20 PHP
php swoft框架实例用法
2020/12/22 PHP
分页栏的web标准实现
2011/11/01 Javascript
JS保留两位小数,多位小数的示例代码
2014/01/07 Javascript
IntersectionObserver API 详解篇
2016/12/11 Javascript
Javascript网页抢红包外挂实现分享
2018/01/11 Javascript
JS实现的集合去重,交集,并集,差集功能示例
2018/03/13 Javascript
JavaScript对象的浅拷贝与深拷贝实例分析
2018/07/25 Javascript
5分钟快速掌握JS中var、let和const的异同
2018/09/19 Javascript
jQuery操作动画完整实例分析
2020/01/10 jQuery
JS的时间格式化和时间戳转换函数示例详解
2020/07/27 Javascript
基于Vue.js+Nuxt开发自定义弹出层组件
2020/10/09 Javascript
[01:15:15]VG VS EG Supermajor小组赛B组胜者组第一轮 BO3第二场 6.2
2018/06/03 DOTA
linux系统使用python获取内存使用信息脚本分享
2014/01/15 Python
Python实现删除文件但保留指定文件
2015/06/21 Python
使用python和pygame绘制繁花曲线的方法
2018/02/24 Python
通过Pandas读取大文件的实例
2018/06/07 Python
Python进程间通信multiprocess代码实例
2020/03/18 Python
spyder 在控制台(console)执行python文件,debug python程序方式
2020/04/20 Python
Python切片列表字符串如何实现切换
2020/08/06 Python
如何在python中实现线性回归
2020/08/10 Python
Python利用socket模块开发简单的端口扫描工具的实现
2021/01/27 Python
html5实现canvas阴影效果示例
2014/05/07 HTML / CSS
英国高档时尚男装购物网站:MR PORTER
2016/08/09 全球购物
联想美国官方商城:Lenovo美国
2017/06/19 全球购物
REN Clean Skincare官网:英国本土有机护肤品牌
2019/02/23 全球购物
一份软件工程师的面试试题
2016/02/01 面试题
高中生物教学反思
2014/02/05 职场文书
班组长岗位职责
2014/03/03 职场文书
体现团队精神的口号
2014/06/06 职场文书
企业法人代表证明书
2014/09/27 职场文书
家庭财产分割协议范文
2014/11/24 职场文书
不同意离婚代理词
2015/05/23 职场文书
网络营销实训总结
2015/08/03 职场文书
学校体育节班级口号
2015/12/25 职场文书