forked from GDSC-Daejin/responsive-slack-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slack.py
145 lines (123 loc) · 4.73 KB
/
slack.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
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
import asyncio
import html
import re
from datetime import datetime, timezone, timedelta
try:
from config import *
except ModuleNotFoundError:
app_token = os.environ["SLACK_APP_TOKEN"]
bot_token = os.environ["SLACK_BOT_TOKEN"]
# Initialize the Slack API client and the bot app
client = WebClient(token=bot_token)
app = App(token=bot_token)
def update(channel_id, message_ts, text, new_text):
response = client.chat_update(
channel=channel_id,
ts=message_ts,
text=text,
blocks=new_text,
)
async def get_message(payload, a):
check = None
today = datetime.now(timezone(timedelta(hours=9))).strftime("%Y-%m-%d")
channel_id = payload["channel"]["id"]
user_id = payload["user"]["id"]
user_name = payload["user"]["name"]
message_ts = payload["container"]["message_ts"]
text = payload["message"]["text"]
comment = f"<@{user_id}>, "
data = payload["message"]["blocks"]
get_date = ""
if a == 1:
status = "*참석*\n "
op_status = "*불참*\n "
op_ps_status = "*불참인원*"
ps_status = "*참석인원*"
elif a == 0:
status = "*불참*\n "
op_status = "*참석*\n "
ps_status = "*불참인원*"
op_ps_status = "*참석인원*"
insert = {
"type": "section",
"fields": [
{"type": "mrkdwn", "text": "*참석인원*\n 0 *(명)*"},
{"type": "mrkdwn", "text": "*불참인원*\n 0 *(명)*"},
],
}
if "divider" in data[-2]["type"]:
data.insert(-1, insert)
for index, block in enumerate(data):
try:
if "context" in block["type"]:
get_date = block["elements"][0]["text"]
pattern = r"\d{4}-\d{2}-\d{2}"
matches = re.findall(pattern, get_date)
get_date = matches[0]
if ("actions" in block["type"]) and get_date and get_date < today:
check = index
except Exception as e :
print(e)
if check:
print(check)
data = payload["message"]["blocks"]
del data[index]
else:
for block in data:
try:
if "section" in block["type"]:
for a in block["fields"]:
if op_status in a["text"]:
a["text"] = a["text"].replace(comment, "")
for person in data[-2]["fields"]:
if person["text"].find(op_ps_status) == 0:
person["text"] = person["text"].split()
person["text"][0] += "\n"
if int(person["text"][1]) > 0:
person["text"][1] = str(a["text"].count("@"))
person["text"] = " ".join(person["text"])
if status in a["text"]:
if comment in a["text"]:
pass
else:
# pass
a["text"] += comment
for person in data[-2]["fields"]:
if person["text"].find(ps_status) == 0:
person["text"] = person["text"].split()
person["text"][0] += "\n"
person["text"][1] = str(a["text"].count("@"))
person["text"] = " ".join(person["text"])
except KeyError as e:
pass
def unescape(input):
return html.unescape(input)
for item in data:
for key in item.keys():
if isinstance(item[key], str):
item[key] = unescape(item[key])
elif isinstance(item[key], dict):
for sub_key in item[key].keys():
if isinstance(item[key][sub_key], str):
item[key][sub_key] = unescape(item[key][sub_key])
update(channel_id, message_ts, text, data)
@app.action("attend")
def handle_attent_edit_button_click(ack, body, logger):
ack()
logger.info(body)
asyncio.run(get_message(body, 1))
@app.action("nonattend")
def handle_nonattent_edit_button_click(ack, body, logger):
ack()
logger.info(body)
asyncio.run(get_message(body, 0))
# asyncio.run(nonattend_edit_message(body))
if __name__ == "__main__":
# Start the bot
handler = SocketModeHandler(app_token=app_token, app=app)
handler.start()