|
| 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 | +from argparse import ArgumentParser |
| 18 | + |
| 19 | +import asyncio |
| 20 | +import aiohttp |
| 21 | +from aiohttp import web |
| 22 | + |
| 23 | +import logging |
| 24 | + |
| 25 | +from aiohttp.web_runner import TCPSite |
| 26 | + |
| 27 | +from linebot import ( |
| 28 | + AsyncLineBotApi, WebhookParser |
| 29 | +) |
| 30 | +from linebot.aiohttp_async_http_client import AiohttpAsyncHttpClient |
| 31 | +from linebot.exceptions import ( |
| 32 | + InvalidSignatureError |
| 33 | +) |
| 34 | +from linebot.models import ( |
| 35 | + MessageEvent, TextMessage, TextSendMessage, |
| 36 | +) |
| 37 | + |
| 38 | +# get channel_secret and channel_access_token from your environment variable |
| 39 | +channel_secret = os.getenv('LINE_CHANNEL_SECRET', None) |
| 40 | +channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None) |
| 41 | +if channel_secret is None: |
| 42 | + print('Specify LINE_CHANNEL_SECRET as environment variable.') |
| 43 | + sys.exit(1) |
| 44 | +if channel_access_token is None: |
| 45 | + print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.') |
| 46 | + sys.exit(1) |
| 47 | + |
| 48 | + |
| 49 | +class Handler: |
| 50 | + def __init__(self, line_bot_api, parser): |
| 51 | + self.line_bot_api = line_bot_api |
| 52 | + self.parser = parser |
| 53 | + |
| 54 | + async def echo(self, request): |
| 55 | + signature = request.headers['X-Line-Signature'] |
| 56 | + body = await request.text() |
| 57 | + |
| 58 | + try: |
| 59 | + events = self.parser.parse(body, signature) |
| 60 | + except InvalidSignatureError: |
| 61 | + return web.Response(status=400, text='Invalid signature') |
| 62 | + |
| 63 | + for event in events: |
| 64 | + if not isinstance(event, MessageEvent): |
| 65 | + continue |
| 66 | + if not isinstance(event.message, TextMessage): |
| 67 | + continue |
| 68 | + |
| 69 | + await self.line_bot_api.reply_message( |
| 70 | + event.reply_token, |
| 71 | + TextSendMessage(text=event.message.text) |
| 72 | + ) |
| 73 | + |
| 74 | + return web.Response(text="OK\n") |
| 75 | + |
| 76 | + |
| 77 | +async def main(port=8000): |
| 78 | + session = aiohttp.ClientSession() |
| 79 | + async_http_client = AiohttpAsyncHttpClient(session) |
| 80 | + line_bot_api = AsyncLineBotApi(channel_access_token, async_http_client) |
| 81 | + parser = WebhookParser(channel_secret) |
| 82 | + |
| 83 | + handler = Handler(line_bot_api, parser) |
| 84 | + |
| 85 | + app = web.Application() |
| 86 | + app.add_routes([web.post('/callback', handler.echo)]) |
| 87 | + |
| 88 | + runner = web.AppRunner(app) |
| 89 | + await runner.setup() |
| 90 | + site = TCPSite(runner=runner, port=port) |
| 91 | + await site.start() |
| 92 | + while True: |
| 93 | + await asyncio.sleep(3600) # sleep forever |
| 94 | + |
| 95 | + |
| 96 | +if __name__ == "__main__": |
| 97 | + logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) |
| 98 | + |
| 99 | + arg_parser = ArgumentParser( |
| 100 | + usage='Usage: python ' + __file__ + ' [--port <port>] [--help]' |
| 101 | + ) |
| 102 | + arg_parser.add_argument('-p', '--port', type=int, default=8000, help='port') |
| 103 | + options = arg_parser.parse_args() |
| 104 | + |
| 105 | + asyncio.run(main(options.port)) |
0 commit comments