Skip to content

Commit a157982

Browse files
authored
[25.08.07 / TASK-240] Feature - 주간 배치의 결과를 슬랙으로 알림 (#41)
* feature: 주간 뉴스레터 배치의 결과를 슬랙으로 알림 * feature: 주간 분석 배치의 결과를 슬랙으로 알림 * modify: 파일 저장시 try-catch문 적용 * feature: gitignore에 결과 텍스트 파일 추가
1 parent 4afca35 commit a157982

File tree

6 files changed

+102
-16
lines changed

6 files changed

+102
-16
lines changed

.github/workflows/run-weekly-analysis.yaml

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,15 +75,41 @@ jobs:
7575
7676
# KST 시간을 GitHub Actions 환경 변수에 세팅
7777
- name: Get Current KST Time
78+
if: always()
7879
run: echo "KST_TIME=$(TZ=Asia/Seoul date +'%Y-%m-%d %H:%M:%S')" >> $GITHUB_ENV
7980

81+
# 결과 파일 읽기
82+
- name: Read Result Output
83+
if: always()
84+
id: read-result
85+
run: |
86+
if [ -f weekly_analysis_result.txt ]; then
87+
RESULT=$(cat weekly_analysis_result.txt)
88+
echo "RESULT<<EOF" >> $GITHUB_OUTPUT
89+
echo "$RESULT" >> $GITHUB_OUTPUT
90+
echo "EOF" >> $GITHUB_OUTPUT
91+
else
92+
echo "RESULT=No output file found" >> $GITHUB_OUTPUT
93+
fi
94+
95+
- name: Send Slack Notification on Success
96+
if: success()
97+
uses: slackapi/slack-github-action@v1.24.0
98+
with:
99+
payload: |
100+
{
101+
"text": "*Weekly Analysis Batch*\n\n✅ *Status:* Success\n📅 *Timestamp (KST):* ${{ env.KST_TIME }}\n📝 *Result:* \n```${{ steps.read-result.outputs.RESULT }}```\n🔗 *Workflow URL:* <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Workflow>"
102+
}
103+
env:
104+
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
105+
80106
- name: Send Slack Notification on Failure
81107
if: failure()
82108
uses: slackapi/slack-github-action@v1.24.0
83109
with:
84110
payload: |
85111
{
86-
"text": "*Weekly Analysis Batch*\n\n❌ *Status:* Failure\n📅 *Timestamp (KST):* ${{ env.KST_TIME }}\n🔗 *Workflow URL:* <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Workflow>"
112+
"text": "*Weekly Analysis Batch*\n\n❌ *Status:* Failure\n📅 *Timestamp (KST):* ${{ env.KST_TIME }}\n📝 *Result:* \n```${{ steps.read-result.outputs.RESULT }}```\n🔗 *Workflow URL:* <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Workflow>"
87113
}
88114
env:
89115
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}

.github/workflows/run-weekly-newsletter.yaml

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,15 +71,41 @@ jobs:
7171
7272
# KST 시간을 GitHub Actions 환경 변수에 세팅
7373
- name: Get Current KST Time
74+
if: always()
7475
run: echo "KST_TIME=$(TZ=Asia/Seoul date +'%Y-%m-%d %H:%M:%S')" >> $GITHUB_ENV
7576

