本代码的前提是:
1. 正在使用homeassistant控制智能家居设备
[Python] 纯文本查看 复制代码
#!/usr/bin/env python
# -- coding: utf-8 --
import datetime
import json
import urllib.request
import urllib.parse
import requests
import schedule
import time
import urllib
corpid = "wxx64"
secret = "OxxxxlbE0k"
agentid = "10xxx"
txt = '早上好,公司空调按任务进行中...温度:17°;模式:制冷...'
# 定义任务函数
def task():
resp = requests.get('http://ip/api/webhook/test-PU0A1g6YvaQUIPCkZoZ0LrhQ')
send_it()
print('指令已下发...')
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')
txt1 = '已经按照指令将空调模式全部设置为: 温度:17度,模式:Cooling... 预祝今天行程万事顺意~'
txt2 = '任务进行中...温度:17°;模式:制冷...'
content = now + ' ' + txt1
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": "叮~ " + txt2,
"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:
print('------------------------')
print(now)
print('转短信通知ing...')
send()
else:
print('------------------------')
print(now)
print('已发送')
# 发送短信通知
def send():
txt4 = '任务进行中...温度:17°;模式:制冷...'
smsapi = "https://axxxao.com/"
user = 'janxxoer'
password = 'ba39axxxd9xxx2xx7'
content = "微信通知异常!\n" + txt4 + '\n预祝今日万事顺意~'
phone = 'xxxxxx'
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():
schedule.every().day.at("09:00").do(task)
if __name__ == '__main__':
# 定义周一到周六的任务
# 正在进行中
print('正在进行中...')
while True:
# print('正在进行中...')
schedule.run_pending()
time.sleep(2)
如有更好的想法,欢迎沟通一起学习! |