From bf32b227dfeee7d1c6fef6ac1ed352fdd3f8683a Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Tue, 29 Sep 2020 11:15:54 -0700 Subject: [PATCH] Add a listener for the Slack "channel_created" event Currently this just posts a simple message when a channel is created. Eventually, we'll want to do something different such as creating a puzzle sheet and linking/pinning it to the channel. --- turbot/slack.py | 22 ++++++++++++++++++---- turbot/turbot.py | 9 +++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/turbot/slack.py b/turbot/slack.py index 9982822..6218100 100644 --- a/turbot/slack.py +++ b/turbot/slack.py @@ -53,7 +53,21 @@ def slack_send_reply(request, text): if (resp.status_code != 200): app.logger.error("Error posting request to Slack: " + resp.text) else: - try: - slack_client.chat_postMessage(channel=channel, text=text) - except SlackApiError as e: - app.logger.error("Slack API error: " + e.response["error"]) + slack_send_message(channel, text) + +def slack_send_message(channel, text): + """Send a Slack message to a specified channel. + + Note: If flask is in debug mode, this function will just print the + text to stdout.""" + + app = current_app + + if (app.debug): + print("Sending message to channel '{}': {}".format(channel, text)) + return + + try: + slack_client.chat_postMessage(channel=channel, text=text) + except SlackApiError as e: + app.logger.error("Slack API error: " + e.response["error"]) diff --git a/turbot/turbot.py b/turbot/turbot.py index fa37804..e7fc87e 100755 --- a/turbot/turbot.py +++ b/turbot/turbot.py @@ -4,6 +4,7 @@ from flask import Flask from slackeventsapi import SlackEventAdapter import os from turbot.rot import rot_route +from turbot.slack import slack_send_message app = Flask(__name__) app.register_blueprint(rot_route) @@ -11,6 +12,14 @@ app.register_blueprint(rot_route) slack_signing_secret = os.environ['SLACK_SIGNING_SECRET'] slack_events = SlackEventAdapter(slack_signing_secret, "/slack/events", app) +@slack_events.on("channel_created") +def handle_channel_created(event_data): + event = event_data["event"] + channel = event["channel"] + slack_send_message(channel["id"], + "Cool. You made a channel named {}" + .format(channel["name"])) + @slack_events.on("error") def handle_error(error): app.logger.error("Error from Slack: " + str(error)) -- 2.43.0