Write the script code for sheet , i want to generate the meta title of 60 characters and meta description of 160 characters by intergrating the chat gpt 4.0
Assistant
Certainly! Below is an example Google Apps Script code you can add to your Google Sheets to generate meta titles and meta descriptions by integrating OpenAI's GPT-4 API.
Key points:
You need an OpenAI API key.
This script reads input from a specific column (e.g., product names or page content).
Sends a prompt to GPT-4 requesting title and description.
Writes back the meta title (60 characters max) and meta description (160 characters max) to specified columns.
Handles API calls with UrlFetchApp.
Step 1: Prepare your sheet columns
Assume:
Column A: Input text (e.g., product name or page text)
Column B: Meta Title (will be output here)
Column C: Meta Description (will be output here)
Step 2: Add the script to Google Sheets
Go to Extensions > Apps Script and paste the code below:
javascript
const OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY_HERE';
function generateMeta() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const dataRange = sheet.getDataRange();
const values = dataRange.getValues();
// Assuming the first row is header; start from row 2
for (let i = 1; i < values.length; i++) {
const inputText = values[i][0];
const metaTitle = values[i][1];
const metaDescription = values[i][2];
// Only run if meta title or description is empty and input text is present
if (inputText && (!metaTitle || !metaDescription)) {
const prompt = `Generate a meta title (max 60 characters) and a meta description (max 160 characters) for the following content:\n\n"${inputText}"\n\nFormat your response as:\nTitle: <title here>\nDescription: <description here>`;
try {
const gptResponse = callOpenAI(prompt);
// Parse response to extract Title and Description
const titleMatch = gptResponse.match(/Title:\s*(.+)/i);
const descMatch = gptResponse.match(/Description:\s*(.+)/i);
if (titleMatch && descMatch) {
// Write back to the sheet
sheet.getRange(i + 1, 2).setValue(titleMatch[1].trim());
sheet.getRange(i + 1, 3).setValue(descMatch[1].trim());
// Optional: Add a short delay to respect API rate limits
Utilities.sleep(1000);
} else {
Logger.log(`Could not parse GPT response on row ${i + 1}: ${gptResponse}`);
}
} catch (e) {
Logger.log(`Error on row ${i + 1}: ${e}`);
}
}
}
}
function callOpenAI(prompt) {
const url = 'https://api.openai.com/v1/chat/completions';
const payload = {
model: 'gpt-4',
messages: [
{ role: 'system', content: 'You are a helpful assistant for generating SEO meta titles and descriptions.' },
{ role: 'user', content: prompt }
],
max_tokens: 200,
temperature: 0.7
};
const options = {
method: 'POST',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${OPENAI_API_KEY}`
},
payload: JSON.stringify(payload),
muteHttpExceptions: true
};
const response = UrlFetchApp.fetch(url, options);
const json = JSON.parse(response.getContentText());
if (json.error) {
throw new Error(json.error.message);
}
return json.choices[0].message.content;
}
Step 3: Replace 'YOUR_OPENAI_API_KEY_HERE' with your actual API key.
Step 4: Run the script
Go back to your sheet.
Click Extensions > Apps Script > click the generateMeta function from the dropdown and hit the run ▶️ button.
The script will process each row where the meta title or description is missing.
Notes:
You may want to limit the number of rows processed at once depending on quota (you could add a counter or check).
You can customize which column the text input is read from and where output goes by modifying the indices in code (values[i][columnIndex]).
The prompt can be improved to suit your tone/style.
If you'd like, I can also help with an automated Custom Menu to trigger this or with onEdit() triggers. Just ask!