### 可以取得 ==使用者輸入== ,則==傳送時間==和==誰傳== 也能用相同邏輯取得資訊。 ![](https://hackmd.io/_uploads/SJy_cBSN3.png) ### 果然Line傳遞的資料都能從相同回應中循得 ### 上面資料因為包含了==UserID== ,故取得==UserProfile==也是相同邏輯 ![](https://hackmd.io/_uploads/BkiGSNDV3.png) * ### ==使用者頭貼==的資料可以這樣取得 ```python= userID = json_data['events'][0]['source']['userId'] userProfile = line_bot_api.get_profile(userID) userPicture = userProfile.picture_url ``` * ### ==使用者名稱==的資料可以這樣取得 ```python= userID = json_data['events'][0]['source']['userId'] user_profile = line_bot_api.get_profile(userID) user_name = user_profile.display_name ``` * ### ==時間格式==可以這樣處理 ```python= sendTime = json_data['events'][0]['timestamp'] #取得時間資料 utc_time = datetime.datetime.utcfromtimestamp(sendTime / 1000.0) #處理毫秒 time_format = "%Y-%m-%d %H:%M:%S" #時間輸出格式 local_time = utc_time + datetime.timedelta(hours=8) #utc+8才是我們的時區 formatted_time = local_time.strftime(time_format) #輸出 ``` * ### 整合在一起的結果就是 ![](https://hackmd.io/_uploads/Syi0INPN3.png) * ### ==UserPicture的Url==點開就是==使用者頭貼==囉 ![](https://hackmd.io/_uploads/HyAZPVPV3.png) ## ==所以使用別人的Line Bot傳訊息務必斟酌== main.py ```python= from flask import Flask, request from linebot import LineBotApi, WebhookHandler from linebot import LineBotApi from linebot.models import ImageMessage, ImageSendMessage from linebot.models import TextSendMessage # 載入 TextSendMessage 模組 import json import datetime from ai import chat,image app = Flask(__name__) CHANNEL_SECRET = "" #代換成自己的channel CHANNEL_ACCESS_TOKEN = "" #代換成自己的access token @app.route("/", methods=['GET']) def home(): return "Hi" @app.route("/", methods=['POST']) def linebot(): body = request.get_data(as_text=True) json_data = json.loads(body) try: line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(CHANNEL_SECRET) signature = request.headers['X-Line-Signature'] handler.handle(body, signature) tk = json_data['events'][0]['replyToken'] # 取得 reply token msg = json_data['events'][0]['message']['text'] # 取得使用者發送的訊息 text_message = TextSendMessage(text = chat(msg)) #TextSendMessage(text=msg) line_bot_api.reply_message(tk, text_message) # 回傳訊息 # 傳送者資訊 userID = json_data['events'][0]['source']['userId'] userProfile = line_bot_api.get_profile(userID) userName = userProfile.display_name #Line名稱 userPicture = userProfile.picture_url #Line頭貼 # 時間戳記 Time = json_data['events'][0]['timestamp'] utcTime = datetime.datetime.utcfromtimestamp(Time / 1000.0) timeFormat = "%Y-%m-%d %H:%M:%S" localTime = utcTime + datetime.timedelta(hours=8) sendTime = localTime.strftime(timeFormat) userRequest = {"Time":sendTime,"UserInput":msg,"UserName":userName,"UserPicture":userPicture} print(userRequest) with open("text.json","a",encoding="utf-8") as fp: json.dump(userRequest,fp,ensure_ascii=False,indent=4) fp.write("\n") except Exception as e: print('error: ' + str(e)) return 'OK' app.run(port="5000") ``` ai.py ```python= from PIL import Image import openai import os from io import BytesIO import requests openai.api_key = os.getenv("OPENAI_API_KEY") def chat(msg): openai.api_key = os.getenv("OPENAI_API_KEY") msg = msg res = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role":"user","content":msg}]) res1 = res["choices"][0]["message"]["content"].replace("\n","") return res1 def image(msg): response = openai.Image.create( prompt=msg, size="256x256", n=1 ) imageUrl = response['data'][0]['url'] return imageUrl ``` output.json ```json= { "Time": "2023-05-09 10:52:48", "UserInput": "什麼時候吃飯剛剛好", "UserName": "同和.", "UserPicture": "https://sprofile.line-scdn.net/0h3xZx95VebFd3AUQls8YSKAdRbz1UcDVFXjciYUJSNDBIMS1RXmIgMhcEMTAeZnkCX2ArYRUBMTN7EhsxaVeQY3AxMmBNMCIFXm4msg" } { "Time": "2023-05-09 10:53:13", "UserInput": "11點了 該吃飯了嗎", "UserName": "同和.", "UserPicture": "https://sprofile.line-scdn.net/0h3xZx95VebFd3AUQls8YSKAdRbz1UcDVFXjciYUJSNDBIMS1RXmIgMhcEMTAeZnkCX2ArYRUBMTN7EhsxaVeQY3AxMmBNMCIFXm4msg" } { "Time": "2023-05-09 10:53:30", "UserInput": "可是現在是上午11點!", "UserName": "同和.", "UserPicture": "https://sprofile.line-scdn.net/0h3xZx95VebFd3AUQls8YSKAdRbz1UcDVFXjciYUJSNDBIMS1RXmIgMhcEMTAeZnkCX2ArYRUBMTN7EhsxaVeQY3AxMmBNMCIFXm4msg" } { "Time": "2023-05-09 10:53:45", "UserInput": "沒關係~", "UserName": "同和.", "UserPicture": "https://sprofile.line-scdn.net/0h3xZx95VebFd3AUQls8YSKAdRbz1UcDVFXjciYUJSNDBIMS1RXmIgMhcEMTAeZnkCX2ArYRUBMTN7EhsxaVeQY3AxMmBNMCIFXm4msg" } ```