# -- 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 = 'xxxoer'
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)
本人偏新手,没有系统学习,只是将尽量融入到工作,没有相关的图片,已经运行很长一段时间,程序没问题,欢迎有更好的想法一起学习。