Skip to content

Commit eb571e4

Browse files
committed
refactor: rewrite discord message sending through httphook
1 parent c3ae79f commit eb571e4

File tree

5 files changed

+48
-37
lines changed

5 files changed

+48
-37
lines changed

dags/app/discord.py

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,24 @@
11
import logging
2-
from datetime import datetime, timedelta
2+
from datetime import datetime
33

44
import requests
5-
from airflow.sdk import Asset, AssetWatcher, Context, dag, task
5+
import tenacity
6+
from airflow.providers.http.hooks.http import HttpHook
7+
from airflow.sdk import Asset, AssetWatcher, Context, Variable, dag, task
68

79
from triggers.finance_report import FinanceReportTrigger
810

9-
logger = logging.getLogger(__name__)
11+
# get the airflow.task logger
12+
task_logger = logging.getLogger("airflow.task")
13+
1014

1115
finance_report_asset = Asset(
1216
name="finance_report",
1317
watchers=[
1418
AssetWatcher(
1519
name="finance_report_watcher",
1620
trigger=FinanceReportTrigger(
17-
# poke_interval=86400, # 60*60*24
18-
poke_interval=5, # 60*60*24
21+
poke_interval=86400, # 60*60*24
1922
),
2023
)
2124
],
@@ -37,31 +40,44 @@
3740
},
3841
)
3942
def discord_message_notification():
40-
"""Send Discord Message"""
43+
"""Send Discord Message."""
4144

42-
@task(
43-
retries=10,
44-
retry_delay=timedelta(seconds=10),
45-
)
45+
@task
4646
def send_discord_message(**context: Context) -> None:
4747
triggering_asset_events = context["triggering_asset_events"]
48-
session = requests.session()
49-
logger.info(f"Receive asset events {triggering_asset_events}")
5048
for asset_uri, asset_events in triggering_asset_events.items():
51-
logger.info(f"Receive asset event from Asset uri={asset_uri}")
49+
task_logger.info(f"Receive asset event from Asset uri={asset_uri}")
50+
51+
http_hook = HttpHook(method="POST", http_conn_id="discord_webhook")
5252
for asset_event in asset_events: # type: ignore[attr-defined]
5353
if asset_event.extra.get("from_trigger", False):
5454
details = asset_event.extra["payload"]
5555
else:
5656
details = asset_event.extra
5757

58-
session.post(
59-
details.get("webhook_url"),
60-
json={
58+
if not details:
59+
task_logger.error(
60+
f"Detail {details} cannot be empty. It's required to send discord message."
61+
)
62+
continue
63+
64+
task_logger.info("Start sending discord message")
65+
endpoint = Variable.get(details.get("webhook_endpoint_key"))
66+
http_hook.run_with_advanced_retry(
67+
endpoint=endpoint,
68+
data={
6169
"username": details.get("username"),
6270
"content": details.get("content"),
6371
},
72+
_retry_args=dict(
73+
wait=tenacity.wait_random(min=1, max=10),
74+
stop=tenacity.stop_after_attempt(10),
75+
retry=tenacity.retry_if_exception_type(
76+
requests.exceptions.ConnectionError
77+
),
78+
),
6479
)
80+
task_logger.info("Discord message sent")
6581

6682
send_discord_message()
6783

dags/app/proposal_reminder/dag.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
Send Proposal Summary to Discord
33
"""
44

5-
from airflow.sdk import Metadata, Variable, asset
5+
from airflow.sdk import Metadata, asset
66
from app.proposal_reminder.udf import get_proposal_summary
77

88
# DEFAULT_ARGS = {
@@ -16,19 +16,17 @@
1616

1717

1818
@asset(
19-
name="proposal_count",
20-
dag_id="proposal_count",
2119
schedule="0 16 * * *", # At 16:00 (00:00 +8)
2220
)
23-
def DISCORD_PROPOSAL_REMINDER_v3(self):
21+
def proposal_count(self):
2422
summary = get_proposal_summary()
2523
n_talk = summary["num_proposed_talk"]
2624
n_tutorial = summary["num_proposed_tutorial"]
2725

2826
yield Metadata(
2927
self,
3028
extra={
31-
"webhook_url": Variable.get("DISCORD_PROGRAM_REMINDER_WEBHOOK"),
29+
"webhook_endpoint_key": "DISCORD_PROGRAM_REMINDER_WEBHOOK",
3230
"username": "Program talk reminder",
3331
"content": f"目前投稿議程數: {n_talk}; 課程數: {n_tutorial}",
3432
},

dags/app/team_registration_bot/dag.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22
Send daily ordering metrics to discord channel
33
"""
44

5-
from airflow.sdk import Metadata, Variable, asset
5+
from airflow.sdk import Metadata, asset
66
from app.team_registration_bot.udf import (
7-
_compose_discord_msg,
8-
_get_statistics_from_bigquery,
7+
compose_discord_msg,
8+
get_statistics_from_bigquery,
99
)
1010

1111
# DEFAULT_ARGS = {
@@ -18,18 +18,15 @@
1818
# }
1919

2020

21-
@asset(
22-
name="registration_statistics",
23-
dag_id="registration_statistics",
24-
schedule="@daily",
25-
)
26-
def KKTIX_DISCORD_BOT_FOR_TEAM_REGISTRATION(self):
27-
statistics = _get_statistics_from_bigquery()
21+
@asset(schedule="@daily")
22+
def registration_statistics(self):
23+
# KKTIX_DISCORD_BOT_FOR_TEAM_REGISTRATION
24+
statistics = get_statistics_from_bigquery()
2825
yield Metadata(
2926
self,
3027
extra={
31-
"webhook_url": Variable.get("discord_webhook_registration_endpoint"),
28+
"webhook_endpoint_key": "discord_webhook_registration_endpoint",
3229
"username": "KKTIX order report",
33-
"content": _compose_discord_msg(statistics),
30+
"content": compose_discord_msg(statistics),
3431
},
3532
)

dags/app/team_registration_bot/udf.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
CLIENT = bigquery.Client(project=os.getenv("BIGQUERY_PROJECT"))
1212

1313

14-
def _get_statistics_from_bigquery() -> RowIterator:
14+
def get_statistics_from_bigquery() -> RowIterator:
1515
query_job = CLIENT.query(
1616
f"""
1717
WITH UNIQUE_RECORDS AS (
@@ -55,10 +55,10 @@ def _get_statistics_from_bigquery() -> RowIterator:
5555
}
5656

5757

58-
def _compose_discord_msg(payload) -> str:
58+
def compose_discord_msg(payload) -> str:
5959
msg = (
6060
f"Hi 這是今天 {datetime.now().date()} 的票種統計資料,"
61-
"售票期結束後,請 follow README 的 `gcloud` 指令進去把 Airflow DAG 關掉\n\n"
61+
"售票期結束後,請 follow README 的 `gcloud` 指令進去把 Airflow dag 關掉\n\n"
6262
)
6363
total = 0
6464
total_income = 0

triggers/finance_report.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ async def run(self) -> AsyncIterator[TriggerEvent]:
125125
msg = format_diff_df_as_message(df_diff)
126126
yield TriggerEvent(
127127
{
128-
"webhook_url": Variable.get("discord_data_stratagy_webhook"),
128+
"webhook_endpoint_key": "discord_data_stratagy_webhook",
129129
"username": "財務機器人",
130130
"content": msg,
131131
}

0 commit comments

Comments
 (0)