Google Sheets via Extensions

 // Configuration Constants

const OPENROUTER_API_KEY = "PASTE_YOUR_ACTIVE_OPENROUTER_KEY_HERE"; 


function generatePendingAutonomousContent() {

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  const data = sheet.getDataRange().getValues();

  

  Logger.log("Total rows found: " + data.length);

  

  for (let i = 1; i < data.length; i++) {

    let channelName = data[i][0]; 

    let channelContext = data[i][1]; 

    let status = data[i][8];      

    

    if (channelName && channelContext && status !== "Generated") {

      let currentRow = i + 1;

      Logger.log(`Researching [${channelName}] based on context: "${channelContext}" (Row ${currentRow})...`);

      

      let aiResult = callAIWithContext(channelName, channelContext);

      

      if (aiResult) {

        sheet.getRange(currentRow, 3).setValue(aiResult.suggestedTopic); 

        sheet.getRange(currentRow, 4).setValue(aiResult.optimizedTitle); 

        sheet.getRange(currentRow, 5).setValue(aiResult.keywords);      

        sheet.getRange(currentRow, 6).setValue(aiResult.scriptContent); 

        sheet.getRange(currentRow, 7).setValue(aiResult.description);   

        sheet.getRange(currentRow, 8).setValue(aiResult.tags);          

        sheet.getRange(currentRow, 9).setValue("Generated");            

        

        Logger.log(`Successfully generated and locked row ${currentRow} for ${channelName}.`);

      } else {

        Logger.log(`AI returned null for row ${currentRow}. Skipping for now.`);

      }

    }

  }

  Logger.log("Batch processing complete. All pending rows are up to date.");

}


function callAIWithContext(channelName, channelContext) {

  const url = "https://openrouter.ai/api/v1/chat/completions";

  

  const prompt = `

    You are an elite YouTube growth strategist and veteran content creator. 

    You are building a high-performing video package for the channel "${channelName}".

    

    CRITICAL CHANNEL CONTEXT (Ground Truth):

    The real focus and niche of this channel is: "${channelContext}".

    

    Do not guess or hallucinate a different niche. Base your research, tone, and topic strictly on this exact context.

    

    CRITICAL SCRIPT REQUIREMENTS (~600 Words & Human Tone):

    - SCRIPT LENGTH: Write a concise, punchy, and information-dense script of around 500-600 words tailored to this specific niche.

    - THE HOOK (First 15 seconds): Do NOT start with "Hey guys, welcome back." Start immediately with a compelling hook or story element relevant to ${channelContext}.

    - HUMAN VOICE: Speak like a real creator talking to a peer. Ban robotic AI filler words like "delve", "tapestry", "furthermore", "in conclusion", "beacon", or "revolutionize". 

    - STRUCTURE: Include sections: [The Hook], [The Core Narrative/Breakdown], [The Deep Dive], and [The Takeaway & CTA].

    - CALL TO ACTION (CTA): Include a smooth, natural CTA asking viewers to subscribe to "${channelName}" and leave a comment.

    

    Task Requirements:

    1. Suggested Topic: A high-demand video topic or title idea tailored specifically for this channel's context.

    2. Optimized Title: A high-CTR, curiosity-driven YouTube title.

    3. Target Keywords: 4-5 high-intent search terms.

    4. Full Video Script (scriptContent): The complete ~600-word conversational script with section headers.

    5. Video Description: A clean, compelling 2-3 sentence summary.

    6. Video Tags: 15-20 comma-separated search tags optimized for YouTube.

    

    Return your response strictly in valid JSON format with keys: "suggestedTopic", "optimizedTitle", "keywords", "scriptContent", "description", "tags".

  `;


  const payload = {

    model: "google/gemini-2.5-flash",

    messages: [{ role: "user", content: prompt }],

    response_format: { type: "json_object" },

    max_tokens: 3000

  };


  const options = {

    method: "post",

    contentType: "application/json",

    headers: {

      "Authorization": "Bearer " + OPENROUTER_API_KEY,

      "HTTP-Referer": "https://aiwiseofficial.blogspot.com",

      "X-Title": "Context-Driven Script Generator"

    },

    payload: JSON.stringify(payload),

    muteHttpExceptions: true

  };


  try {

    let response = UrlFetchApp.fetch(url, options);

    let responseText = response.getContentText();

    let json = JSON.parse(responseText);

    

    if (json.choices && json.choices[0].message) {

      let content = json.choices[0].message.content;

      content = content.replace(/```json/g, "").replace(/```/g, "").trim();

      return JSON.parse(content);

    } else {

      Logger.log("OpenRouter Error Response: " + responseText);

    }

  } catch (error) {

    Logger.log("Exception caught in callAIWithContext: " + error.toString());

  }

  return null;

}

Post a Comment

0 Comments