【Python】【LINE Bot】 앵무새 반환 LINE Bot 만들기
12764 단어 경 6파이썬LINEmessagingAPIlinebotGit
그냥 앵무새를 반환하는 LINE Bot을 만들어 보았습니다.
![](https://s1.md5.ltd/image/b40597aca91825e38237339106622a1a.png)
1.LineMessagingAPI 채널을 만들기
LINE Developers로 채널 만들기
기본적으로 다음 공식 페이지에 따라 특별히 문제없이 등록할 수 있어야 합니다.
Messaging API를 사용하려면 | LINE Developers
![](https://s1.md5.ltd/image/095ffd304cb0e5d4a10169ada43a3b0f.png)
무사 채널이 등록할 수 있으면 ↓와 같은 상태로
![](https://s1.md5.ltd/image/5d78bede191a7748dd034343a5f5efce.png)
나중에 필요하므로 다음 두 가지를 확인하십시오.
Channel secret ← Basic Setting 탭 안에 있습니다
Channel access token (long-lived) ← MessagingAPI 탭 안에 있습니다
2. 에 6
계정 만들기
기본적으로 다음 공식 페이지에 따라 특별히 문제없이 등록할 수 있어야 합니다.
Heroku Dev Center
![](https://s1.md5.ltd/image/25feeae1f3bbc279fbf95b22d1f7391f.png)
Heroku CLI 다운로드
다음 페이지에서 Heroku CLI 다운로드 및 설치
The Heroku CLI | Heroku Dev Center
![](https://s1.md5.ltd/image/a7ebcf0ec0ced3c9de48df506a14c411.png)
성공적인 설치가 완료되면 터미널에서 heroku 명령을 사용할 수 있어야합니다.
![](https://s1.md5.ltd/image/6f427eac2cf16eb87fff42e4348d30f7.png)
3. 배포할 파일 만들기
파일 구성
다음 구성으로 파일 만들기
![](https://s1.md5.ltd/image/32a92b9f9ffc4486794fd7f2997cd3a8.png)
마인. py
프로그램의 본체 부분
main.py# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import sys
from argparse import ArgumentParser
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)
app = Flask(__name__)
# get channel_secret and channel_access_token from your 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)
line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)
@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:
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessage)
def message_text(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.message.text)
)
if __name__ == "__main__":
port = int(os.getenv("PORT", 5000))
app.run(host="0.0.0.0", port=port)
Procfile
프로그램 실행 방법
web: python main.py
requirements.txt
사용할 모듈
Flask==0.12.2
line-bot-sdk==1.8.0
runtime.txt
파이썬 버전 설명
python-3.6.6
4.Heroku에 배포
git 저장소를 만들고 커밋
터미널 등에서 다음 명령을 실행합니다.
$ cd line-bot
$ git init
$ git config user.name "名前"
$ git config user.email メールアドレス
$ git add .
$ git commit -m "コメント"
$ cd line-bot : 루트 디렉토리로 이동
$ git init : git 저장소 초기화
$ git config user.name "이름": config 설정
$ git config user.email 이메일 주소 : config 설정
$ git add . : 추가
$ git commit -m "댓글": 커밋
Heroku에 로그인
다음 명령을 실행하여 Heroku에 로그인
$ heroku login
실행하면 아래와 같은 상태가 되므로 무언가 키를 누르면 브라우저에서 로그인 화면이 표시되므로,
Log In 버튼을 클릭하여 로그인 상태로 전환
![](https://s1.md5.ltd/image/184bdf8cebd2fe53730e5aaa879c1a83.png)
![](https://s1.md5.ltd/image/f78fceaa922f4d31d2fd693f81170f72.png)
애플리케이션을 만들고 배포
다음 명령을 실행하여 Heroku에 응용 프로그램 만들기 및 배포
$ heroku create アプリケーション名
$ heroku config:set LINE_CHANNEL_SECRET="Channel Secret" --app アプリケーション名
$ heroku config:set LINE_CHANNEL_ACCESS_TOKEN="アクセストークン" --app アプリケーション名
$ git push heroku master
애플리케이션 이름은 임의의 이름입니다.
'Channel Secret'과 '액세스 토큰'은 LINE Developers에서 채널을 만들 때 확인한 것을 설정한다.
build pack 설정
build pack 의 설정을 할 수 없으면 배포에 실패하는 경우가 있다.
이 경우 다음 명령을 실행하여 빌드 팩을 설정하십시오.
$ heroku buildpacks:set heroku/python
5.LINE Bot 측에서 webhook 설정
LineDevelopers 콘솔에서 만든 채널의 웹 후크 설정 설정
Webhook을 사용하고 webhook URL에 다음 URL을 지정하십시오.
https://アプリケーション名.herokuapp.com/callback
완성
여기까지의 작업이 완료되면 앵무새 돌려주는 봇이 완성되었습니다!
Heroku도 Git도 MessagingAPI도 사용한 적이 없는 초보자였지만, 의외로 간단하게 작성할 수 있었습니다
앞으로는 이것을 바탕으로 무언가를 만들 수 있으면 좋겠다.
Reference
이 문제에 관하여(【Python】【LINE Bot】 앵무새 반환 LINE Bot 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/pon187/items/7adb5504ab31af5ef52e
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
계정 만들기
기본적으로 다음 공식 페이지에 따라 특별히 문제없이 등록할 수 있어야 합니다.
Heroku Dev Center
![](https://s1.md5.ltd/image/25feeae1f3bbc279fbf95b22d1f7391f.png)
Heroku CLI 다운로드
다음 페이지에서 Heroku CLI 다운로드 및 설치
The Heroku CLI | Heroku Dev Center
![](https://s1.md5.ltd/image/a7ebcf0ec0ced3c9de48df506a14c411.png)
성공적인 설치가 완료되면 터미널에서 heroku 명령을 사용할 수 있어야합니다.
![](https://s1.md5.ltd/image/6f427eac2cf16eb87fff42e4348d30f7.png)
3. 배포할 파일 만들기
파일 구성
다음 구성으로 파일 만들기
![](https://s1.md5.ltd/image/32a92b9f9ffc4486794fd7f2997cd3a8.png)
마인. py
프로그램의 본체 부분
main.py# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import sys
from argparse import ArgumentParser
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)
app = Flask(__name__)
# get channel_secret and channel_access_token from your 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)
line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)
@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:
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessage)
def message_text(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.message.text)
)
if __name__ == "__main__":
port = int(os.getenv("PORT", 5000))
app.run(host="0.0.0.0", port=port)
Procfile
프로그램 실행 방법
web: python main.py
requirements.txt
사용할 모듈
Flask==0.12.2
line-bot-sdk==1.8.0
runtime.txt
파이썬 버전 설명
python-3.6.6
4.Heroku에 배포
git 저장소를 만들고 커밋
터미널 등에서 다음 명령을 실행합니다.
$ cd line-bot
$ git init
$ git config user.name "名前"
$ git config user.email メールアドレス
$ git add .
$ git commit -m "コメント"
$ cd line-bot : 루트 디렉토리로 이동
$ git init : git 저장소 초기화
$ git config user.name "이름": config 설정
$ git config user.email 이메일 주소 : config 설정
$ git add . : 추가
$ git commit -m "댓글": 커밋
Heroku에 로그인
다음 명령을 실행하여 Heroku에 로그인
$ heroku login
실행하면 아래와 같은 상태가 되므로 무언가 키를 누르면 브라우저에서 로그인 화면이 표시되므로,
Log In 버튼을 클릭하여 로그인 상태로 전환
![](https://s1.md5.ltd/image/184bdf8cebd2fe53730e5aaa879c1a83.png)
![](https://s1.md5.ltd/image/f78fceaa922f4d31d2fd693f81170f72.png)
애플리케이션을 만들고 배포
다음 명령을 실행하여 Heroku에 응용 프로그램 만들기 및 배포
$ heroku create アプリケーション名
$ heroku config:set LINE_CHANNEL_SECRET="Channel Secret" --app アプリケーション名
$ heroku config:set LINE_CHANNEL_ACCESS_TOKEN="アクセストークン" --app アプリケーション名
$ git push heroku master
애플리케이션 이름은 임의의 이름입니다.
'Channel Secret'과 '액세스 토큰'은 LINE Developers에서 채널을 만들 때 확인한 것을 설정한다.
build pack 설정
build pack 의 설정을 할 수 없으면 배포에 실패하는 경우가 있다.
이 경우 다음 명령을 실행하여 빌드 팩을 설정하십시오.
$ heroku buildpacks:set heroku/python
5.LINE Bot 측에서 webhook 설정
LineDevelopers 콘솔에서 만든 채널의 웹 후크 설정 설정
Webhook을 사용하고 webhook URL에 다음 URL을 지정하십시오.
https://アプリケーション名.herokuapp.com/callback
완성
여기까지의 작업이 완료되면 앵무새 돌려주는 봇이 완성되었습니다!
Heroku도 Git도 MessagingAPI도 사용한 적이 없는 초보자였지만, 의외로 간단하게 작성할 수 있었습니다
앞으로는 이것을 바탕으로 무언가를 만들 수 있으면 좋겠다.
Reference
이 문제에 관하여(【Python】【LINE Bot】 앵무새 반환 LINE Bot 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/pon187/items/7adb5504ab31af5ef52e
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import sys
from argparse import ArgumentParser
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)
app = Flask(__name__)
# get channel_secret and channel_access_token from your 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)
line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)
@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:
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessage)
def message_text(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.message.text)
)
if __name__ == "__main__":
port = int(os.getenv("PORT", 5000))
app.run(host="0.0.0.0", port=port)
web: python main.py
Flask==0.12.2
line-bot-sdk==1.8.0
python-3.6.6
git 저장소를 만들고 커밋
터미널 등에서 다음 명령을 실행합니다.
$ cd line-bot
$ git init
$ git config user.name "名前"
$ git config user.email メールアドレス
$ git add .
$ git commit -m "コメント"
$ cd line-bot : 루트 디렉토리로 이동
$ git init : git 저장소 초기화
$ git config user.name "이름": config 설정
$ git config user.email 이메일 주소 : config 설정
$ git add . : 추가
$ git commit -m "댓글": 커밋
Heroku에 로그인
다음 명령을 실행하여 Heroku에 로그인
$ heroku login
실행하면 아래와 같은 상태가 되므로 무언가 키를 누르면 브라우저에서 로그인 화면이 표시되므로,
Log In 버튼을 클릭하여 로그인 상태로 전환
![](https://s1.md5.ltd/image/184bdf8cebd2fe53730e5aaa879c1a83.png)
![](https://s1.md5.ltd/image/f78fceaa922f4d31d2fd693f81170f72.png)
애플리케이션을 만들고 배포
다음 명령을 실행하여 Heroku에 응용 프로그램 만들기 및 배포
$ heroku create アプリケーション名
$ heroku config:set LINE_CHANNEL_SECRET="Channel Secret" --app アプリケーション名
$ heroku config:set LINE_CHANNEL_ACCESS_TOKEN="アクセストークン" --app アプリケーション名
$ git push heroku master
애플리케이션 이름은 임의의 이름입니다.
'Channel Secret'과 '액세스 토큰'은 LINE Developers에서 채널을 만들 때 확인한 것을 설정한다.
build pack 설정
build pack 의 설정을 할 수 없으면 배포에 실패하는 경우가 있다.
이 경우 다음 명령을 실행하여 빌드 팩을 설정하십시오.
$ heroku buildpacks:set heroku/python
5.LINE Bot 측에서 webhook 설정
LineDevelopers 콘솔에서 만든 채널의 웹 후크 설정 설정
Webhook을 사용하고 webhook URL에 다음 URL을 지정하십시오.
https://アプリケーション名.herokuapp.com/callback
완성
여기까지의 작업이 완료되면 앵무새 돌려주는 봇이 완성되었습니다!
Heroku도 Git도 MessagingAPI도 사용한 적이 없는 초보자였지만, 의외로 간단하게 작성할 수 있었습니다
앞으로는 이것을 바탕으로 무언가를 만들 수 있으면 좋겠다.
Reference
이 문제에 관하여(【Python】【LINE Bot】 앵무새 반환 LINE Bot 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/pon187/items/7adb5504ab31af5ef52e
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
https://アプリケーション名.herokuapp.com/callback
여기까지의 작업이 완료되면 앵무새 돌려주는 봇이 완성되었습니다!
Heroku도 Git도 MessagingAPI도 사용한 적이 없는 초보자였지만, 의외로 간단하게 작성할 수 있었습니다
앞으로는 이것을 바탕으로 무언가를 만들 수 있으면 좋겠다.
![](https://s1.md5.ltd/image/a2853a987d244746b1262a5f41da7cea.png)
Reference
이 문제에 관하여(【Python】【LINE Bot】 앵무새 반환 LINE Bot 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/pon187/items/7adb5504ab31af5ef52e텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)