-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
272 lines (228 loc) · 9.01 KB
/
Copy pathapp.py
File metadata and controls
272 lines (228 loc) · 9.01 KB
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import logging
import sys
import threading
import time
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from config import Config
from state import InMemoryState, RedisState
from channel_manager import ChannelManager
from slack_logger import SlackLogHandler, SlackLogFilter
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)
def main():
config_errors = Config.validate()
if config_errors:
for error in config_errors:
logger.error(f"Config error: {error}")
sys.exit(1)
app = App(
token=Config.SLACK_BOT_TOKEN,
signing_secret=Config.SLACK_SIGNING_SECRET,
)
if Config.REDIS_URL:
state_backend = RedisState(Config.REDIS_URL)
logger.info("Using Redis for state")
else:
state_backend = InMemoryState()
logger.info("Using in-memory state (set REDIS_URL for persistence)")
channel_manager = ChannelManager(app.client, state_backend)
if Config.LOG_CHANNEL:
slack_handler = SlackLogHandler(app.client, Config.LOG_CHANNEL)
slack_handler.addFilter(SlackLogFilter())
logging.getLogger().addHandler(slack_handler)
logger.info("Slack log channel enabled")
@app.event("team_join")
def handle_team_join(event: dict, logger: logging.Logger):
if not Config.BOT_ENABLED:
return
user = event.get("user", {})
user_id = user.get("id")
if not user_id or user.get("is_bot"):
return
# If user is a guest, wait until they become full member
if user.get("is_restricted") or user.get("is_ultra_restricted"):
state_backend.add_pending_guest(user_id)
return
try:
channel_manager.add_user_to_welcome_channel(user_id)
except Exception:
logger.exception("Error processing team_join")
@app.event("member_joined_channel")
def handle_member_joined(event: dict, client, logger: logging.Logger):
if not Config.BOT_ENABLED:
return
user_id = event.get("user")
channel_id = event.get("channel")
if not user_id or not channel_id:
return
current_state = state_backend.get_state()
is_welcome_channel = channel_id == current_state.current_channel_id
if not is_welcome_channel:
try:
info = client.conversations_info(channel=channel_id)
channel_name = info["channel"]["name"]
is_welcome_channel = Config.is_welcome_channel_name(channel_name)
except Exception:
pass
if not is_welcome_channel:
return
# Only process if user hasn't been handled by team_join
if not state_backend.is_user_processed(user_id):
try:
channel_manager.add_user_to_welcome_channel(user_id)
except Exception:
logger.exception("Failed to process new user from channel join")
@app.event("message")
def handle_message_events(body, logger):
pass
@app.action("optin_join")
def handle_optin_join(ack, body, client):
ack()
user_id = body["user"]["id"]
channel_id = body["actions"][0]["value"]
success = channel_manager._invite_user(channel_id, user_id)
if success:
client.chat_postEphemeral(
channel=body["channel"]["id"],
user=user_id,
text=f"You've been added to <#{channel_id}>!",
)
else:
client.chat_postEphemeral(
channel=body["channel"]["id"],
user=user_id,
text=f"Couldn't add you to <#{channel_id}>. Try joining manually.",
)
@app.action("optin_decline")
def handle_optin_decline(ack, body, client):
ack()
client.chat_postEphemeral(
channel=body["channel"]["id"],
user=body["user"]["id"],
text="No problem! You can always join later.",
)
@app.command("/helpme")
def handle_help_command(ack, body, client, logger):
logger.info(f"Received /i-need-help command from {body['user_id']}")
ack()
user_id = body["user_id"]
if not Config.WELCOME_COMMITTEE_CHANNEL:
client.chat_postEphemeral(
channel=body["channel_id"],
user=user_id,
text="Help requests aren't configured yet. Ask in a public channel!",
)
return
client.chat_postEphemeral(
channel=body["channel_id"],
user=user_id,
text="Need help?",
blocks=[
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":wave: *Need help getting started?*\n\nClick below and someone from our welcome committee will reach out!"
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "Ask for Help"},
"style": "primary",
"action_id": "request_help",
},
],
},
],
)
@app.action("request_help")
def handle_help_request(ack, body, client):
ack()
user_id = body["user"]["id"]
if not Config.WELCOME_COMMITTEE_CHANNEL:
return
try:
client.chat_postMessage(
channel=Config.WELCOME_COMMITTEE_CHANNEL,
text=f"<@{user_id}> needs help!",
blocks=[
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f":raising_hand: <@{user_id}> is looking for help!\n\nCan someone DM them?"
}
},
],
)
client.chat_postEphemeral(
channel=body["channel"]["id"],
user=user_id,
text=":white_check_mark: Request sent! Someone will DM you soon.",
)
logger.info(f"Help request sent for user {user_id}")
except Exception as e:
logger.error(f"Failed to send help request: {e}")
client.chat_postEphemeral(
channel=body["channel"]["id"],
user=user_id,
text="Something went wrong. Try again or ask in a public channel.",
)
@app.event("user_change")
def handle_user_change(event: dict, logger: logging.Logger):
if not Config.BOT_ENABLED:
return
user = event.get("user", {})
user_id = user.get("id")
if not user_id:
return
is_restricted = user.get("is_restricted", False)
is_ultra_restricted = user.get("is_ultra_restricted", False)
if not is_restricted and not is_ultra_restricted:
if state_backend.is_pending_guest(user_id):
try:
channel_manager.process_promoted_guest(user_id)
except Exception:
logger.exception("Failed to process promoted guest")
logger.info("=" * 50)
logger.info("Welcome Bot starting...")
logger.info(f"Enabled: {Config.BOT_ENABLED}")
logger.info(f"Batch size: {Config.BATCH_SIZE}")
logger.info(f"Channel format: {Config.get_channel_name(1)}, {Config.get_channel_name(2)}, ...")
if Config.REMOVAL_AFTER_DAYS > 0:
logger.info(f"Auto-removal: after {Config.REMOVAL_AFTER_DAYS} day(s), checked every {Config.REMOVAL_CHECK_INTERVAL_MINUTES} min")
else:
logger.info("Auto-removal: disabled")
logger.info("=" * 50)
if Config.REMOVAL_AFTER_DAYS > 0:
if not Config.REDIS_URL:
logger.warning(
"Auto-removal is enabled without REDIS_URL — add-times are kept "
"in memory only and will be lost on restart, so users added before "
"a restart won't be removed. Set REDIS_URL for durable tracking."
)
def _removal_sweeper():
interval = Config.REMOVAL_CHECK_INTERVAL_MINUTES * 60
while True:
try:
channel_manager.remove_expired_users()
except Exception:
logger.exception("Error during expired-user removal sweep")
time.sleep(interval)
threading.Thread(target=_removal_sweeper, daemon=True, name="removal-sweeper").start()
logger.info("Removal sweeper thread started")
if Config.SLACK_APP_TOKEN:
handler = SocketModeHandler(app, Config.SLACK_APP_TOKEN)
handler.start()
else:
app.start(port=3000)
if __name__ == "__main__":
main()