77+
# 결과 파일 읽기
78+
- name: Read Result Output
79+
if: always()
80+
id: read-result
81+
run: |
82+
if [ -f newsletter_batch_result.txt ]; then
83+
RESULT=$(cat newsletter_batch_result.txt)
84+
echo "RESULT<<EOF" >> $GITHUB_OUTPUT
85+
echo "$RESULT" >> $GITHUB_OUTPUT
86+
echo "EOF" >> $GITHUB_OUTPUT
87+
else
88+
echo "RESULT=No output file found" >> $GITHUB_OUTPUT
89+
fi
90+
91+
- name: Send Slack Notification on Success
92+
if: success()
93+
uses: slackapi/slack-github-action@v1.24.0
94+
with:
95+
payload: |
96+
{
97+
"text": "*Weekly Newsletter Batch*\n\n✅ *Status:* Success\n📅 *Timestamp (KST):* ${{ env.KST_TIME }}\n📝 *Result:* \n```${{ steps.read-result.outputs.RESULT }}```\n🔗 *Workflow URL:* <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Workflow>"
98+
}
99+
env:
100+
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
101+
76102
- name: Send Slack Notification on Failure
77103
if: failure()
78104
uses: slackapi/slack-github-action@v1.24.0
79105
with:
80106
payload: |
81107
{
82-
"text": "*Weekly Newsletter Batch*\n\n❌ *Status:* Failure\n📅 *Timestamp (KST):* ${{ env.KST_TIME }}\n🔗 *Workflow URL:* <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Workflow>"
108+
"text": "*Weekly Newsletter Batch*\n\n❌ *Status:* Failure\n📅 *Timestamp (KST):* ${{ env.KST_TIME }}\n📝 *Result:* \n```${{ steps.read-result.outputs.RESULT }}```\n🔗 *Workflow URL:* <${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View Workflow>"
83109
}
84110
env:
85111
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# CUSTOM
22
**/timescale_data/**
3-
3+
*_result.txt
44

55
# Created by https://www.toptal.com/developers/gitignore/api/macos,python,pycharm,django
66
# Edit at https://www.toptal.com/developers/gitignore?templates=macos,python,pycharm,django

insight/tasks/weekly_newsletter_batch.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -510,23 +510,41 @@ def run(self) -> None:
510510
if (total_processed + total_failed) > 0
511511
else 0
512512
)
513+
elapsed_time = (get_local_now() - start_time).total_seconds()
513514

514515
if total_processed > total_failed:
515516
# 과반수 이상 성공시에만 processed로 마킹
516517
self._update_weekly_trend_result()
517518
logger.info(
518-
f"Newsletter batch process completed successfully in {(get_local_now() - start_time).total_seconds()} seconds. "
519+
f"Newsletter batch process completed successfully in {elapsed_time} seconds. "
519520
f"Processed: {total_processed}, Failed: {total_failed}, Success Rate: {success_rate:.2%}"
520521
)
521522
else:
522523
logger.warning(
523-
f"Newsletter batch process failed to meet success criteria in {(get_local_now() - start_time).total_seconds()} seconds. "
524+
f"Newsletter batch process failed to meet success criteria in {elapsed_time} seconds. "
524525
f"Processed: {total_processed}, Failed: {total_failed}, Success Rate: {success_rate:.2%}. "
525526
f"WeeklyTrend remains unprocessed due to low success rate (< 50%)"
526527
)
527528

529+
# 결과 파일 저장 (for slack notification)
530+
try:
531+
with open("newsletter_batch_result.txt", "w") as f:
532+
f.write(
533+
f"✅ 뉴스레터 발송 완료: 성공 {total_processed}명, 실패 {total_failed}\\n"
534+
)
535+
f.write(f" - 소요 시간: {elapsed_time}\\n")
536+
f.write(f" - 성공률: {success_rate:.2%}\\n")
537+
except Exception as e:
538+
logger.error(f"Failed to save newsletter batch result: {e}")
539+
528540
except Exception as e:
529541
logger.error(f"Newsletter batch process failed: {e}")
542+
try:
543+
with open("newsletter_batch_result.txt", "w") as f:
544+
f.write(f"❌ 뉴스레터 발송 실패: {e}")
545+
except Exception as e:
546+
logger.error(f"Failed to save newsletter batch result: {e}")
547+
530548
raise
531549

532550

insight/tasks/weekly_trend_analysis.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,9 +195,17 @@ async def main():
195195
result = await analyzer.run()
196196

197197
if result.success:
198-
print(f"✅ 주간 트렌드 분석 완료: {result.metadata}")
198+
try:
199+
with open("weekly_analysis_result.txt", "w") as f:
200+
f.write(f"✅ 주간 트렌드 분석 완료: {result.metadata}\\n")
201+
except Exception as e:
202+
print(f"결과 파일 저장 실패: {e}")
199203
else:
200-
print(f"❌ 주간 트렌드 분석 실패: {result.error}")
204+
try:
205+
with open("weekly_analysis_result.txt", "w") as f:
206+
f.write(f"❌ 주간 트렌드 분석 실패: {result.error}\\n")
207+
except Exception as e:
208+
print(f"결과 파일 저장 실패: {e}")
201209
return 1
202210

203211
return 0

insight/tasks/weekly_user_trend_analysis.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -520,16 +520,24 @@ async def main():
520520
successful = metadata.get("successful_users", 0)
521521
expired = metadata.get("expired_token_users", 0)
522522

523-
print("✅ 사용자 주간 분석 완료")
524-
print(f" - 성공: {successful}명")
525-
print(f" - 토큰 만료: {expired}명")
526-
527-
if expired > 0:
528-
print(
529-
f" ⚠️ 토큰 만료 사용자: {metadata.get('expired_user_ids', [])}"
530-
)
523+
# 결과 파일 저장 (for slack notification)
524+
try:
525+
with open("weekly_analysis_result.txt", "a") as f:
526+
f.write(
527+
f"✅ 사용자 주간 분석 완료: 성공 {successful}명, 토큰 만료 {expired}\\n"
528+
)
529+
f.write(
530+
f" - 토큰 만료 사용자: {metadata.get('expired_user_ids', [])}"
531+
)
532+
except Exception as e:
533+
print(f"결과 파일 저장 실패: {e}")
531534
else:
532-
print(f"❌ 사용자 주간 분석 실패: {result.error}")
535+
try:
536+
with open("weekly_analysis_result.txt", "a") as f:
537+
f.write(f"❌ 사용자 주간 분석 실패: {result.error}")
538+
except Exception as e:
539+
print(f"결과 파일 저장 실패: {e}")
540+
533541
return 1
534542

535543
return 0

0 commit comments

Comments
 (0)