Skip to content

Commit 5526312

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 2e13107 commit 5526312

12 files changed

Lines changed: 233 additions & 198 deletions

File tree

src/friendly_computing_machine/bot/handlers/actions.py

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -154,75 +154,79 @@ def handle_manman_server_stop(
154154
def handle_poll_vote(ack: Ack, body, client: SlackWebClientFCM, logger):
155155
"""Handle poll vote button clicks."""
156156
ack()
157-
157+
158158
try:
159-
from friendly_computing_machine.db.dal.poll_dal import insert_poll_vote, get_poll_by_id
159+
import datetime
160+
161+
from friendly_computing_machine.db.dal.poll_dal import (
162+
get_poll_by_id,
163+
insert_poll_vote,
164+
)
160165
from friendly_computing_machine.models.poll import PollVoteCreate
161166
from friendly_computing_machine.temporal.util import get_temporal_client_async
162-
import datetime
163-
import asyncio
164-
167+
165168
# Parse action_id to get poll_id and option_id
166169
action_id = body["actions"][0]["action_id"]
167170
# Format: poll_vote_{poll_id}_{option_id}
168171
parts = action_id.split("_")
169172
poll_id = int(parts[2])
170173
option_id = int(parts[3])
171-
174+
172175
user_id = body["user"]["id"]
173-
176+
174177
logger.info(f"User {user_id} voting for option {option_id} in poll {poll_id}")
175-
178+
176179
# Check if poll is still active
177180
poll = get_poll_by_id(poll_id)
178181
if not poll or not poll.is_active:
179182
ack("This poll is no longer active.")
180183
return
181-
184+
182185
if not poll.workflow_id:
183186
logger.error(f"Poll {poll_id} has no workflow_id")
184187
ack("Error: Poll workflow not found.")
185188
return
186-
189+
187190
# Record the vote
188191
vote_create = PollVoteCreate(
189192
poll_id=poll_id,
190193
poll_option_id=option_id,
191194
slack_user_slack_id=user_id,
192195
created_at=datetime.datetime.now(),
193196
)
194-
197+
195198
insert_poll_vote(vote_create)
196199
logger.info(f"Recorded vote for user {user_id} in poll {poll_id}")
197-
200+
198201
# Send signal to the temporal workflow to trigger update
199202
def send_signal():
200203
try:
201204
import asyncio
205+
202206
async def async_send_signal():
203207
temporal_client = await get_temporal_client_async()
204208
handle = temporal_client.get_workflow_handle(poll.workflow_id)
205209
await handle.signal("request_poll_update")
206210
logger.info(f"Sent update signal to workflow {poll.workflow_id}")
207-
211+
208212
# Run the async operation synchronously
209213
asyncio.run(async_send_signal())
210214
except Exception as e:
211215
logger.warning(f"Failed to send signal to workflow: {e}")
212-
216+
213217
send_signal()
214-
218+
215219
# Send ephemeral confirmation to the user
216220
client.chat_postEphemeral(
217221
channel=body["channel"]["id"],
218222
user=user_id,
219-
text="✅ Your vote has been recorded!"
223+
text="✅ Your vote has been recorded!",
220224
)
221-
225+
222226
except Exception as e:
223227
logger.exception(f"Error handling poll vote: {e}")
224228
client.chat_postEphemeral(
225229
channel=body["channel"]["id"],
226230
user=body["user"]["id"],
227-
text="❌ Sorry, there was an error recording your vote. Please try again."
231+
text="❌ Sorry, there was an error recording your vote. Please try again.",
228232
)

src/friendly_computing_machine/bot/handlers/commands.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -160,23 +160,23 @@ def handle_wpoll_command(ack: Ack, say: Say, command, client: SlackWebClientFCM)
160160
span.set_attribute("slack.command", "/wpoll")
161161
span.set_attribute("slack.user.id", command["user_id"])
162162
span.set_attribute("slack.channel.id", command["channel_id"])
163-
163+
164164
# Import here to avoid circular imports
165165
from friendly_computing_machine.bot.modal_schemas import PollCreateModal
166-
166+
167167
modal = PollCreateModal()
168168
# Pass the channel ID as private metadata so we can retrieve it in the view handler
169169
view = modal.build()
170170
view["private_metadata"] = command["channel_id"]
171-
171+
172172
client.views_open(
173173
trigger_id=command["trigger_id"],
174174
view=view,
175175
)
176-
176+
177177
logger.info("Poll creation modal opened for user %s", command["user_id"])
178178
span.set_status(trace.Status(trace.StatusCode.OK))
179-
179+
180180
except Exception as e:
181181
span.record_exception(e)
182182
span.set_status(trace.Status(trace.StatusCode.ERROR, str(e)))

src/friendly_computing_machine/bot/handlers/views.py

Lines changed: 58 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -64,38 +64,64 @@ def handle_view_submission_events(ack, body, logger):
6464
def handle_poll_create_submission(ack: Ack, body, client: SlackWebClientFCM, logger):
6565
"""Handle poll creation modal submission."""
6666
ack()
67-
67+
6868
try:
6969
import datetime
70-
from friendly_computing_machine.db.dal.poll_dal import insert_poll, insert_poll_options
71-
from friendly_computing_machine.models.poll import PollCreate, PollOptionCreate
72-
from friendly_computing_machine.temporal.poll_workflow import PollWorkflow, PollWorkflowParams
73-
from friendly_computing_machine.temporal.util import execute_workflow, get_temporal_queue_name
70+
7471
from friendly_computing_machine.bot.util import slack_send_message
75-
from friendly_computing_machine.db.dal.poll_dal import update_poll_message_info
76-
72+
from friendly_computing_machine.db.dal.poll_dal import (
73+
insert_poll,
74+
insert_poll_options,
75+
update_poll_message_info,
76+
)
77+
from friendly_computing_machine.models.poll import PollCreate, PollOptionCreate
78+
from friendly_computing_machine.temporal.poll_workflow import (
79+
PollWorkflow,
80+
PollWorkflowParams,
81+
)
82+
from friendly_computing_machine.temporal.util import (
83+
execute_workflow,
84+
get_temporal_queue_name,
85+
)
86+
7787
# Extract form data
7888
values = body["view"]["state"]["values"]
79-
89+
8090
# Required fields
8191
title = values["poll_title_block"]["poll_title_input"]["value"]
8292
option1 = values["poll_option_1_block"]["poll_option_1_input"]["value"]
8393
option2 = values["poll_option_2_block"]["poll_option_2_input"]["value"]
84-
94+
8595
# Optional fields
86-
description = values.get("poll_description_block", {}).get("poll_description_input", {}).get("value")
87-
option3 = values.get("poll_option_3_block", {}).get("poll_option_3_input", {}).get("value")
88-
option4 = values.get("poll_option_4_block", {}).get("poll_option_4_input", {}).get("value")
89-
option5 = values.get("poll_option_5_block", {}).get("poll_option_5_input", {}).get("value")
90-
96+
description = (
97+
values.get("poll_description_block", {})
98+
.get("poll_description_input", {})
99+
.get("value")
100+
)
101+
option3 = (
102+
values.get("poll_option_3_block", {})
103+
.get("poll_option_3_input", {})
104+
.get("value")
105+
)
106+
option4 = (
107+
values.get("poll_option_4_block", {})
108+
.get("poll_option_4_input", {})
109+
.get("value")
110+
)
111+
option5 = (
112+
values.get("poll_option_5_block", {})
113+
.get("poll_option_5_input", {})
114+
.get("value")
115+
)
116+
91117
# Get user and channel info
92118
user_id = body["user"]["id"]
93119
channel_id = body["view"]["private_metadata"]
94-
120+
95121
if not channel_id:
96122
logger.error("No channel ID found in private_metadata")
97123
return
98-
124+
99125
# Create poll in database
100126
expires_at = datetime.datetime.now() + datetime.timedelta(hours=8)
101127
poll_create = PollCreate(
@@ -107,10 +133,10 @@ def handle_poll_create_submission(ack: Ack, body, client: SlackWebClientFCM, log
107133
expires_at=expires_at,
108134
is_active=True,
109135
)
110-
136+
111137
poll = insert_poll(poll_create)
112138
logger.info(f"Created poll with ID: {poll.id}")
113-
139+
114140
# Create poll options
115141
options_data = [(option1, 1), (option2, 2)]
116142
if option3:
@@ -119,45 +145,48 @@ def handle_poll_create_submission(ack: Ack, body, client: SlackWebClientFCM, log
119145
options_data.append((option4, 4))
120146
if option5:
121147
options_data.append((option5, 5))
122-
148+
123149
poll_options = [
124150
PollOptionCreate(poll_id=poll.id, text=text, display_order=order)
125151
for text, order in options_data
126152
]
127-
153+
128154
insert_poll_options(poll_options)
129155
logger.info(f"Created {len(poll_options)} options for poll {poll.id}")
130-
156+
131157
# Send initial poll message to channel
132158
initial_message = f"📊 **{title}**"
133159
if description:
134160
initial_message += f"\n_{description}_"
135161
initial_message += "\n\n_Setting up poll..._"
136-
162+
137163
slack_message = slack_send_message(
138164
channel=channel_id,
139165
message=initial_message,
140166
)
141-
167+
142168
# Update poll with message info
143-
update_poll_message_info(poll.id, slack_message.id, slack_message.ts.isoformat())
144-
169+
update_poll_message_info(
170+
poll.id, slack_message.id, slack_message.ts.isoformat()
171+
)
172+
145173
# Start temporal workflow
146174
workflow_id = f"poll-workflow-{poll.id}-{datetime.datetime.now().isoformat()}"
147-
175+
148176
# Update poll with workflow ID
149177
from friendly_computing_machine.db.dal.poll_dal import update_poll_workflow_id
178+
150179
update_poll_workflow_id(poll.id, workflow_id)
151-
180+
152181
execute_workflow(
153182
PollWorkflow.run,
154183
PollWorkflowParams(poll_id=poll.id, duration_hours=8),
155184
id=workflow_id,
156185
task_queue=get_temporal_queue_name("main"),
157186
)
158-
187+
159188
logger.info(f"Started poll workflow {workflow_id} for poll {poll.id}")
160-
189+
161190
except Exception as e:
162191
logger.exception(f"Error creating poll: {e}")
163192
# In a real app, you might want to show an error message to the user

src/friendly_computing_machine/db/dal/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@
4545
get_poll_by_id,
4646
get_poll_options,
4747
get_poll_vote_counts,
48-
get_poll_votes,
4948
get_poll_voters_by_option,
49+
get_poll_votes,
5050
insert_poll,
5151
insert_poll_options,
5252
insert_poll_vote,

src/friendly_computing_machine/db/dal/poll_dal.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,16 @@ def get_poll_by_id(poll_id: int) -> Optional[Poll]:
3333
return session.exec(statement).first()
3434

3535

36-
def update_poll_message_info(poll_id: int, slack_message_id: int, slack_message_ts: str) -> Poll:
36+
def update_poll_message_info(
37+
poll_id: int, slack_message_id: int, slack_message_ts: str
38+
) -> Poll:
3739
"""Update poll with Slack message information."""
3840
with Session(get_db_connection()) as session:
3941
statement = select(Poll).where(Poll.id == poll_id)
4042
poll = session.exec(statement).first()
4143
if not poll:
4244
raise ValueError(f"Poll with id {poll_id} not found")
43-
45+
4446
poll.slack_message_id = slack_message_id
4547
poll.slack_message_ts = slack_message_ts
4648
session.add(poll)
@@ -56,7 +58,7 @@ def update_poll_workflow_id(poll_id: int, workflow_id: str) -> Poll:
5658
poll = session.exec(statement).first()
5759
if not poll:
5860
raise ValueError(f"Poll with id {poll_id} not found")
59-
61+
6062
poll.workflow_id = workflow_id
6163
session.add(poll)
6264
session.commit()
@@ -71,7 +73,7 @@ def deactivate_poll(poll_id: int) -> Poll:
7173
poll = session.exec(statement).first()
7274
if not poll:
7375
raise ValueError(f"Poll with id {poll_id} not found")
74-
76+
7577
poll.is_active = False
7678
session.add(poll)
7779
session.commit()
@@ -93,7 +95,11 @@ def insert_poll_options(poll_options: List[PollOptionCreate]) -> List[PollOption
9395
def get_poll_options(poll_id: int) -> List[PollOption]:
9496
"""Get all options for a poll, ordered by display_order."""
9597
with Session(get_db_connection()) as session:
96-
statement = select(PollOption).where(PollOption.poll_id == poll_id).order_by(PollOption.display_order)
98+
statement = (
99+
select(PollOption)
100+
.where(PollOption.poll_id == poll_id)
101+
.order_by(PollOption.display_order)
102+
)
97103
return list(session.exec(statement).all())
98104

99105

@@ -103,10 +109,10 @@ def insert_poll_vote(vote_create: PollVoteCreate) -> PollVote:
103109
# Check if user already voted for this poll
104110
existing_vote_statement = select(PollVote).where(
105111
PollVote.poll_id == vote_create.poll_id,
106-
PollVote.slack_user_slack_id == vote_create.slack_user_slack_id
112+
PollVote.slack_user_slack_id == vote_create.slack_user_slack_id,
107113
)
108114
existing_vote = session.exec(existing_vote_statement).first()
109-
115+
110116
if existing_vote:
111117
# Update existing vote
112118
existing_vote.poll_option_id = vote_create.poll_option_id
@@ -149,4 +155,4 @@ def get_poll_voters_by_option(poll_id: int) -> dict:
149155
if vote.poll_option_id not in voters_by_option:
150156
voters_by_option[vote.poll_option_id] = []
151157
voters_by_option[vote.poll_option_id].append(vote.slack_user_slack_id)
152-
return voters_by_option
158+
return voters_by_option

src/friendly_computing_machine/models/poll.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import datetime
2-
from typing import List, Optional
2+
from typing import Optional
33

44
from sqlalchemy import Column, DateTime, func
55
from sqlmodel import Field
@@ -87,4 +87,4 @@ def to_poll_vote(self) -> PollVote:
8787
poll_option_id=self.poll_option_id,
8888
slack_user_slack_id=self.slack_user_slack_id,
8989
created_at=self.created_at,
90-
)
90+
)

0 commit comments

Comments
 (0)