|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 | +# not use this file except in compliance with the License. You may obtain |
| 5 | +# a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 | +# License for the specific language governing permissions and limitations |
| 13 | +# under the License. |
| 14 | + |
| 15 | +import os |
| 16 | +import sys |
| 17 | + |
| 18 | +import aiohttp |
| 19 | + |
| 20 | +from fastapi import Request, FastAPI, HTTPException |
| 21 | + |
| 22 | + |
| 23 | +from linebot import ( |
| 24 | + AsyncLineBotApi, WebhookParser |
| 25 | +) |
| 26 | +from linebot.aiohttp_async_http_client import AiohttpAsyncHttpClient |
| 27 | +from linebot.exceptions import ( |
| 28 | + InvalidSignatureError |
| 29 | +) |
| 30 | +from linebot.models import ( |
| 31 | + MessageEvent, TextMessage, TextSendMessage, |
| 32 | +) |
| 33 | + |
| 34 | +# get channel_secret and channel_access_token from your environment variable |
| 35 | +channel_secret = os.getenv('LINE_CHANNEL_SECRET', None) |
| 36 | +channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None) |
| 37 | +if channel_secret is None: |
| 38 | + print('Specify LINE_CHANNEL_SECRET as environment variable.') |
| 39 | + sys.exit(1) |
| 40 | +if channel_access_token is None: |
| 41 | + print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.') |
| 42 | + sys.exit(1) |
| 43 | + |
| 44 | + |
| 45 | +app = FastAPI() |
| 46 | +session = aiohttp.ClientSession() |
| 47 | +async_http_client = AiohttpAsyncHttpClient(session) |
| 48 | +line_bot_api = AsyncLineBotApi(channel_access_token, async_http_client) |
| 49 | +parser = WebhookParser(channel_secret) |
| 50 | + |
| 51 | +@app.post("/callback") |
| 52 | +async def handle_callback(request: Request): |
| 53 | + signature = request.headers['X-Line-Signature'] |
| 54 | + |
| 55 | + # get request body as text |
| 56 | + body = await request.body() |
| 57 | + body = body.decode() |
| 58 | + |
| 59 | + try: |
| 60 | + events = parser.parse(body, signature) |
| 61 | + except InvalidSignatureError: |
| 62 | + raise HTTPException(status_code=400, detail="Invalid signature") |
| 63 | + |
| 64 | + for event in events: |
| 65 | + if not isinstance(event, MessageEvent): |
| 66 | + continue |
| 67 | + if not isinstance(event.message, TextMessage): |
| 68 | + continue |
| 69 | + |
| 70 | + await line_bot_api.reply_message( |
| 71 | + event.reply_token, |
| 72 | + TextSendMessage(text=event.message.text) |
| 73 | + ) |
| 74 | + |
| 75 | + return 'OK' |
0 commit comments