Python实现灾害预警信息即时推送

原理

主要采用requests爬取国家预警中心的API,检测本地灾害预警信息,格式化并推送Qmsg酱(QQ机器人),在服务器端
利用Crontab定时执行代码,实现动态监测功能。

平台

  1. Linux 平台
  2. python 3.9
  3. pip3 (requests)

代码

#!/usr/bin/python3
import requests
import json

#qmsg推送函数
#详情请查看 https://qmsg.zendee.cn/
def qmsg_push(wa):
    url2 = "您自己的推送URL"
    msg = '预警:
'+str(wa)+'@'
    params = {"msg": msg}
    res = requests.post(url2, data=params)
    json2 =res.json()
    if json2['success']== True :
            print('Qmsg酱推送成功')
            print(res.text)
    else:
            print('Qmsg酱推送失败')
            print(res.text)


#获取预警信息
url = "http://www.12379.cn/data/alarm_list_all.html"
res = requests.post(url,timeout=None)
res.encoding = 'utf-8'
json2 = res.json()
warning=[]
#判断是否有对应城市预警信息已经对应类型
#一般预警平台会存在多条信息,第一条是最新的
for i in json2['alertData']:
    if ('荔城区' in i['headline'] or '荔城区' in i['description']) and '暴雨' in i['headline']:
        warning.append(i['description'])
        break
#无预警退出
#有预警格式化并推送信息
if  warning==[] :
    print('无预警')
else:
    wa = json.dumps(warning,ensure_ascii=False)
    print(wa)
    qmsg_push(wa)

服务器部署

  1. Linux服务器
  2. Python3
  3. pip3安装requests
pip3 install requests
  1. 创建文件
    利用VIM或其他编辑器,写入代码到yujing文件内,添加执行权限。
chmod +x yujing
  1. 定时脚本
    Crontab设置定时任务
    找到yujing文件位置,比如/root/yujing,新建一个log文件 然后cronrab -e进入编辑输入以下命令
*/60 * * * * /root/yy > /root/log
  1. 查看日志
cat /root/log

实现效果

image
bilibili演示地址

注意

本文为Billyme原创,不允许任何形式的转载,本文地址https://www.cnblogs.com/billyme/p/15104031.html。

原文地址:https://www.cnblogs.com/billyme/p/15104031.html