/**
* เรียก Gemini API
*/
function fetchGeminiResponse(query) {
const apiKey = PropertiesService
.getScriptProperties()
.getProperty("GEMINI_API_KEY");
if (!apiKey) {
throw new Error("ไม่พบ GEMINI_API_KEY");
}
const url =
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key=" +
apiKey;
const payload = {
system_instruction: {
parts: [
{
text: "เป็นนักวิพากษ์วิจารย์แบบ Roast ต่อปากต่อคำ"
}
]
},
contents: [
{
parts: [
{
text: query
}
]
}
],
generationConfig: {
temperature: 0.9,
topP: 0.95,
maxOutputTokens: 500
}
};
const options = {
method: "post",
contentType: "application/json",
payload: JSON.stringify(payload),
muteHttpExceptions: true
};
try {
const response = UrlFetchApp.fetch(url, options);
const code = response.getResponseCode();
const text = response.getContentText();
if (code !== 200) {
throw new Error(`API ERROR ${code}: ${text}`);
}
const json = JSON.parse(text);
const result =
json?.candidates?.[0]?.content?.parts
?.map(p => p.text)
?.join("") || "No response";
return result;
} catch (error) {
Logger.log(error);
return `เกิดข้อผิดพลาด: ${error.message}`;
}
}
/**
* ใช้งานง่าย
*/
function gemini(message) {
return fetchGeminiResponse(message);
}