4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

flask(anaconda) + herokuでlinebotやってみた

4
Last updated at Posted at 2016-06-01

はじめに

最近はやりのlinebotを作ってみたくてやってみました。
それと、どうしてもpythonで作ってみたかった!

参考

anaconda環境でflaskで開発したサーバーをherokuに上げる
LINE BOT APIを使ってPythonでLINE BOTを作ってみた

以下の三つは友達が結構詳しくrubyで作っているので見てみてください。
LINE BOT が チラシをくれた(1) 〜おうむ返し編
LINE BOT が チラシをくれた(2) 〜PUSH編
LINE BOT が チラシをくれた(3) 〜最後まで

今回の目標

おうむ返しができるところまで作りたい!

環境設定ファイル

conda-requirements.txt
# This file may be used to create an environment using:
# $ conda create --name <env> --file <this file>
# platform: osx-64
flask=0.10.1=py35_1
gunicorn=19.1.0=py35_0
itsdangerous=0.24=py35_0
jinja2=2.8=py35_0
markupsafe=0.23=py35_0
openssl=1.0.2h=0
pastedeploy=1.5.2=py35_1
pip=8.1.1=py35_1
python=3.5.1=0
readline=6.2=2
setuptools=20.7.0=py35_0
sqlite=3.9.2=0
tk=8.5.18=0
werkzeug=0.11.9=py35_0
wheel=0.29.0=py35_0
xz=5.0.5=1
zlib=1.2.8=0
runtime.txt
python-3.5.1

ソースコード

from flask import Flask
from flask import request


import os
import requests
import json
import re



LINEBOT_API_EVENT ='https://trialbot-api.line.me/v1/events'
LINE_HEADERS = {
    'Content-type': 'application/json; charset=UTF-8',
    'X-Line-ChannelID':os.environ['CONTENT'], # Channel ID
    'X-Line-ChannelSecret':os.environ['CHANNEL'], # Channel secre
    'X-Line-Trusted-User-With-ACL':os.environ['MID'] # MID (of Channel)
}
# proxies = {'https': os.environ['PROXIES']}
proxies = {'http': os.environ.get('FIXIE_URL', ''), 'https': os.environ.get('FIXIE_URL', '')}

def post_event( to, content):
    msg = {
        'to': [to],
        'toChannel': 1383378250, # Fixed  value
        'eventType': "138311608800106203", # Fixed value
        'content': content
    }
    print(msg)
    r = requests.post(LINEBOT_API_EVENT, headers=LINE_HEADERS, data=json.dumps(msg),proxies = proxies)

def post_text( to, text ):
    content = {
        'contentType':1,
        'toType':1,
        'text':text,
    }
    post_event(to, content)

app = Flask(__name__)
@app.route("/callback", methods=['POST'])
def hello():
    msgs = request.json['result']
    for msg in msgs:
        text = msg['content']['text']
        print(text)
        post_text(msg['content']['from'],text)
        return ''
if __name__ == "__main__":
    app.run()

最後に

この記事をあげる前にいろいろ、この先のステップのコードまで進んでいたので、コードを戻すときに余計なものが入っているかもしれませんが、そこはすみません、
channelIDなどはherokuの環境変数としておいています。

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?