This tutorial will describe how to send messages to Slack, using the Slack API with Python.
Slack
To send slack messages, you need to download Slacker.
pip install slacker
Then in your python script, you need to import it.
from slacker import Slacker
Then you need to set up your API token. This is what connects you to your Slack team.
See overview of all of your tokens here
Create a Slacker variable with your token as input, as well as a a channel variable:
slack = Slacker("<Your API token here>");
channel = "<Your Slack channel, e.g. #ttm4115>"
Send messages with this function call:
slack.chat.post_message(channel, "<Your message here>");
MQTT
To communicate with an MQTT broker, install Paho MQTT.
pip install paho-mqtt
And import it to your script:
from paho.mqtt.client import Client
Then we need a client, an on_connect
method (where you subscribe to your topics), and an on_message
(when you receive messages).
An example of on_connect
and on_message
is given here:
topic_sub = "<Topic to subscribe to>"
def on_connect(client, userdata, rc):
print("Connected with result code "+str(rc) + "to topic: " + topic_sub)
client.subscribe(topic_sub)
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
message = "Melding fra MQTT med topic: " + msg.topic + " er mottatt:\n"+ msg.payload;
# Send the received message to a slack channel, for instance stored in a variable
slack.chat.post_message("<Slack channel here>", message);
As you can see, in the on_connect
, you specify which topics you subscribe to.
In the on_message
, we get the message, and we send it to the slack-channel (as described above).
Now we need to connect to the MQTT server, as well as set on_connect
and on_message
.
Paho makes it easy to specify a client:
mqtt_client = mqtt.Client()
Then we specify the functions we have:
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
Then we connect the client to a broker (HiveMQ has a public one we can use), and make it run until the client gets disconnected:
mqtt_client.connect("broker.hivemq.com",1883,8000);
mqtt_client.loop_forever()
Combined
import paho.mqtt.client as mqtt
from paho.mqtt.client import Client
slack = Slacker("<API token here>");
channel = "<Slack channel to send messages to, e.g. #ttm4115>"
topic_sub = "<MQTT topic to subscribe to>"
def on_connect(client, userdata, rc):
print("Connected with result code " + str(rc) + " to topic " + topic_sub)
client.subscribe(topic_sub)
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
message = "Melding fra MQTT med topic: " + msg.topic + " er mottatt:\n" + msg.payload
# Send the received message to the slack channel from your variable
slack.chat.post_message(channel, message)
mqtt_client = Client()
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.connect("broker.hivemq.com", 1883, 8000)
mqtt_client.loop_forever()