forked from hsuan1117/test_linebot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
374 lines (295 loc) · 11.2 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import json
import os
from math import floor
import qrcode
import requests
from PIL import Image, ImageFont
from PIL import ImageDraw
from uuid import uuid4
from barcode import EAN13, Code128
from barcode.writer import ImageWriter # 載入 barcode.writer 的 ImageWriter
from flask import Flask, request, abort, render_template, jsonify, redirect, url_for
from dotenv import load_dotenv
from future.backports.datetime import datetime
from linebot.v3 import (
WebhookHandler
)
from linebot.v3.exceptions import (
InvalidSignatureError
)
from linebot.v3.messaging import (
Configuration,
ApiClient,
MessagingApi,
ReplyMessageRequest,
TextMessage, TemplateMessage, ButtonsTemplate, MessageAction, URIAction, ImageMessage, PostbackAction, FlexMessage,
FlexCarousel
)
from linebot.v3.webhooks import (
MessageEvent,
TextMessageContent, PostbackEvent
)
from pillow_heif import register_heif_opener
from template import flex
app = Flask(__name__, static_folder='static')
load_dotenv()
configuration = Configuration(access_token=os.environ.get('LINE_CHANNEL_ACCESS_TOKEN'))
handler = WebhookHandler(os.environ.get('LINE_CHANNEL_SECRET'))
register_heif_opener()
@app.route("/callback", methods=['POST'])
def 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)
app.logger.info("Request body: " + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
app.logger.info("Invalid signature. Please check your channel access token/channel secret.")
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessageContent)
def handle_message(event):
with ApiClient(configuration) as api_client:
line_bot_api = MessagingApi(api_client)
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[
TemplateMessage(
alt_text='功能表',
template=ButtonsTemplate(
text='請選擇服務項目',
actions=[
PostbackAction(
label='會員卡',
displayText='顯示會員卡',
data='action=member_card'
),
]
)
),
FlexMessage(
alt_text='功能表',
contents=FlexCarousel.from_json(flex)
)
]
)
)
@handler.add(PostbackEvent)
def handle_postback(event):
with ApiClient(configuration) as api_client:
line_bot_api = MessagingApi(api_client)
if event.postback.data == 'action=member_card':
if os.path.exists('static/users.json'):
users = json.load(open('static/users.json'))
else:
users = []
userId = event.source.user_id
user_info = list(filter(lambda x: x["id"] == userId, users))
if len(user_info) == 0:
user_info = {
"id": userId,
"name": "未提供",
}
users.append(user_info)
with open("static/users.json", "w") as f:
json.dump(users, f)
else:
user_info = user_info[0]
gen_member_card(user_info["name"], userId)
uid = userId
line_bot_api.reply_message_with_http_info(
ReplyMessageRequest(
reply_token=event.reply_token,
messages=[
ImageMessage(
original_content_url=f"https://test-linebot.hsuan.app/static/card/{uid}.png",
preview_image_url=f"https://test-linebot.hsuan.app/static/card/{uid}.png"
),
ImageMessage(
original_content_url=f"https://test-linebot.hsuan.app/static/card/{uid}_qr.png",
preview_image_url=f"https://test-linebot.hsuan.app/static/card/{uid}_qr.png"
)
]
)
)
def gen_member_card(name, uid):
# Open an Image
img = Image.open("static/card.png")
if not os.path.exists("static/card"):
os.makedirs("static/card")
qr = qrcode.make(uid, border=1)
qr.save(f"static/card/{uid}_qr.png")
barcode = Code128(uid[1:].zfill(12), writer=ImageWriter())
barcode.save(f"static/card/{uid}_barcode")
avatar_path = f"static/avatar/{uid}"
if os.path.exists(avatar_path):
avatar = Image.open(f"static/avatar/{uid}", formats=["png", "jpeg"])
else:
avatar = Image.open("static/avatar/default.png")
base_width = 800
wpercent = (base_width / float(avatar.size[0]))
hsize = int((float(avatar.size[1]) * float(wpercent)))
avatar = avatar.resize((800, hsize))
img.paste(avatar, (300, 600))
# Call draw Method to add 2D graphics in an image
I1 = ImageDraw.Draw(img)
# Add Text to an image
I1.text((1800, 860), name, fill=(0, 0, 0), font=ImageFont.truetype('static/font.ttf', 64))
I1.text((1800, 980), uid, fill=(0, 0, 0), font=ImageFont.truetype('static/font.ttf', 64))
I1.text((1800, 1100), "綠星會員", fill=(0, 0, 0), font=ImageFont.truetype('static/font.ttf', 64))
# Resize the QR code
qr = qr.resize((400, 400))
# Paste the QR code into the image
img.paste(qr, (2400, 1300))
barcode = Image.open(f"static/card/{uid}_barcode.png")
img.paste(barcode, (1250, 1300))
# Save the edited image
img.save(f"static/card/{uid}.png")
@app.get('/api/admin/items')
def item_api_index():
if not os.path.exists("static/item.json"):
with open("static/item.json", "w") as f:
f.write("[]")
items = json.load(open("static/item.json"))
return jsonify(items)
@app.get('/profile')
def profile():
return render_template('profile.html')
@app.post('/api/admin/orders')
def order_api_create():
if not os.path.exists("static/order.json"):
with open("static/order.json", "w") as f:
f.write("[]")
if not os.path.exists("static/point.json"):
with open("static/point.json", "w") as f:
f.write("[]")
orders = json.load(open("static/order.json"))
points = json.load(open("static/point.json"))
order_id = str(uuid4())
orders.append({
"id": order_id,
"user_id": request.json["userId"],
"items": request.json["items"],
"total": request.json["total"],
})
point_record_id = str(uuid4())
points.append({
"id": point_record_id,
"user_id": request.json["userId"],
"description": f"消費 {request.json['total']} 元,獲得 {floor(request.json['total'] / 10)} 點",
"order_id": order_id,
"point": floor(request.json["total"] / 10),
"created_at": datetime.now().isoformat(),
})
with open("static/order.json", "w") as f:
json.dump(orders, f)
with open("static/point.json", "w") as f:
json.dump(points, f)
return jsonify(orders)
@app.get('/api/admin/orders')
def order_api_index():
if not os.path.exists("static/order.json"):
with open("static/order.json", "w") as f:
f.write("[]")
orders = json.load(open("static/order.json"))
items = json.load(open("static/item.json"))
# inner join name, price
for order in orders:
order["items"] = list(map(lambda x: {
"id": x["id"],
"qty": x["qty"],
"name": filter(lambda z: z["id"] == x["id"], items).__next__()["name"],
"price": filter(lambda z: z["id"] == x["id"], items).__next__()["price"],
}, order["items"]))
# for order in orders:
# order["items"] = json.load(open("static/item.json"))
# order["items"] = list(filter(lambda x: x["id"] in order["items"], order["items"]))
return jsonify(orders)
@app.post('/admin/items')
def item_create():
if not os.path.exists("static/item.json"):
with open("static/item.json", "w") as f:
f.write("[]")
items = json.load(open("static/item.json"))
item_id = str(uuid4())
request.files["image"].save(f"static/item/{item_id}.png")
items.append({
"id": item_id,
"name": request.form["name"],
"image": f"https://test-linebot.hsuan.app/static/item/{item_id}.png",
"price": request.form["price"],
})
with open("static/item.json", "w") as f:
json.dump(items, f)
return redirect("https://test-linebot.hsuan.app/admin/items")
@app.get('/api/points')
def point_index():
if not os.path.exists("static/point.json"):
with open("static/point.json", "w") as f:
f.write("[]")
if not os.path.exists("static/users.json"):
with open("static/users.json", "w") as f:
f.write("[]")
points = json.load(open("static/point.json"))
users = json.load(open("static/users.json"))
userId = request.headers.get("Authorization")
userId = userId.replace("Bearer ", "")
user_info = requests.post("https://api.line.me/oauth2/v2.1/verify", data={
"id_token": userId,
"client_id": os.environ.get("LINE_CHANNEL_ID"),
}).json()
userId = user_info["sub"]
user_db_info = list(filter(lambda x: x["id"] == userId, users))
if len(user_db_info) == 0:
users.append({
"id": userId,
"name": user_info["name"],
})
with open("static/users.json", "w") as f:
json.dump(users, f)
points = list(filter(lambda x: x["user_id"] == userId, points))
return jsonify(points)
@app.post('/profile/avatar')
def upload_avatar():
if not os.path.exists("static/avatar"):
os.makedirs("static/avatar")
if not os.path.exists("static/users.json"):
with open("static/users.json", "w") as f:
f.write("[]")
users = json.load(open("static/users.json"))
userId = request.form.get('token')
user_info = requests.post("https://api.line.me/oauth2/v2.1/verify", data={
"id_token": userId,
"client_id": os.environ.get("LINE_CHANNEL_ID"),
}).json()
print(user_info)
userId = user_info["sub"]
user_db = list(filter(lambda x: x["id"] == userId, users))
if len(user_db) == 0:
user_info = {
"id": userId,
"name": user_info["name"],
}
users.append(user_info)
with open("static/users.json", "w") as f:
json.dump(users, f)
else:
user_info = user_db[0]
request.files["avatar"].save(f"static/avatar/{userId}")
gen_member_card(user_info["name"], userId)
return redirect("https://test-linebot.hsuan.app/")
@app.get('/')
def index():
return render_template('index.html')
@app.get('/admin')
def admin():
return render_template('admin.html')
@app.get('/admin/items')
def item_index():
return render_template('manage/items.html')
if __name__ == "__main__":
app.run()