首页 > 编程语言 >python实现企业微信机器人自动发消息

python实现企业微信机器人自动发消息

时间:2022-09-02 17:33:51浏览次数:63  
标签:__ work python 微信 self base64 send data 发消息

一)创建企业微信群机器人

1)先创建一个测试用临时对话群

操作步骤:先在手机端打开企业微信,点击右上角+按钮 -> 发起群聊 -> 联系人中选择2人点击确定,即可创建一个临时对话群

2)点击群对话右上角3个点“...”打开菜单 -> 在群机器人这里点击右侧“未添加” -> 添加机器人 -> 点击右上角“添加”

 

3)对新加的机器人进行姓名编辑 -> 点击确定,机器人添加成功。Webhook地址点击复制,保存

二)python脚本实现机器人自动发送消息

 1)python脚本实现机器人发送文本消息

import requests,base64,hashlib

class WXWork_SMS:
    def __init__(self):
        self.headers = {"Content-Type": "text/html"}
        self.send_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxx"  # 测试机器人webhook地址
        self.auth = ('Content-Type', 'application/json')


    def send_requests(self,send_data):
        res = requests.post(url=self.send_url, headers=self.headers, json=send_data, auth=self.auth)
        print(res.json())
        
    def send_msg(self):
        # 发送消息
        send_data = {
            "msgtype": "text",  # 消息类型,此时固定为news
            "text": {
                "content": '测试消息',
                "mentioned_list":  ["@all"]
            }
        }
        self.send_requests(send_data)
if __name__ == '__main__':
    sms = WXWork_SMS()
   sms.send_msg()

2)python脚本实现机器人发送本地图片

    def img_md5(self):
        #将本地图片转换为base64编码和md5值
        pic=r"F:\img\img.png"
        with open(pic,'rb')as f:
            image=f.read()
            image_base64=str(base64.b64encode(image),encoding='utf-8')
            my_md5=hashlib.md5()
            img_data=base64.b64decode(image_base64)
            my_md5.update(img_data)
            myhash=my_md5.hexdigest()
        return image_base64,myhash

    def send_img(self,image_base64,myhash):
        # 发送图片
        send_data = {
            "msgtype": "image",  # 消息类型,此时固定为news
            "image": {
                "base64": image_base64,
                "md5":myhash
            }
        }
        self.send_requests(send_data)

if __name__ == '__main__':
    sms = WXWork_SMS()
    image_base64,myhash=sms.img_md5()
    sms.send_img(image_base64,myhash)

3)python脚本实现机器人发送图文消息

    def send_news(self):
        # 图文类型消息
        send_data = {
            "msgtype": "news",  # 消息类型,此时固定为news
            "news": {
                "articles": [  # 图文消息,一个图文消息支持1到8条图文
                    {
                        "title": "下班啦",  # 标题,不超过128个字节,超过会自动截断
                        "description": "准备下班了,记得打卡~",  # 描述,不超过512个字节,超过会自动截断
                        "url": "www.baidu.com",  # 点击后跳转的链接。
                        "picurl": "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png"
                        # 图文消息的图片链接,支持JPG、PNG格式,较好的效果为大图 1068*455,小图150*150。
                    }

                ]
            }
        }
        self.send_requests(send_data)
if __name__ == '__main__':
    sms = WXWork_SMS()
    sms.send_news()

4)定时发送消息

import requests
import json
import datetime
import time

wx_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxx"  # 测试机器人webhook
send_message1 = "测试消息1"
send_message2="测试消息2"
send_message3='测试消息3'
send_message4 = "测试消息4"

def get_current_time():
    """获取当前时间,当前时分秒"""
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    hour = datetime.datetime.now().strftime("%H")
    mm = datetime.datetime.now().strftime("%M")
    ss = datetime.datetime.now().strftime("%S")
    today = datetime.datetime.now().date()
    is_work = today.isoweekday()
    print(now_time)
    print(is_work)
    return now_time, hour, mm, ss,is_work

def sleep_time(hour, m, sec):
    return hour * 3600 + m * 60 + sec

def send_msg(content):
    data = json.dumps({"msgtype": "text", "text": {"content": content, "mentioned_list": ["@all"]}})
    r = requests.post(wx_url, data, auth=('Content-Type', 'application/json'))
    print(r.json())

def every_time_send_msg(h1='16', m1='00',h2='11', m2='00',h3='18', m3='00',h4='10', m4='05',mode="game"):
    # 死循环

    while True:
        if  mode == "game" :
            # 获取当前时间和当前时分秒
            c_now, c_h, c_m, c_s,work_day = get_current_time()
            if work_day in range (1,7) and c_h == h1 and c_m == m1:
                print(work_day)
                send_msg(send_message1)
            elif work_day in range (1,7) and c_h == h3 and c_m == m3:
                print(work_day)
                send_msg(send_message3)
            elif work_day in range (1,7) and c_h == h4 and c_m == m4:
                print(work_day)
                send_msg(send_message4)
            elif work_day==5 and c_h == h2 and c_m == m2:
                print(work_day==5)
                send_msg(send_message2)
            time.sleep(60)

if __name__ == '__main__':
    every_time_send_msg(mode="game")

 

标签:__,work,python,微信,self,base64,send,data,发消息
From: https://www.cnblogs.com/muxiaomu/p/16650603.html

相关文章

  • Python之DataFrame基础知识点
    https://blog.csdn.net/u012856866/article/details/118936961?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166210446116782391824184%2522%252C%2522scm%2......
  • Python源码学习-Objects类型
    目录简介类型定义类型对象对象操作缓存池本文基于Python3.10.4。简介在python中,有两种类型可以保存bytes(字节)类型的数据。分别是bytes与bytearray。其中bytearray支持修......
  • python采集财经数据信息并作可视化~
    前言......
  • Python
    Python测试开发实战Python编程基础蚂蚁金服:Java阿里集团:Java,Python腾讯云:Python字节:python,go,phppycharm快捷指令ctrl+alt+s:打开软件设置ctrl+d:复制当前......
  • centos 安装python3
    centos编译安装python3.71.安装依赖,下载python3.7#1、yum更新yum源yumupdate#2、安装Python3.7所需的依赖否则安装后没有pip3包yuminstallzlib-develbzip2-develo......
  • ubuntu 升级python3
    #下载到home中wgethttps://www.python.org/ftp/python/3.9.0/Python-3.9.0.tgz#在home中解压tar-zxfPython-3.9.0.tgz#进入python3.9cdPython-3.9.0./config......
  • python的常用方法和模块
    1.str类下的方法Pythonzfill()方法返回指定长度的字符串,原字符串右对齐,前面填充0......
  • 微信小程序元素超出页面宽度的解决
    有时候可能会出现这种情况,如下图底部的添加店铺的按钮超出页面宽度了,直接在给按钮外面的盒子加一个css样式:box-sizing:border-box; 这样就正常显示了 ......
  • Python万能参数(*args, **kwargs)
    Python万能参数(*args,**kwargs)Python内置一颗这样的语法糖,它允许函数声明时以(args,**kwargs)声明它的参数,而(args,**kwargs)可以接受任何类型的参数。动态传参*ar......
  • 学习:python进阶 属性查找顺序,隐藏属性,开放接口
          隐藏属性    开放接口 ......