diff --git a/ssa/slack-bot/slackbot.py b/ssa/slack-bot/slackbot.py new file mode 100644 index 0000000..773f56d --- /dev/null +++ b/ssa/slack-bot/slackbot.py @@ -0,0 +1,75 @@ +""" +slackbot.py + +Use slack app integration to post messages via the slack api +""" + +import configparser +import influxdb +import time +import datetime +import requests + +PUMP1_FLOW_QUERY = """ +SELECT last(value) as value From Pump1 +""" +PUMP2_FLOW_QUERY = """ +SELECT last(value) as value From Pump2 +""" + + +class SlackBot: + def __init__(self): + self.config = configparser.ConfigParser() + self.config.read("slackbot_config.ini") + self.last_dtime1 = 0 + self.last_dtime2 = 0 + + def run(self): + while True: + self.post_update() + time.sleep(self.config.get("sleep_time_sec")) + + def post_update(self): + # poll latest data + with influxdb.InfluxDBClient( + self.config["influxdb"].get("host", "localhost"), + self.config["influxdb"].get("port", "8086"), + self.config["influxdb"].get("username", None), + self.config["influxdb"].get("password", None), + self.config["influxdb"].get("dbname", "paddle"), + ) as idb_client: + result1 = idb_client.query(PUMP1_FLOW_QUERY) + (pump1, time1) = self.parse_pump_query_result(result1, "Pump1") + result2 = idb_client.query(PUMP2_FLOW_QUERY) + (pump2, time2) = self.parse_pump_query_result(result2, "Pump2") + + # post to slack channel + dtime1 = datetime.datetime.fromisoformat(time1) + dtime2 = datetime.datetime.fromisoformat(time2) + message = f"Pump1: {pump1:4.1f} ({dtime1.strftime("%d %b %Y, %I:%M%p")})\nPump2: {pump2:4.1f} ({dtime2.strftime("%d %b %Y, %I:%M%p")})" + + json_message = { + "channel": self.config["slack"].get("channel_id"), + "text": message, + } + + headers = { + "Authorization": f"Bearer {self.config["slack"].get("token")}", + "Content-type": "application/json" + } + post_url = self.config["slack"].get("post_url") + + requests.post(url=post_url, headers=headers, json=json_message) + + + def parse_pump_query_result(self, result, name): + data = list(result.get_points(name))[0] + value = data.get("value") + time = data.get("time") + return (value, time) + + +if __name__ == "__main__": + slackBot = SlackBot() + slackBot.run() diff --git a/ssa/slack-bot/slackbot_config.ini b/ssa/slack-bot/slackbot_config.ini new file mode 100644 index 0000000..e69de29