File size: 4,083 Bytes
46d560c
 
543231b
 
7305727
 
 
 
324b97d
 
 
7305727
 
 
 
 
 
 
71ea8b6
7305727
761d26a
 
7305727
75325c4
 
761d26a
 
7305727
 
75325c4
7305727
ac83549
0b12084
8c77142
 
 
 
 
33821f7
 
 
8c77142
 
06f311b
8c77142
b64b32f
27295ef
79507aa
8c77142
7305727
8c77142
 
fadcecc
7305727
 
 
ac83549
 
 
adc88c5
 
ac83549
78cdfd0
ac83549
7305727
a69f1b6
 
 
7305727
e90ea76
7305727
 
2fa1c78
7305727
 
 
 
 
 
 
 
 
75325c4
7305727
 
 
 
78cdfd0
75325c4
78cdfd0
 
8c77142
75325c4
 
78cdfd0
 
 
 
 
 
ac83549
19f1ca3
79507aa
19f1ca3
79507aa
 
 
 
 
 
 
 
 
 
32c7a28
79507aa
e4c9f86
 
79507aa
 
 
 
 
32c7a28
90b5706
79507aa
e4c9f86
79507aa
 
9e2546b
ac83549
 
 
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
# 東吳大學資料系2025年LINEBOT

from flask import Flask, request, abort, send_from_directory
import pyimgur

import markdown
from bs4 import BeautifulSoup

from linebot.v3 import (
    WebhookHandler
)
from linebot.v3.exceptions import (
    InvalidSignatureError
)
from linebot.v3.messaging import (
    Configuration,
    ApiClient,
    MessagingApi,
    MessagingApiBlob,
    ReplyMessageRequest,
    TextMessage,
    ImageMessage
)
from linebot.v3.webhooks import (
    MessageEvent,
    TextMessageContent,
    ImageMessageContent
)

import os
import requests
import logging
import tempfile
import google.generativeai as genai

# HF_TOKEN = os.environ.get('HF_TOKEN')
# headers = {"Authorization": f"Bearer {HF_TOKEN}"}

imgur_client_id = os.environ.get('IMGUR_CLIENT_ID')
imgur_client = pyimgur.Imgur(imgur_client_id)

GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
genai.configure(api_key=GOOGLE_API_KEY)
model = genai.GenerativeModel('gemini-2.0-flash')

static_tmp_path = "/tmp"
os.makedirs(static_tmp_path, exist_ok=True)

# API_URL = "https://api-inference.huggingface.co/models/mistralai/Mixtral-8x7B-Instruct-v0.1"
def query(payload):
    # response = requests.post(API_URL, headers=headers, json=payload)
    response = model.generate_content(payload)
    return response.text

app = Flask(__name__)

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
app.logger.setLevel(logging.INFO)

channel_secret = os.environ.get('YOUR_CHANNEL_SECRET')
channel_access_token = os.environ.get('YOUR_CHANNEL_ACCESS_TOKEN')

configuration = Configuration(access_token=channel_access_token)
handler = WebhookHandler(channel_secret)

@app.route("/")
def home():
    return {"message": "Line Webhook Server"}

@app.route("/", 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:
        app.logger.info("Invalid signature. Please check your channel access token/channel secret.")
        abort(400)

    return 'OK'

@handler.add(MessageEvent, message=TextMessageContent)
def handle_message(event):
    with ApiClient(configuration) as api_client:
        line_bot_api = MessagingApi(api_client)
        response = query(event.message.text)
        html_msg = markdown.markdown(response)
        soup = BeautifulSoup(html_msg, 'html.parser')
        line_bot_api.reply_message_with_http_info(
            ReplyMessageRequest(
                reply_token=event.reply_token,
                messages=[TextMessage(text=soup.get_text())]
            )
        )

@handler.add(MessageEvent, message=ImageMessageContent)
def handle_content_message(event):
    ext = 'jpg'
    with ApiClient(configuration) as api_client:
        line_bot_blob_api = MessagingApiBlob(api_client)
        message_content = line_bot_blob_api.get_message_content(message_id=event.message.id)
        with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix=ext + '-', delete=False) as tf:
            tf.write(message_content)
            tempfile_path = tf.name

    dist_path = tempfile_path + '.' + ext
    dist_name = os.path.basename(dist_path)
    os.rename(tempfile_path, dist_path)
    uploaded_image = imgur_client.upload_image(dist_path)

    with ApiClient(configuration) as api_client:
        line_bot_api = MessagingApi(api_client)
        line_bot_api.reply_message(
            ReplyMessageRequest(
                reply_token=event.reply_token,
                messages=[
                    TextMessage(text='Save content.'),
                    TextMessage(text=uploaded_image.link)
                    # TextMessage(text=request.host_url + os.path.join('static', 'tmp', dist_name))
                ]
            )
        )


@app.route('/static/<path:path>')
def send_static_content(path):
    return send_from_directory('static', path)