我想做个在Google Sheets( https://docs.google.com/spreadsheets/ )上用Openai的API翻译的功能,把A列的英文->翻译到B列的中文,代码是写在Google Sheets的扩展程序内的Apps脚本内的,用的是Google Apps Script代码,但是这段代码工作起来毛病百出,我让chatGPT看,才发现这家伙胡说八道起来很吓人,东一榔头西一棒子的,所以还是来这里寻求帮助了,还请帮忙修改一下代码啊。谢谢!
补充说明:A列的行数未知,只要不为空就继续翻译,直到A列为空时程序停止。
function translateText() {
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var range = sheet.getRange("A1:A" + lastRow);
var values = range.getValues();
for (var i = 0; i < values.length; i++) {
var text = values[i][0];
console.log("Original text: " + text);
var translatedText = getTranslation(text);
console.log("Translated text: " + translatedText);
sheet.getRange("B" + (i + 1)).setValue(translatedText);
Utilities.sleep(5000); // Pause for 5 second
}
}
function getTranslation(text) {
var url = "https://api.openai.com/v1/engines/davinci/completions";
var data = {
"prompt": "translate from english to chinese: " + text,
"temperature": 0.7,
"max_tokens": 60,
"n": 1,
"stop": "."
};
var options = {
"method": "POST",
"contentType": "application/json",
"payload": JSON.stringify(data),
"headers": {
"Authorization": "Bearer " + "sk-XXXXXXXXXXXXXXXXXXXXXXXXX" // 在这里输入您的API密钥
}
};
try {
var response = UrlFetchApp.fetch(url, options);
var json = JSON.parse(response.getContentText());
var translatedText = json.choices[0].text.trim();
console.log("API response: " + response.getContentText());
return translatedText;
} catch (error) {
Logger.log("Translation failed. Error message: " + error.message);
return "";
}
}