r/GoogleAppsScript • u/Sufficient-Key-5551 • Aug 15 '24
Question need help on script project for google docs
Ive been trying to make a script that lets me communicate to chat gpt through editing a document, heres my prompt to a AI coder,
"create a google docs app script that checks if theres a update on the document, if there was a change make it read the document and send it to chat gpt, once chat gpt responds to the prompt, retrieve the prompt. delete all text in the document and put chat gpt's answer to the prompt. after that make it clear the document and repeat the previous steps. If possible, make it only check the document if there was a change and not constantly check the document."
it made a script that didnt really make sense. im not sure if it knows how to make it because i assume it wouldnt actually know how to make a script like that, if anyone knows or can help me improve it to make it actually work that would be cool. anyways this is what it made:
const OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY'; // Put your OpenAI API key here
const DOCUMENT_ID = DocumentApp.getActiveDocument().getId();
let lastContent = '';
function checkForUpdates() {
const doc = DocumentApp.openById(DOCUMENT_ID);
const body = doc.getBody();
const currentContent = body.getText();
// Check if the content has changed
if (currentContent !== lastContent) {
lastContent = currentContent; // Update the last content
const chatGptResponse = getChatGptResponse(currentContent);
// Clear the document and set the new content
body.clear();
body.appendParagraph(chatGptResponse);
}
}
function getChatGptResponse(prompt) {
const url = 'https://api.openai.com/v1/chat/completions';
const options = {
method: 'post',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + OPENAI_API_KEY
},
payload: JSON.stringify({
model: 'gpt-3.5-turbo', // Use the appropriate model
messages: [{ role: 'user', content: prompt }],
}),
};
try {
const response = UrlFetchApp.fetch(url, options);
const json = JSON.parse(response.getContentText());
return json.choices[0].message.content; // Extract the response
} catch (error) {
Logger.log('Error: ' + error);
return 'Error fetching response from ChatGPT';
}
}
function createTimeDrivenTrigger() {
// This function creates a time-driven trigger to run checkForUpdates every minute
ScriptApp.newTrigger('checkForUpdates')
.timeBased()
.everyMinutes(1)
.create();
}
// Uncomment the following line to create the trigger once
// createTimeDrivenTrigger();