Commit 35f86fafbf2883c62a0e29fdfb19fab50b323a78

Authored by Greg Sandstrom
1 parent 666db27d6e
Exists in main

first stab at slackbot integration

Showing 1 changed file with 75 additions and 0 deletions Side-by-side Diff

ssa/slack-bot/slackbot.py View file @ 35f86fa
  1 +"""
  2 +slackbot.py
  3 +
  4 +Use slack app integration to post messages via the slack api
  5 +"""
  6 +
  7 +import configparser
  8 +import influxdb
  9 +import time
  10 +import datetime
  11 +import requests
  12 +
  13 +PUMP1_FLOW_QUERY = """
  14 +SELECT last(value) as value From Pump1
  15 +"""
  16 +PUMP2_FLOW_QUERY = """
  17 +SELECT last(value) as value From Pump2
  18 +"""
  19 +
  20 +
  21 +class SlackBot:
  22 + def __init__(self):
  23 + self.config = configparser.ConfigParser()
  24 + self.config.read("slackbot_config.ini")
  25 + self.last_dtime1 = 0
  26 + self.last_dtime2 = 0
  27 +
  28 + def run(self):
  29 + while True:
  30 + self.post_update()
  31 + time.sleep(self.config.get("sleep_time_sec"))
  32 +
  33 + def post_update(self):
  34 + # poll latest data
  35 + with influxdb.InfluxDBClient(
  36 + self.config["influxdb"].get("host", "localhost"),
  37 + self.config["influxdb"].get("port", "8086"),
  38 + self.config["influxdb"].get("username", None),
  39 + self.config["influxdb"].get("password", None),
  40 + self.config["influxdb"].get("dbname", "paddle"),
  41 + ) as idb_client:
  42 + result1 = idb_client.query(PUMP1_FLOW_QUERY)
  43 + (pump1, time1) = self.parse_pump_query_result(result1, "Pump1")
  44 + result2 = idb_client.query(PUMP2_FLOW_QUERY)
  45 + (pump2, time2) = self.parse_pump_query_result(result2, "Pump2")
  46 +
  47 + # post to slack channel
  48 + dtime1 = datetime.datetime.fromisoformat(time1)
  49 + dtime2 = datetime.datetime.fromisoformat(time2)
  50 + 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")})"
  51 +
  52 + json_message = {
  53 + "channel": self.config["slack"].get("channel_id"),
  54 + "text": message,
  55 + }
  56 +
  57 + headers = {
  58 + "Authorization": f"Bearer {self.config["slack"].get("token")}",
  59 + "Content-type": "application/json"
  60 + }
  61 + post_url = self.config["slack"].get("post_url")
  62 +
  63 + requests.post(url=post_url, headers=headers, json=json_message)
  64 +
  65 +
  66 + def parse_pump_query_result(self, result, name):
  67 + data = list(result.get_points(name))[0]
  68 + value = data.get("value")
  69 + time = data.get("time")
  70 + return (value, time)
  71 +
  72 +
  73 +if __name__ == "__main__":
  74 + slackBot = SlackBot()
  75 + slackBot.run()