前幾天都講爬蟲,納今天來講一個API使用方法吧
來介紹google bard,雖然不是一個很成熟的生成式AI,但由於結果生成很快,所以在這邊也是一個相比Chatgpt與Bing AI來的有優勢的選擇。
先到Bard聊天頁面,F12->Application->Cookies的"__Secure-1PSID"、"__Secure-1PSIDTS"、"__Secure-1PSIDCC"的值複製下來
以下是程式碼環節
首先要先安裝pip套件
pip install bardapi
import requests
import subprocess
import threading
import warnings
import json
from bardapi.constants import SESSION_HEADERS
from bardapi import Bard
from linebot import LineBotApi, WebhookHandler, LineBotSdkDeprecatedIn30
from linebot.models import TextSendMessage, ImageSendMessage
from flask import Flask, request
def bard_chatbot(text):
token = "<cookie __Secure-1PSID的值>"
session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", token)
session.cookies.set("__Secure-1PSIDTS", "<cookie __Secure-1PSID的值>")
session.cookies.set("__Secure-1PSIDCC", "<cookie __Secure-1PSIDCC的值>")
bard = Bard(token=token, session=session)
bard_return = bard.get_answer(text)['content']
return bard_return
app = Flask(__name__)
@app.route("/", methods=['POST'])
def get_reply():
#這邊記得修改
api = LineBotApi('<你的Channel access token>')
handler = WebhookHandler('<你的Channel secret>')
body = request.get_data(as_text=True)
json_data = json.loads(body)
try:
signature = request.headers['X-Line-Signature']
handler.handle(body, signature)
user_id = json_data['events'][0]["source"]['userId']
text = json_data['events'][0]['message']['text']
if text[:3] == "gpt":
bard_return = bard_chatbot(text[4:])
api.push_message(user_id, TextSendMessage(text=bard_return))
except Exception as e:
print(e)
return 'OK'
def jobs1():
app.run()
#--log=stdout, 將輸出送至終端機
#這邊記得修改
def jobs2():
subprocess.run([
"ngrok",
"http",
"5000",
"--domain=<你的domain位置>",
"--log=stdout"
])
if __name__ == "__main__":
#避免出現警告訊息
warnings.filterwarnings("ignore", category=LineBotSdkDeprecatedIn30)
#多執行緒工作
jobs = []
jobs.append(threading.Thread(target=jobs1))
jobs.append(threading.Thread(target=jobs2))
for i in range(len(jobs)):
jobs[i].start()
效果如下
由於Google Bard目前是實驗版,並無官方API可以使用。
從網站中取得的cookie可能會隨著時間而無效,若需長期使用必須得持續更新資訊。
https://github.com/dsdanielpark/Bard-API/issues/99#issuecomment-1635491543