-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
149 lines (114 loc) · 3.85 KB
/
app.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
146
147
148
149
# -*- coding:utf-8 -*-
from asyncio import gather, sleep
from linebot.v3.exceptions import InvalidSignatureError
from linebot.v3.webhooks import (
FollowEvent,
JoinEvent,
MemberJoinedEvent,
MessageEvent,
PostbackEvent,
StickerMessageContent,
TextMessageContent,
)
from sanic import (
HTTPResponse,
Request,
Sanic,
ServiceUnavailable,
Unauthorized,
empty,
redirect,
)
from ntpu_linebot import (
LINE_API_UTIL,
STICKER,
handle_follow_join_event,
handle_postback_event,
handle_sticker_message,
handle_text_message,
ntpu_contact,
ntpu_course,
ntpu_id,
)
app = Sanic(__name__)
@app.before_server_start
async def before_server_start(sanic: Sanic):
"""
Async function called before the server starts.
Args:
sanic (Sanic): The Sanic application instance.
"""
while not all(
await gather(
STICKER.load_stickers(),
ntpu_id.healthz(sanic),
ntpu_contact.healthz(sanic),
ntpu_course.healthz(sanic),
)
):
await sleep(1)
@app.route("/", methods=["HEAD", "GET"])
async def index(_: Request) -> HTTPResponse:
"""Redirects to the project GitHub page"""
return redirect("https://github.com/garyellow/ntpu-linebot")
@app.route("/healthz", methods=["HEAD", "GET"])
async def healthz(_: Request) -> HTTPResponse:
"""Checks the health status."""
return empty()
@app.route("/healthy", methods=["HEAD", "GET"])
async def healthy(request: Request) -> HTTPResponse:
"""
Asynchronous function for checking the health status of various services.
Args:
request (Request): The request object.
Returns:
HTTPResponse: Response object indicating the health status.
"""
if not await ntpu_id.healthz(request.app):
raise ServiceUnavailable("ID Service Unavailable")
if not await ntpu_contact.healthz(request.app):
raise ServiceUnavailable("Contact Service Unavailable")
if not await ntpu_course.healthz(request.app):
raise ServiceUnavailable("Course Service Unavailable")
return empty()
@app.route("/callback", methods=["POST"])
async def callback(request: Request) -> HTTPResponse:
"""
Handle LINE Bot webhook events.
Args:
request (Request): The request object representing the incoming webhook request.
Returns:
HTTPResponse: The response object indicating the success of the callback function.
Raises:
ServiceUnavailable: If any of the services (ID, Contact, Course) are unavailable.
Unauthorized: If the request signature is invalid.
"""
if not all(
await gather(
*[
ntpu_id.healthz(request.app),
ntpu_contact.healthz(request.app),
ntpu_course.healthz(request.app),
]
)
):
raise ServiceUnavailable("Service Unavailable")
try:
events = LINE_API_UTIL.parser.parse(
request.body.decode(),
request.headers.get("X-Line-Signature"),
)
for event in events:
await LINE_API_UTIL.loading_message(event.source.user_id)
if isinstance(event, MessageEvent):
if isinstance(event.message, TextMessageContent):
request.app.add_task(handle_text_message(event))
elif isinstance(event.message, StickerMessageContent):
request.app.add_task(handle_sticker_message(event))
elif isinstance(event, PostbackEvent):
request.app.add_task(handle_postback_event(event))
elif isinstance(event, (FollowEvent, JoinEvent, MemberJoinedEvent)):
request.app.add_task(handle_follow_join_event(event))
return empty()
except InvalidSignatureError as exc:
raise Unauthorized("Invalid signature") from exc