teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

コードを修正しました。

2020/09/13 04:06

投稿

raspypy
raspypy

スコア247

title CHANGED
@@ -1,1 +1,1 @@
1
- Heroku 急にくなった LINE BOT
1
+ Heroku 動作し
body CHANGED
@@ -3,189 +3,15 @@
3
3
  1カ月前に動作確認した際、動いていたプログラムが急に動かなくなってしまいました。
4
4
  原因が分からず困っております。
5
5
 
6
- **動かなくなったと判断した理由**
7
- LINE BOTプログラムですので、LINEからメッセージを送ると、決まった返答がくるプログラムですが、
8
- LINEからメッセージを送信しても、返答が何もありません。(「既読」にはなります。)
9
6
 
10
7
  ##プログラム内容
11
8
  deployしたプログラムコードを掲載します。
12
- LINE BOTプログラムです。
13
9
 
14
- ```python
15
- # -*- coding: utf-8 -*-
16
- from __future__ import unicode_literals
17
- import errno
18
- import os
19
- import sys
20
- import tempfile
21
- import logging
22
- from argparse import ArgumentParser
23
-
24
- from flask import Flask, request, abort
25
-
26
- from linebot import (
27
- LineBotApi, WebhookHandler
28
- )
29
- from linebot.exceptions import (
30
- InvalidSignatureError
31
- )
32
- from linebot.models import (
33
- MessageEvent, TextMessage, TextSendMessage,
34
- SourceUser, SourceGroup, SourceRoom,
35
- TemplateSendMessage, ConfirmTemplate, MessageTemplateAction,
36
- ButtonsTemplate, ImageCarouselTemplate, ImageCarouselColumn, URITemplateAction,
37
- PostbackTemplateAction, DatetimePickerTemplateAction,
38
- CarouselTemplate, CarouselColumn, PostbackEvent,
39
- StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage,
40
- ImageMessage, VideoMessage, AudioMessage, FileMessage,
41
- UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent, BeaconEvent
42
- )
43
10
 
44
- import paho.mqtt.client as mqtt
45
-
46
- # ブローカーに接続できたときの処理
47
- def on_connect(client, userdata, flag, rc):
48
- print("Connected with result code " + str(rc))
49
-
50
- # ブローカーが切断したときの処理
51
- def on_disconnect(client, userdata, flag, rc):
52
- if rc != 0:
53
- print("Unexpected disconnection.")
54
-
55
- # publishが完了したときの処理
56
- def on_publish(client, userdata, mid):
57
- print("publish: {0}".format(mid))
58
-
59
-
60
- app = Flask(__name__)
61
-
62
- # ログを標準出力へ。heroku logs --tail で確認するためです。
63
- # app.logger.info で出力するため、レベルは INFO にする。
64
- app.logger.addHandler(logging.StreamHandler(sys.stdout))
65
- app.logger.setLevel(logging.INFO)
66
-
67
- #Secret, tokenは、Exportに設定する方がおすすめ(Web公開されてしまうので…)
68
- line_bot_api = LineBotApi('hogehogehoge')
69
- handler = WebhookHandler('hoge')
70
-
71
- static_tmp_path = os.path.join(os.path.dirname(__file__), 'static', 'tmp')
72
-
73
- client = mqtt.Client() # クラスのインスタンス(実体)の作成
74
- client.on_connect = on_connect # 接続時のコールバック関数を登録
75
- client.on_disconnect = on_disconnect # 切断時のコールバックを登録
76
- client.on_publish = on_publish # メッセージ送信時のコールバック
77
-
78
- client.tls_set("/etc/ssl/certs/ca-certificates.crt")
79
-
80
- client.username_pw_set("xxxxx", "hogehoge")
81
- client.connect("xxxxx.cloudmqtt.com", xxxxx)
82
-
83
-
84
- # function for create tmp dir for download content
85
- def make_static_tmp_dir():
86
- try:
87
- os.makedirs(static_tmp_path)
88
- except OSError as exc:
89
- if exc.errno == errno.EEXIST and os.path.isdir(static_tmp_path):
90
- pass
91
- else:
92
- raise
93
-
94
-
95
- @app.route("/callback", methods=['POST'])
96
- def callback():
97
- # get X-Line-Signature header value
98
- signature = request.headers['X-Line-Signature']
99
-
100
- # get request body as text
101
- body = request.get_data(as_text=True)
102
- app.logger.info("Request body: " + body)
103
-
104
- # handle webhook body
105
- try:
106
- handler.handle(body, signature)
107
- except InvalidSignatureError:
108
- abort(400)
109
-
110
- return 'OK'
111
-
112
- @handler.add(MessageEvent, message=TextMessage)
113
- def handle_text_message(event):
114
- text = event.message.text
115
- # 通信処理スタート
116
- client.loop_start() # subはloop_forever()だが,pubはloop_start()で起動だけさせる
117
- if text == 'password':
118
- buttons_template = ButtonsTemplate(
119
- title='test', text='select', actions=[
120
- PostbackTemplateAction(label='green', data='green'),
121
- PostbackTemplateAction(label='red', data='red'),
122
- PostbackTemplateAction(label='blue', data='blue'),
123
- PostbackTemplateAction(label='yellow', data='yellow'),
124
- ])
125
- template_message = TemplateSendMessage(
126
- alt_text='Buttons alt text', template=buttons_template)
127
- line_bot_api.reply_message(event.reply_token, template_message)
128
- else:
129
- client.publish("system","xxxx") # トピック名とメッセージを決めて送信
130
- line_bot_api.reply_message(
131
- #botは停止中
132
- #event.reply_token, TextSendMessage(text=event.message.text))
133
- event.reply_token, TextSendMessage(text='正しいパスワードを入力して下さい。'))
134
-
135
- @handler.add(PostbackEvent)
136
- def handle_postback(event):
137
- # 通信処理スタート
138
- client.loop_start() # subはloop_forever()だが,pubはloop_start()で起動だけさせる
139
- if event.postback.data == 'green':
140
- client.publish("system","green") # トピック名とメッセージを決めて送信
141
- line_bot_api.reply_message(
142
- event.reply_token, TextSendMessage(text='green'))
143
- elif event.postback.data == 'red':
144
- client.publish("system","red") # トピック名とメッセージを決めて送信
145
- line_bot_api.reply_message(
146
- event.reply_token, TextSendMessage(text='red。'))
147
- elif event.postback.data == 'blue':
148
- client.publish("system","blue") # トピック名とメッセージを決めて送信
149
- line_bot_api.reply_message(
150
- event.reply_token, TextSendMessage(text='blue'))
151
- elif event.postback.data == 'yellow':
152
- client.publish("system","yellow") # トピック名とメッセージを決めて送信
153
- line_bot_api.reply_message(
154
- event.reply_token, TextSendMessage(text='yellow'))
155
-
156
- if __name__ == "__main__":
157
- arg_parser = ArgumentParser(
158
- usage='Usage: python ' + __file__ + ' [--port <port>] [--help]'
159
- )
160
- arg_parser.add_argument('-p', '--port', type=int, default=int(os.environ.get('PORT', 8000)), help='port')
161
- arg_parser.add_argument('-d', '--debug', default=False, help='debug')
162
- arg_parser.add_argument('--host', default='0.0.0.0', help='host')
163
- options = arg_parser.parse_args()
164
-
165
- app.run(debug=options.debug, host=options.host, port=options.port)
166
- ```
167
-
168
11
  ##heroku log
