-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
216 lines (175 loc) · 6.59 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import logging
import sys
import json
from datetime import datetime, timedelta
import schedule as schedule
import sqlalchemy.exc
from flask import Flask, abort, request, Response
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError, LineBotApiError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage, FollowEvent, UnfollowEvent,
)
from sqlalchemy.exc import IntegrityError
from werkzeug.middleware.proxy_fix import ProxyFix
import line
import text_handler as th
from const import SEC_TO_IGNORE_MESSAGES
from models.status_type import StatusType
import models.status_type as st
import config
from database.database import init_db, db
import message as ms
import slack
from models import User
import catcher_rec as cr
import spreadsheet
import const.color as color
def create_app():
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1, x_proto=1)
app.config['SQLALCHEMY_DATABASE_URI'] = config.get_db_uri()
init_db(app)
return app
app = create_app()
with app.app_context():
db.create_all()
workbook = config.connect_gspread()
worksheet_goal_rate = workbook.worksheet('Goal_Rate')
logging.basicConfig(level=logging.WARN, stream=sys.stdout)
channel_access_token = config.LINE_CHANNEL_ACCESS_TOKEN
channel_secret = config.LINE_CHANNEL_SECRET
if channel_secret is None or channel_access_token is None:
app.logger.error('Specify LINE_CHANNEL_SECRET and LINE_CHANNEL_ACCESS_TOKEN in .env file')
sys.exit(1)
line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)
# somehow RuntimeError happens
# cr.setup_catcher_tag()
schedule.every(1).week.do(cr.refresh_catcher_tag)
@app.route('/health', methods=["GET"])
def health():
return 'OK'
@app.route('/', methods=["POST"])
def index():
data = request.data.decode('utf-8')
data = json.loads(data)
# for challenge of slack api
if 'challenge' in data:
token = str(data['challenge'])
return Response(token, mimetype='text/plane')
# for events which you added
if 'event' in data:
event = data['event']
app.logger.info(event)
reply_to_user(event)
return 'OK'
@app.route('/callback', methods=['POST'])
def callback():
signature = request.headers['X-Line-Signature']
body = request.get_data(as_text=True)
try:
handler.handle(body, signature)
except LineBotApiError as e:
app.logger.error(f"Got exception from LINE Messaging API: {e.message}\n")
for m in e.error.details:
app.logger.error(f" {m.property}: {m.message}")
except InvalidSignatureError:
app.logger.error("Invalid signature. Please check your channel access token/channel secret.")
abort(400)
return 'OK'
@handler.add(FollowEvent)
def handle_follow(event):
user_id = event.source.user_id
profile = line_bot_api.get_profile(user_id)
# send welcome message on LINE
msg = ms.default.MENU
msg.template.title = profile.display_name + 'さん、はじめまして!\n' \
'友達追加ありがとうございます!'
msg.template.title = 'メッセージありがとうございます!'
line_bot_api.reply_message(event.reply_token, msg)
# add user to db
user = User(id=user_id, name=profile.display_name)
db.session.add(user)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
slack.refollow(user.get_name())
return
# send message to slack
slack.follow(user.get_name())
@handler.add(UnfollowEvent)
def handle_unfollow(event):
user_id = event.source.user_id
user = User.query.get(user_id)
slack.block(user.get_name())
@handler.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
text = event.message.text
user_id = event.source.user_id
# Record timestamp that message was received
# before accessing the DB (locking user record)
message_received_timestamp = datetime.now()
# get user from db
try:
user = db.session.query(User).filter(User.id == user_id).with_for_update().one()
except sqlalchemy.exc.NoResultFound:
# db.session.expunge_all()
profile = line_bot_api.get_profile(user_id)
user = User(id=user_id, name=profile.display_name)
db.session.add(user)
db.session.commit()
user = db.session.query(User).filter(User.id == user_id).with_for_update().one()
last_handled_timestamp = user.get_last_handled_timestamp()
if last_handled_timestamp is not None:
diff = message_received_timestamp - last_handled_timestamp
if diff < timedelta(seconds=SEC_TO_IGNORE_MESSAGES):
line.send_single_msg(line_bot_api, user.get_id(), ms.default.TOO_FAST)
db.session.expunge_all()
return
user.set_last_handled_timestamp()
db.session.commit()
ss_stage = user.get_session_stage()
ss_type = user.get_session_type()
if ss_stage != 0 and text == ms.default.KEY_END:
spreadsheet.record_goal_rate(user, worksheet_goal_rate, False)
line_bot_api.reply_message(event.reply_token, TextSendMessage(text=ms.default.END))
if ss_type != StatusType.CONTACT:
user.set_answer_msg(text)
slack.send_msg_to_other_thread(user, color=color.INTERRUPTION)
user.reset()
cr.reset(user_id)
elif ss_stage == 0:
th.stage0(line_bot_api, user, event)
elif ss_type == StatusType.CATCH_REC:
th.catcher_rec(line_bot_api, user, event)
elif ss_type == StatusType.CONTACT:
slack.send_msg_to_contact_thread(user.get_name(), text, user.get_thread_ts_contact())
elif st.is_included(StatusType.SELF_REF, ss_type):
th.self_ref(line_bot_api, user, event)
elif st.is_included(StatusType.BN_CREATE, ss_type):
th.bn_create(line_bot_api, user, event)
db.session.commit()
db.session.expunge_all()
def reply_to_user(event):
if 'bot_id' not in event and 'thread_ts' in event:
thread_ts = event['thread_ts']
channel = event['channel']
user = None
if channel == config.CONTACT_CHANNEL_ID:
user = User.query.filter_by(thread_ts_contact=thread_ts).first()
elif channel == config.OTHER_CHANNEL_ID:
user = User.query.filter_by(thread_ts_other=thread_ts).first()
if user is None:
return
user_id = user.get_id()
msg = event['text']
line_bot_api.push_message(user_id, TextSendMessage(text=msg))
if __name__ == "__main__":
# app.run()
app.run(host='0.0.0.0')