Skip to content

Instantly share code, notes, and snippets.

@okdtsk
Last active January 12, 2021 13:47
Show Gist options
  • Select an option

  • Save okdtsk/af70f33e2197b759848df8d6a800ce0a to your computer and use it in GitHub Desktop.

Select an option

Save okdtsk/af70f33e2197b759848df8d6a800ce0a to your computer and use it in GitHub Desktop.
line-botsdk-python example for pycon
{
"version": "2.0",
"app_name": "./line-bot-for-pycon",
"stages": {
"dev": {
"api_gateway_stage": "dev",
"environment_variables": {
"LINEBOT_CHANNEL_ACCESS_TOKEN": "blahblahblah",
"LINEBOT_CHANNEL_SECRET": "blahblahblah"
}
},
"prod": {
"api_gateway_stage": "prod",
"environment_variables": {
"LINEBOT_CHANNEL_ACCESS_TOKEN": "blahblahblah",
"LINEBOT_CHANNEL_SECRET": "blahblahblah"
}
}
}
}
#!/usr/bin/env python
import os
from chalice import Chalice
from chalice import Response
from linebot import LineBotApi
from linebot import WebhookHandler
from linebot.models import MessageEvent
from linebot.models import TextMessage
from linebot.models import TextSendMessage
from linebot.exceptions import InvalidSignatureError
from linebot.exceptions import LineBotApiError
app = Chalice(app_name='line-bot')
line_bot_api = LineBotApi(os.environ['LINEBOT_CHANNEL_ACCESS_TOKEN'])
handler = WebhookHandler(os.environ['LINEBOT_CHANNEL_SECRET'])
@app.route('/callback', methods=['POST'])
def callback():
signature = app.current_request.headers['X-Line-Signature']
body = app.current_request.raw_body.decode('utf-8')
try:
handler.handle(body, signature)
except InvalidSignatureError as e:
return Response({'ok': False,
'error': e.message},
status_code=400)
except LineBotApiError as e:
return Response({'ok': False,
'error': 'Failed {}'.format(e)},
status_code=500)
return Response({'ok': True})
@handler.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
# Ignore a request for verification
# (when pressing 'VERIFY' button in developers console)
if event.reply_token in ('00000000000000000000000000000000',
'ffffffffffffffffffffffffffffffff'):
return
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.message.text)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment