通过python实现企业微信通知及短信通知

接到需求,获取每日的公网IP,并通过企业微信自建应用发送每天的IP地址(企业微信自建应用有一个坑,必须要添加信任可用IP才可以发送信息) 达不到完美需求,于是延伸使用,判断发送企微的json信息是否成功,如果不成功,调用短信通知服务模块进行通>知,并保存相关日志到本地(可改为邮件保存)

#!/usr/bin/env python
# -- coding: utf-8 --
"""
 @Program:接到需求,获取每日的公网IP,并通过企业微信自建应用发送每天的IP地址(企业微信自建应用有一个坑,必须要添加信任可用IP才可以发送信息) 达不到完美需求,于是延伸使用,判断发送企微的json信息是否成功,如果不成功,调用短信通知服务模块进行通知,并保存相关日志到本地(可改为邮件保存)
 @Author: Janexiaoer
 @Motto : All we do is for fun.~
 
"""
import datetime
import json
import time
import urllib
import urllib.request
import urllib.parse
import requests
from urllib.request import urlopen

# 
# 周日不发信息通知 (无实际需求,暂未续写)
# 每次发完信息后记录到日志当中
t = datetime.datetime.now().strftime('%Y-%m-%d')
ip = urlopen('http://ip.42.pl/raw').read().decode()
with open(r"C:\ip.txt", mode='a') as f:
    f.write(t + '  ' + ip)
    f.write("\n")
# print(ip)

# 发送微信通知
# 微信通知
corpid = "wwbxxxxxxxx"
secret = "OG-plxxxxxxxxzxxxYlxxxx0k"
agentid = "10xxx"


def get_token():
    url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}'
    resp = requests.get(url=url)
    json_dict = resp.json()
    hosts = json_dict.get('access_token')
    if resp.status_code != 200:
        print('请求失败,请检查url')
        return
    return hosts


def send_it():
    now = datetime.datetime.now().strftime('%Y-%m-%d,%H:%M:%S')
    content = now + '  最新IP地址是:' + ip
    # print(content)
    web = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}'.format(get_token())

    form_data = {
        "touser": "@all",  # 接收人
        "msgtype": "textcard",
        "agentid": agentid,  # 应用ID
        "textcard": {
            "title": "叮~ 最新IP地址: " + ip,
            "description": content,
            'url': 'https://api.yimian.xyz/img?type=wallpaper&R18=true',
            "btntxt": "随机风景"
        },
        "safe": 0
    }
    send_msg_res = requests.post(url=web, data=json.dumps(form_data))
    json_dict = send_msg_res.json()
    hosts = json_dict.get('errcode')
    if hosts == 60020:
        txt = '发送失败,错误码60020,公网IP不可信'
        print('转短信通知ing...')
        send()
        with open(r"C:\get_error.log", mode='a') as f1:
            f1.write(t + txt + ip)
            f1.write("\n")
    elif hosts != 200:
        txt1 = '发送失败,程序异常,错误码:'
        with open(r"C:\get_error.log", mode='a') as f1:
            f1.write(t + txt1 + hosts + ip)
            f1.write("\n")
    else:
        print(send_msg_res.text)
        print('已发送')


# 发送短信通知
def send():
    smsapi = "https://api.smsbao.com/"  # 使用的是短信宝平台
    user = 'janexiaoer' 
    password = 'baxxxxxxxxxxxxxxxxxx4f9xxxxx7'
    content = "【xxx】微信通知异常," + "最新IP地址:" + ip
    phone = '1234567890'

    data = urllib.parse.urlencode({'u': user, 'p': password, 'm': phone, 'c': content})
    send_url = smsapi + 'sms?' + data
    response = urllib.request.urlopen(send_url)
    the_page = response.read().decode('utf-8')
    # if the_page.status():


if __name__ == '__main__':
    send_it()
    time.sleep(2)

Windows通过pyinstaller打包成exe,添加到系统自带的任务计划程序实现每天或响应时间的自动运行程序。
Linux直接cron或者在该程序中添加Schedule定时调度,在运行程序即可。

posted @   Janexiaoer  阅读(350)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示