169
12
  **heroku logs --tailで取得した情報は次のとおりです。**
170
13
  **crash**が発生しているのですが、今まで発生していませんでした。
171
14
 
172
15
  ```text
173
- 2020-09-07T00:07:40.780756+00:00 heroku[web.1]: State changed from starting to crashed
174
- 2020-09-07T00:07:40.783097+00:00 heroku[web.1]: State changed from crashed to starting
175
- 2020-09-07T00:07:42.854094+00:00 heroku[web.1]: Starting process with command `python app.py`
176
- 2020-09-07T00:07:44.993470+00:00 app[web.1]: Traceback (most recent call last):
177
- 2020-09-07T00:07:44.993486+00:00 app[web.1]: File "app.py", line 81, in <module>
178
- 2020-09-07T00:07:44.993495+00:00 app[web.1]: client.connect("tailor.cloudmqtt.com", 21683)
179
- 2020-09-07T00:07:44.993495+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 937, in connect
180
- 2020-09-07T00:07:44.993651+00:00 app[web.1]: return self.reconnect()
181
- 2020-09-07T00:07:44.993652+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 1071, in reconnect
182
- 2020-09-07T00:07:44.993854+00:00 app[web.1]: sock = self._create_socket_connection()
183
- 2020-09-07T00:07:44.993857+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 3522, in _create_socket_connection
184
- 2020-09-07T00:07:44.994573+00:00 app[web.1]: return socket.create_connection(addr, source_address=source, timeout=self._keepalive)
185
- 2020-09-07T00:07:44.994574+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/socket.py", line 575, in create_connection
186
- 2020-09-07T00:07:44.994706+00:00 app[web.1]: raise err
187
- 2020-09-07T00:07:44.994748+00:00 app[web.1]: socket.error: [Errno 111] Connection refused
188
- 2020-09-07T00:07:45.061209+00:00 heroku[web.1]: Process exited with status 1
189
- 2020-09-07T00:07:45.107734+00:00 heroku[web.1]: State changed from starting to crashed
190
16
  2020-09-07T00:30:40.814943+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=POST path="/callback" host=remote-plc.herokuapp.com request_id=1ce21cf8-616b-461e-a524-548ecba183b9 fwd="147.92.150.193" dyno= connect= service= status=503 bytes= protocol=https
191
17
  ```

1

コマンド実行時のログを追加しました。

2020/09/13 04:05

投稿

raspypy
raspypy

スコア247

title CHANGED
File without changes
body CHANGED
@@ -13,21 +13,7 @@
13
13
 
14
14
  ```python
15
15
  # -*- coding: utf-8 -*-
16
-
17
- # Licensed under the Apache License, Version 2.0 (the "License"); you may
18
- # not use this file except in compliance with the License. You may obtain
19
- # a copy of the License at
20
- #
21
- # http://www.apache.org/licenses/LICENSE-2.0
22
- #
23
- # Unless required by applicable law or agreed to in writing, software
24
- # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
25
- # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
26
- # License for the specific language governing permissions and limitations
27
- # under the License.
28
-
29
16
  from __future__ import unicode_literals
30
-
31
17
  import errno
32
18
  import os
33
19
  import sys