Python MQTT how to publish a single message (one-shot)

dependencies

for this example, we use paho-mqtt, install it via pip:

pip3 install paho-mqtt

INFO: you also need a mqtt tracker, like mosquitto to test your requests

script

this script will publish one message to the broker, we dont deal here with subscriptions and stuff, just send one message.

import paho.mqtt.publish as publish

def sendMqttEvent(hostname,topic,payload,qos=0):
try:
    publish.single(topic, payload=payload, qos=qos, retain=False, hostname=hostname,
    port=1883, client_id="generic-client", keepalive=60, will=None, auth=None, tls=None, transport="tcp")
except Exception as e:
    print("sendMqttEvent failed, because: %s"%e)    

# usage
sendMqttEvent('generic-url.com','bern/EG/PIR','HEELLLOOOO')