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 相关文章推荐
wxPython 入门教程
Oct 07 Python
Python中条件选择和循环语句使用方法介绍
Mar 13 Python
Python实现大文件排序的方法
Jul 10 Python
浅析Python的web.py框架中url的设定方法
Jul 11 Python
Django 拆分model和view的实现方法
Aug 16 Python
详解python中的模块及包导入
Aug 30 Python
python用quad、dblquad实现一维二维积分的实例详解
Nov 20 Python
Python3 中作为一等对象的函数解析
Dec 11 Python
运行tensorflow python程序,限制对GPU和CPU的占用操作
Feb 06 Python
使用Python Tkinter实现剪刀石头布小游戏功能
Oct 23 Python
如何用python写个模板引擎
Jan 14 Python
python 如何将两个实数矩阵合并为一个复数矩阵
May 19 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的FTP学习(一)
2006/10/09 PHP
PHP 杂谈《重构-改善既有代码的设计》之四 简化条件表达式
2012/04/09 PHP
深入PHP许愿墙模块功能分析
2013/06/25 PHP
PHP会话控制实例分析
2016/12/24 PHP
php实现图片按比例截取的方法
2017/02/06 PHP
XAMPP升级PHP版本实现步骤解析
2020/09/04 PHP
JavaScript 函数调用规则
2009/09/14 Javascript
php与js的区别是什么
2013/08/05 Javascript
js动态设置div的值下例子
2013/10/29 Javascript
javascript中递归的两种写法
2017/01/17 Javascript
Vue.js 2.0窥探之Virtual DOM到底是什么?
2017/02/10 Javascript
Vue中使用vux的配置详解
2017/05/05 Javascript
vue v-on监听事件详解
2017/05/17 Javascript
Vue-router路由判断页面未登录跳转到登录页面的实例
2017/10/26 Javascript
nodejs实现大文件(在线视频)的读取
2020/10/16 NodeJs
解决Vue打包之后文件路径出错的问题
2018/03/06 Javascript
Angular5升级RxJS到5.5.3报错:EmptyError: no elements in sequence的解决方法
2018/04/09 Javascript
vue-quill-editor+plupload富文本编辑器实例详解
2018/10/19 Javascript
vue-router的两种模式的区别
2019/05/30 Javascript
[00:55]2015国际邀请赛中国区预选赛5月23日——28日约战上海
2015/05/25 DOTA
[02:29]大剑、皮鞭、女装,这届DOTA2勇士令状里都有
2020/07/17 DOTA
python实现读取excel写入mysql的小工具详解
2017/11/20 Python
python编程测试电脑开启最大线程数实例代码
2018/02/09 Python
基于Django ORM、一对一、一对多、多对多的全面讲解
2019/07/26 Python
python selenium实现发送带附件的邮件代码实例
2019/12/10 Python
python实现手势识别的示例(入门)
2020/04/15 Python
Python的scikit-image模块实例讲解
2020/12/30 Python
工程造价专业大专生求职信
2013/10/06 职场文书
小学运动会入场式解说词
2014/02/18 职场文书
产品质量承诺书
2014/03/27 职场文书
整顿机关作风心得体会
2014/09/10 职场文书
党政领导班子群众路线对照检查材料
2014/10/26 职场文书
检讨书范文
2015/01/27 职场文书
搞笑欢迎词大全
2015/09/30 职场文书
anaconda python3.8安装后降级
2021/06/11 Python
Java Optional<Foo>转换成List<Bar>的实例方法
2021/06/20 Java/Android