-
Notifications
You must be signed in to change notification settings - Fork 7
/
app.py
152 lines (124 loc) · 5.22 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import logging
import os
from pathlib import Path
import git
from dotenv import load_dotenv
from flask import Flask, jsonify, request
from slack import WebClient
from slack_sdk.errors import SlackApiError
from slackeventsapi import SlackEventAdapter
DEPLOYS_CHANNEL_NAME = "#project-blt-lettuce-deploys"
JOINS_CHANNEL_ID = "C06RMMRMGHE"
CONTRIBUTE_ID = "C04DH8HEPTR"
load_dotenv()
logging.basicConfig(
filename="slack_messages.log",
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)
app = Flask(__name__)
slack_events_adapter = SlackEventAdapter(os.environ["SIGNING_SECRET"], "/slack/events", app)
client = WebClient(token=os.environ["SLACK_TOKEN"])
client.chat_postMessage(channel=DEPLOYS_CHANNEL_NAME, text="bot started v1.9 240611-1 top")
@app.route("/slack/events", methods=["POST"])
def slack_events():
data = request.json
# Respond to Slack's URL verification challenge
if "challenge" in data:
return jsonify({"challenge": data["challenge"]})
# Handle other event types here
event = data.get("event", {})
handle_message(event)
return "Event received", 200
# keep for debugging purposes
# @app.before_request
# def log_request():
# if request.path == '/slack/events' and request.method == 'POST':
# # Log the request headers and body
# logging.info(f"Headers: {request.headers}")
# logging.info(f"Body: {request.get_data(as_text=True)}")
# Determine the root directory (assumes the script is run from the root folder)
root_dir = Path(__file__).resolve().parent
@app.route("/update_server", methods=["POST"])
def webhook():
if request.method == "POST":
current_directory = os.path.dirname(os.path.abspath(__file__))
repo = git.Repo(current_directory)
origin = repo.remotes.origin
origin.pull()
latest_commit_message = repo.head.commit.message.strip()
client.chat_postMessage(
channel=DEPLOYS_CHANNEL_NAME,
text=f"Deployed the latest version 1.8. Latest commit: {latest_commit_message}",
)
return "OK", 200
return "Error", 400
@slack_events_adapter.on("team_join")
def handle_team_join(event_data):
user_id = event_data["event"]["user"]["id"]
# Post a message in the private joins channel
response = client.chat_postMessage(
channel=JOINS_CHANNEL_ID, text=f"<@{user_id}> joined the team."
)
if not response["ok"]:
client.chat_postMessage(
channel=DEPLOYS_CHANNEL_NAME,
text=f"Error sending message: {response['error']}",
)
logging.error(f"Error sending message: {response['error']}")
try:
response = client.conversations_open(users=[user_id])
dm_channel_id = response["channel"]["id"]
with open("welcome_message.txt", "r", encoding="utf-8") as file:
welcome_message_template = file.read()
welcome_message = welcome_message_template.format(user_id=user_id)
blocks = [{"type": "section", "text": {"type": "mrkdwn", "text": welcome_message.strip()}}]
client.chat_postMessage(
channel=dm_channel_id, text="Welcome to the OWASP Slack Community!", blocks=blocks
)
except Exception as e:
logging.error(f"Error sending welcome message: {e}")
@slack_events_adapter.on("message")
def handle_message(payload):
message = payload.get("event", {})
try:
response = client.auth_test()
bot_user_id = response["user_id"]
except SlackApiError:
bot_user_id = None
# Check if the message was not sent by the bot itself
if message.get("user") != bot_user_id:
if (
message.get("subtype") is None
and not any(keyword in message.get("text", "").lower() for keyword in ["#contribute"])
and any(
keyword in message.get("text", "").lower()
for keyword in ("contribute", "contributing", "contributes")
)
):
user = message.get("user")
channel = message.get("channel")
logging.info(f"detected contribute sending to channel: {channel}")
response = client.chat_postMessage(
channel=channel,
text=(
f"Hello <@{user}>! Please check this channel "
f"<#{CONTRIBUTE_ID}> for contributing guidelines today!"
),
)
if not response["ok"]:
client.chat_postMessage(
channel=DEPLOYS_CHANNEL_NAME,
text=f"Error sending message: {response['error']}",
)
logging.error(f"Error sending message: {response['error']}")
if message.get("channel_type") == "im":
user = message["user"] # The user ID of the person who sent the message
text = message.get("text", "") # The text of the message
try:
if message.get("user") != bot_user_id:
client.chat_postMessage(channel=JOINS_CHANNEL_ID, text=f"<@{user}> said {text}")
# Respond to the direct message
client.chat_postMessage(channel=user, text=f"Hello <@{user}>, you said: {text}")
except SlackApiError as e:
print(f"Error sending response: {e.response['error']}")