Last active
October 8, 2022 15:29
-
-
Save jinie/7cbc7035508d32f00b52 to your computer and use it in GitHub Desktop.
Pushover.net notifications with MQTT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import paho.mqtt.client as paho | |
import http.client, urllib | |
import argparse | |
import logging | |
import json | |
import sys | |
def parse_message(self, message): | |
dataDict = json.loads(message) | |
return dataDict | |
def on_connect(client, userdata, flags, rc): | |
client.subscribe("/notification/#",0) | |
def on_message(client, userdata, msg): | |
logging.info("received message with topic"+msg.topic) | |
msgData = msg.payload.decode('utf-8') | |
dataDict = json.loads(msgData) | |
if('notification' in dataDict): | |
notification = dataDict['notification'] | |
conn = http.client.HTTPSConnection("api.pushover.net:443") | |
conn.request("POST", "/1/messages.json", | |
urllib.parse.urlencode({ | |
"token": "APP_TOKEN", | |
"user": "USER_TOKEN", | |
"message": "%s\n%s" (msg.topic,notification), | |
}), { "Content-type": "application/x-www-form-urlencoded" }) | |
conn.getresponse() | |
def get_args(): | |
ap = argparse.ArgumentParser() | |
ap.add_argument('-H','--host',help="MQTT Host to connect to", default='localhost') | |
ap.add_argument('-p','--port',help="MQTT port to connect to", type=int, default='1883') | |
ap.add_argument('-v', help="Increase log level, can be specified multiple times", action='count', default=1) | |
args = ap.parse_args() | |
return args | |
def main(): | |
args = get_args() | |
#loglevel = logging.WARNING | |
loglevel = logging.INFO | |
if args.v == 2: | |
loglevel = logging.INFO | |
elif (args.v > 2) or 'pdb' in sys.modules: | |
loglevel = logging.DEBUG | |
#Logger | |
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=loglevel) | |
client = paho.Client() | |
client.user_data_set(args) | |
client.on_connect = on_connect | |
client.on_message = on_message | |
client.connect(args.host, args.port, 60) | |
client.loop_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment