-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
247 lines (202 loc) · 7.52 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
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
"""
AidenBot: Multi-purpose bot for LINE messaging app.
(c) 2017-2019 laymonage
"""
import errno
import os
import sys
from flask import Flask, request, abort
from flask.logging import create_logger
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError, LineBotApiError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage, ImageSendMessage,
SourceGroup, SourceRoom, FileMessage, UnfollowEvent, LeaveEvent
)
from helper._handler import command_handler
from helper.bencoin import penangan_operasi
from helper.file import mirror
APP = Flask(__name__)
LOG = create_logger(APP)
# Get CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN from environment variable
CHANNEL_SECRET = os.getenv('LINE_CHANNEL_SECRET', None)
CHANNEL_ACCESS_TOKEN = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
if CHANNEL_SECRET is None:
print('Specify LINE_CHANNEL_SECRET as environment variable.')
sys.exit(1)
if CHANNEL_ACCESS_TOKEN is None:
print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
sys.exit(1)
AIDEN = LineBotApi(CHANNEL_ACCESS_TOKEN)
HANDLER = WebhookHandler(CHANNEL_SECRET)
MAXIMUM_MIRROR_SIZE = 52428800
STATIC_TMP_PATH = os.path.join(os.path.dirname(__file__), 'static', 'tmp')
MY_ID = os.getenv('MY_USER_ID', None)
MYSELF = AIDEN.get_profile(MY_ID)
def make_static_tmp_dir():
"""Create temporary directory for download content."""
try:
os.makedirs(STATIC_TMP_PATH)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(STATIC_TMP_PATH):
pass
else:
raise
@APP.route("/callback", methods=['POST'])
def callback():
"""Handle webhook callback."""
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
LOG.info(("Request body: ", body))
# handle webhook body
try:
HANDLER.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK'
def get_profile_and_set_id(event):
"""Return the profile and set_id (mid) of an event's source."""
if isinstance(event.source, SourceGroup):
profile = AIDEN.get_group_member_profile(event.source.group_id,
event.source.user_id)
set_id = event.source.group_id
elif isinstance(event.source, SourceRoom):
profile = AIDEN.get_room_member_profile(event.source.room_id,
event.source.user_id)
set_id = event.source.room_id
else:
profile = AIDEN.get_profile(event.source.user_id)
set_id = event.source.user_id
return (profile, set_id)
def compose_reply_content(*msgs, mode=('text',)*5):
"""Compose a reply content with msgs."""
msgs = msgs[:5]
content = []
for idx, msg in enumerate(msgs):
if mode[idx] == 'text':
if isinstance(msg, (tuple, list)):
content = [TextSendMessage(text=item) for item in msg]
else:
content.append(TextSendMessage(text=msg))
elif mode[idx] == 'image':
if isinstance(msg, (tuple, list)):
content = [
ImageSendMessage(
original_content_url=item, preview_image_url=item
)
for item in msg
]
else:
content.append(ImageSendMessage(
original_content_url=msg,
preview_image_url=msg))
elif mode[idx] == 'custimg':
if isinstance(msg, (tuple, list)):
content = [
ImageSendMessage(
original_content_url=item[0],
preview_image_url=item[1]
)
for item in msg
]
else:
content.append(ImageSendMessage(
original_content_url=msg[0],
preview_image_url=msg[1]))
return content
@HANDLER.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
"""Handle a text message event."""
text = event.message.text
subject, set_id = get_profile_and_set_id(event)
def quickreply(*msgs, mode=('text',)*5):
"""Reply the message with msgs."""
AIDEN.reply_message(
event.reply_token, compose_reply_content(*msgs, mode=mode)
)
def bye():
"""Leave a chat room."""
if isinstance(event.source, SourceGroup):
quickreply("Leaving group...")
AIDEN.leave_group(event.source.group_id)
elif isinstance(event.source, SourceRoom):
quickreply("Leaving room...")
AIDEN.leave_room(event.source.room_id)
else:
quickreply("I can't leave a 1:1 chat.")
def getprofile():
"""Send display name and status message of a user."""
result = ("Display name: " + subject.display_name + "\n"
"Profile picture: " + subject.picture_url)
try:
profile = AIDEN.get_profile(event.source.user_id)
if profile.status_message:
result += "\n" + "Status message: " + profile.status_message
except LineBotApiError:
pass
quickreply(result)
if text[0] == '/':
command = text[1:]
result = command_handler(command, subject, MYSELF, set_id)
if command.lower().strip().startswith('bye'):
bye()
elif command.lower().strip().startswith('profile'):
getprofile()
elif result:
if result[0] in ('text', 'image', 'custimg'):
quickreply(*result[1:], mode=(result[0],)*len(result[1:]))
elif result[0] == 'multi':
mode, content = [], []
for item in result[1]:
mode.append(item[0])
content.append(item[1])
quickreply(*content, mode=mode)
else:
quickreply(result)
elif text.split()[0] in ('DAFTAR', 'TAMBAH', 'UBAH', 'SETOR',
'INFO', 'TRANSFER', 'TARIK', 'BANTUAN'):
quickreply(penangan_operasi(event.source.user_id, text.strip()))
@HANDLER.add(MessageEvent, message=FileMessage)
def handle_file_message(event):
"""Handle file message event."""
message_content = AIDEN.get_message_content(event.message.id)
if isinstance(event.source, SourceGroup):
set_id = event.source.group_id
elif isinstance(event.source, SourceRoom):
set_id = event.source.room_id
else:
set_id = event.source.user_id
link = mirror(message_content, event.message.file_name,
request.host_url, set_id)
if not link:
return
file_size = int(message_content.response.headers['Content-Length'])
if file_size > MAXIMUM_MIRROR_SIZE:
AIDEN.reply_message(
event.reply_token,
TextSendMessage(text="File size shouldn't exceed 50 MB.")
)
AIDEN.reply_message(
event.reply_token, [
TextSendMessage(text="Mirror:"),
TextSendMessage(text=link)
]
)
@HANDLER.add(UnfollowEvent)
def handle_unfollow():
"""Handle unfollow event."""
LOG.info("Got Unfollow event")
@HANDLER.add(LeaveEvent)
def handle_leave():
"""Handle leave event."""
LOG.info("Got leave event")
if __name__ == "__main__":
make_static_tmp_dir()
PORT = int(os.getenv('PORT', '5000'))
APP.run(host='0.0.0.0', port=PORT)