iT邦幫忙

0

line bot 無法發送訊息

  • 分享至 

  • xImage

小弟我目前在寫一個小專題,主要目的就是將sql的資訊以及放在imgur的照片透過flask發送到line,但每次將sql讀取資料後,flask就發送報錯,我認為是當他讀取sql時無法及時回應line的request從而引發問題,但我在網路上並沒有找到解決辦法,請問各位大神有甚麼方法可以解決?

以下是我的程式碼

from flask import Flask,request,jsonify,render_template
#from pyngrok import ngrok #colab使用
from linebot.v3.messaging import MessagingApi
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage,StickerSendMessage, ImageSendMessage, LocationSendMessage
import json
import time
import pyimgur
import threading
import sqlite3
import os
import webbrowser
import configparser
#from pyngrok import ngrok
user_id = 'my_id'
#line_bot_api.push_message('my_id', TextSendMessage(text='Hello World!!!'))   #測試使用
urlx = "my_ip"

#imgur圖片上傳
im1 = pyimgur.Imgur('imgur_id') #人臉截圖
uploaded_img2 = im1.upload_image("x.jpeg",title="PyImgur2")
#sql指令
command = "SELECT worker_name FROM work_sheet WHERE id = (SELECT MAX(id) FROM work_sheet)"


app = Flask(__name__)
#port = "5000"
#public_url = ngrok.connect(port).public_url
#print(f" * ngrok tunnel \"{public_url}\" -> \"http://127.0.0.1:{port}\"")

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'db'}
config = configparser.ConfigParser()
config.read('config.ini')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#lineg設定
line_bot_api = MessagingApi(config.get('line-bot','channel_access_token'))
handler = WebhookHandler(config.get('line-bot','channel_secret'))
#sql指令
def allowed_file(filename):
        return '.' in filename and \
                filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def extract_last_data(filepath):
    with open(filepath, 'r') as sql_file:
        sql_commands = sql_file.read().split(';')
        last_command = sql_commands[-2].strip()  # Get the second last command (last command could be empty)
        return execute_sql_command(last_command)

def execute_sql_command(sql_command):
    # Connect to your database
    conn = sqlite3.connect('DevDB.db')
    cursor = conn.cursor()
    # Execute SQL command
    cursor.execute(sql_command)
    # Fetch the result (assuming you're fetching a single row)
    last_data = cursor.fetchone()
    # Close connection
    conn.close()
    return last_data
#flask網頁
@app.route('/')

def home():
    image_url2 = uploaded_img2.link
    body = request.get_data(as_text=True)
    try:
        data = execute_sql_command(command)
        xy = data[0]
        print(xy)
        print(image_url2)
        signature = request.headers['X-Line-Signature']
        handler.handle(body, signature)
        msg = str(xy)
        if msg != None:
            #line_bot_api.push_message(user_id,TextSendMessage(text=msg))          
            #line_bot_api.push_message(user_id,ImageSendMessage(original_content_url=image_url2,preview_image_url=image_url2))
            return msg
        else:
            return 'OK'
    except:
        print('error')



if __name__ == "__main__":
    app.run()
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///DevDB.db'

以下是報錯訊息:
[2024-05-23 05:28:19,832] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "C:\Users\yoyol\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask\app.py", line 1473, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\yoyol\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask\app.py", line 883, in full_dispatch_request
return self.finalize_request(rv)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\yoyol\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask\app.py", line 902, in finalize_request
response = self.make_response(rv)
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\yoyol\AppData\Local\Programs\Python\Python312\Lib\site-packages\flask\app.py", line 1174, in make_response
raise TypeError(
TypeError: The view function for 'home' did not return a valid response. The function either returned None or ended without a return statement.
127.0.0.1 - - [23/May/2024 05:28:19] "GET / HTTP/1.1" 500 -
127.0.0.1 - - [23/May/2024 05:28:19] "GET /favicon.ico HTTP/1.1" 404 -

看更多先前的討論...收起先前的討論...
阿摔 iT邦新手 3 級 ‧ 2024-05-21 10:45:48 檢舉
發送前加個等待時間讓sql的資料跑完呢?
froce iT邦大師 1 級 ‧ 2024-05-22 22:12:51 檢舉
報錯是什麼錯?沒錯誤訊息誰知道是啥錯...
arthur iT邦新手 5 級 ‧ 2024-05-23 05:29:55 檢舉
@froce 報錯訊息並沒有提供特別有用的資訊
arthur iT邦新手 5 級 ‧ 2024-05-23 05:30:40 檢舉
@阿摔 加延遲時間還是一樣
arthur iT邦新手 5 級 ‧ 2024-05-23 05:33:10 檢舉
但我也找不到要如何看line那邊的報錯,line那邊有一項X-Ray-Retry-Key,我在github 找到了方法,我之後試試
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答