In a fit of anger, he developed a group chat robot

Reading assistant

Author introduction: currently working as an e-commerce data analyst, his daily work focuses on crawler and DBA database management, supplemented by business scenario model building! He has been engaged in data related work since 16 years, and has been growing from his original cousin to big data, data mining and machine learning! Daily active in CSDN

Solgan: Science and technology make the future of business, and data can see through the essence of the problem CSDN: https://blog.csdn.net/qq_35866846 WeChat official account: a tricky journey

Project background

Recently, you need to send an excel sheet to your colleagues, which will be provided by others and placed on the shared disk. Because your colleagues work in Party B, the external network cannot access the internal network shared disk, so you need to update and send it once a day. I have to say that laziness is the primary productivity. Doing such mechanical operation every day is an insult to the code, so I'm angry to study the robot in enterprise wechat!

Achievement display

As shown in the figure, perfect execution, plus a scheduled task, you can send it regularly every day

Project disassembly

1. Add robot

Note here that during the test

  • Only internal groups can add robots, while external groups cannot
  • Multiple robots can be added,
  • You can also add a robot to multiple groups, and each group can receive the message sent by the robot

2. Robot code

Official API address reference

The only annoyance is that the official case is written by curl tool, and I write python However, the principle of code is basically the same (install it), but this similarity still exists. This simple sentence can be realized by yourself

Directly to the code, the explanation is written in the comments of the code block

import requests, json
import datetime
import time
wx_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key = [your own robot key]“
send_message = "Test: test robot No. 1!"
def get_current_time():
    """Get the current time, current hour, minute and second"""
    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")
    return now_time, hour, mm, ss
def sleep_time(hour, m, sec):
    """Returns the total number of seconds"""
    return hour * 3600 + m * 60 + sec

def send_msg(content):
    """Aite all and send the specified information"""
    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(interval_h=0, interval_m=1, interval_s=0, special_h="00", special_m="00", mode="special"):
    """Send the specified message at the specified time every day"""
    # Set automatic execution interval
    second = sleep_time(interval_h, interval_m, interval_s)
    # Dead cycle
    while True:
        # Gets the current time and the current hour, minute and second
        c_now, c_h, c_m, c_s = get_current_time()
        print("Current time:", c_now, c_h, c_m, c_s)
        if mode == "special":
            if c_h == special_h and c_m == special_m:
                # implement
                print("Sending...")
                send_msg(send_message)
        else:
            send_msg(send_message)
    print("every other" + str(interval_h) + "hour" + str(interval_m) + "branch" + str(interval_s) + "Once per second")
    # delayed
    time.sleep(second)
if __name__ == '__main__':
    every_time_send_msg(mode="no")

# File push test
def wx_post(file):
    # Upload file interface address
    id_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key = [your own robot key] & type = file '  
    # open read the file and get the wearing json    
    data = {'file': open(file, 'rb')}  # post jason
    # post request upload file
    response = requests.post(url=id_url, files=data)  
    json_res = response.json()  # Return to json
    media_id = json_res['media_id']  # Extract return ID
    wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key = [your own robot key] '# sending message interface address
    data = {"msgtype": "file", "file": {"media_id": media_id}}  # post json
    r = requests.post(url=wx_url, json=data)  # post request message
    return r  # Return request status
# Local file test
wx_post("test.xlsx")

# Test shared files
sharePath = '\\\\Intranet IP address\\xxx\\Checklist 2021.03.05.xlsx'
wx_post(sharePath)

3. Set time task

Set a scheduled task and execute it every day

Science and technology make the future of business, and data can see through the essence of the problem! I am a tricky way. Thank you for reading. Welcome to forward and share some likes! The article is only for learning and exchange. Please indicate the source of reprint!

Added by bhinkel on Fri, 07 Jan 2022 03:41:56 +0200