butterrobot/butterrobot/lib/slack.py

39 lines
914 B
Python
Raw Normal View History

2020-04-22 21:58:06 +00:00
from typing import Optional, Text
2020-10-28 10:19:30 +00:00
import requests
2020-04-22 21:58:06 +00:00
import structlog
from butterrobot.config import SLACK_BOT_OAUTH_ACCESS_TOKEN
logger = structlog.get_logger()
class SlackAPI:
BASE_URL = "https://slack.com/api"
class SlackError(Exception):
pass
class SlackClientError(Exception):
pass
@classmethod
2020-10-28 10:19:30 +00:00
def send_message(cls, channel, message, thread: Optional[Text] = None):
2020-04-22 21:58:06 +00:00
payload = {
"text": message,
2020-07-03 15:34:49 +00:00
"channel": channel,
2020-04-22 21:58:06 +00:00
}
if thread:
payload["thread_ts"] = thread
2020-10-28 10:19:30 +00:00
response = requestts.post(
2020-04-22 21:58:06 +00:00
f"{cls.BASE_URL}/chat.postMessage",
data=payload,
headers={"Authorization": f"Bearer {SLACK_BOT_OAUTH_ACCESS_TOKEN}"},
2020-10-28 10:19:30 +00:00
)
response_json = response.json()
if not response_json["ok"]:
raise cls.SlackClientError(response_json)