These are java script codes to copy and paste…
TO Retreieve Data from Retell
// Replace with your Retell API key
const RETELL_API_KEY = ‘Your private Key Here’;
const SHEET_NAME = ‘Sheet1’; // Change to your sheet name if different
// Pre-defined product prices per second (Updated)
const predefinedPrices = {
“elevenlabs_tts”: 0.07 / 60, // Price per second
“openai_deepgram_tts”: 0.08 / 60, // Price per second
“gpt_4o_mini”: 0.006 / 60, // Price per second
“gpt_4o”: 0.05 / 60, // Price per second
“claude_3_haiku”: 0.012 / 60, // Price per second
“claude_3_5_sonnet”: 0.06 / 60, // Price per second
“retell_platform”: 0.01 / 60 // Updated price for retell_platform, per second
};
function fetchRetellCallData() {
// Set up the Retell API request
const url = ‘https://api.retellai.com/v2/list-calls’;
const options = {
method: ‘post’,
headers: {
‘Authorization’: `Bearer ${RETELL_API_KEY}`,
‘Content-Type’: ‘application/json’
},
muteHttpExceptions: true,
payload: JSON.stringify({ limit: 100 })
};
// Call the Retell API
const response = UrlFetchApp.fetch(url, options);
const data = JSON.parse(response.getContentText());
// Reference to the Google Sheet
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
// Clear the sheet and set headers
sheet.clear();
sheet.appendRow([
“TotalCost”, “CallID”, “AgentID”, “CallStatus”, “StartTimestamp”, “EndTimestamp”,
“Transcript”, “RecordingURL”, “UserSentiment”, “CallSuccessful”, “CallSummary”,
“ProductsUsed”, “DurationSeconds”, “DisconnectionReason”, “name”, “appointment”, “age”, // For custom analysis data
]);
// Iterate through each call entry and add it to the sheet
data.forEach(call => {
// Initialize default values
let dynamicColumns = [];
let finalPrice = 0;
const productsUsed = [];
const durationSeconds = call.call_cost?.total_duration_seconds || 0;
let callId = call.call_id || ‘-‘;
let agentId = call.agent_id || ‘-‘;
let callStatus = call.call_status || ‘-‘;
let startTimestamp = call.start_timestamp ? new Date(call.start_timestamp).toLocaleString() : ‘-‘;
let endTimestamp = call.end_timestamp ? new Date(call.end_timestamp).toLocaleString() : ‘-‘;
let transcript = call.transcript || ‘-‘;
let recordingUrl = call.recording_url || ‘-‘;
let userSentiment = call.call_analysis?.user_sentiment || ‘-‘;
// Modify this logic to handle true, false, or empty values for CallSuccessful
let callSuccessful = ‘-‘;
if (call.call_analysis?.call_successful === true) {
callSuccessful = ‘true’;
} else if (call.call_analysis?.call_successful === false) {
callSuccessful = ‘false’;
}
let callSummary = call.call_analysis?.call_summary || ‘-‘;
let disconnectionReason = call.disconnection_reason || ‘-‘;
// Handle dynamic custom analysis data
const customAnalysisData = call.call_analysis?.custom_analysis_data || {};
let customDataColumns = [];
for (const key in customAnalysisData) {
if (customAnalysisData.hasOwnProperty(key)) {
// Only add the value of each key (not the key itself)
customDataColumns.push(customAnalysisData[key]);
}
}
// Calculate the final price based on predefined prices per second
for (const [product, pricePerSecond] of Object.entries(predefinedPrices)) {
const isProductUsed = call.call_cost?.product_costs?.some(cost => cost.product === product);
if (isProductUsed) {
productsUsed.push(product);
finalPrice += pricePerSecond * durationSeconds; // Multiply by seconds
}
}
// Round the final price to 4 decimal places
finalPrice = finalPrice > 0 ? finalPrice.toFixed(4) : ‘-‘;
// Append the row to the sheet, ensuring placeholders for missing or invalid data
sheet.appendRow([
`$${finalPrice}`, // Total Cost in first column
callId,
agentId,
callStatus,
startTimestamp,
endTimestamp,
transcript,
recordingUrl,
userSentiment,
callSuccessful, // Now this will be ‘true’, ‘false’, or ‘-‘
callSummary,
productsUsed.join(“, “),
durationSeconds > 0 ? durationSeconds : ‘-‘, // Duration in seconds
disconnectionReason,
…customDataColumns // Add the custom data as additional columns (only values)
]);
});
}
// Create a trigger that runs the fetchRetellCallData function every 5 minutes
function createTimeDrivenTrigger() {
// This will create a time-driven trigger to run the fetchRetellCallData function every 30 minutes
ScriptApp.newTrigger(‘fetchRetellCallData’)
.timeBased()
.everyMinutes(30)
.create();
}
To Calculate Weekly monthly and Total Records
function calculateWeeklyMonthlyTotalMetrics() {
// Define the sheet and the column locations
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(“Sheet1”);
const dateColumn = 5; // Column E (4th column)
const priceColumn = 1; // Column A (15th column)
const statusColumn = 10; // Column J (15th column)
// Define the new columns starting at column R (17th column)
const weeklyCostColumn = 20;
const weeklyCallsColumn = 21;
const weeklySuccessCallsColumn = 22;
const weeklyUnsuccessCallsColumn = 23;
const monthlyCallsColumn = 24;
const monthlySuccessCallsColumn = 25;
const monthlyUnsuccessCallsColumn = 26;
const totalCallsColumn = 27;
const totalSuccessCallsColumn = 28;
const totalUnsuccessCallsColumn = 29;
// Get all values in columns D, M, and I
const data = sheet.getDataRange().getValues();
const today = new Date();
const sevenDaysAgo = new Date(today);
const thirtyDaysAgo = new Date(today);
sevenDaysAgo.setDate(today.getDate() – 7);
thirtyDaysAgo.setDate(today.getDate() – 30);
// Initialize weekly, monthly, and total metrics
let weeklyCost = 0;
let weeklyCalls = 0;
let weeklySuccessfulCalls = 0;
let weeklyUnsuccessfulCalls = 0;
let monthlyCalls = 0;
let monthlySuccessfulCalls = 0;
let monthlyUnsuccessfulCalls = 0;
let totalCalls = 0;
let totalSuccessfulCalls = 0;
let totalUnsuccessfulCalls = 0;
// Iterate through the data to calculate metrics
for (let i = 1; i < data.length; i++) { // Start at 1 to skip the header row
const dateValue = new Date(data[i][dateColumn – 1]);
const price = parseFloat(data[i][priceColumn – 1]) || 0;
const isSuccess = data[i][statusColumn – 1] === true; // Check if successful
// Total metrics (no date filter)
totalCalls++;
if (isSuccess) {
totalSuccessfulCalls++;
} else {
totalUnsuccessfulCalls++;
}
// Monthly metrics (last 30 days)
if (dateValue >= thirtyDaysAgo && dateValue <= today) {
monthlyCalls++;
if (isSuccess) {
monthlySuccessfulCalls++;
} else {
monthlyUnsuccessfulCalls++;
}
}
// Weekly metrics (last 7 days)
if (dateValue >= sevenDaysAgo && dateValue <= today) {
weeklyCost += price;
weeklyCalls++;
if (isSuccess) {
weeklySuccessfulCalls++;
} else {
weeklyUnsuccessfulCalls++;
}
}
}
// Append weekly metrics to the top of their respective columns
sheet.getRange(1, weeklyCostColumn).setValue(“Weekly Cost”).setBackground(“#D3D3D3”);
sheet.getRange(2, weeklyCostColumn).setValue(weeklyCost);
sheet.getRange(1, weeklyCallsColumn).setValue(“Weekly Calls”).setBackground(“#D3D3D3”);
sheet.getRange(2, weeklyCallsColumn).setValue(weeklyCalls);
sheet.getRange(1, weeklySuccessCallsColumn).setValue(“Weekly Successful Calls”).setBackground(“#D3D3D3”);
sheet.getRange(2, weeklySuccessCallsColumn).setValue(weeklySuccessfulCalls);
sheet.getRange(1, weeklyUnsuccessCallsColumn).setValue(“Weekly Unsuccessful Calls”).setBackground(“#D3D3D3”);
sheet.getRange(2, weeklyUnsuccessCallsColumn).setValue(weeklyUnsuccessfulCalls);
// Append monthly metrics to the top of their respective columns
sheet.getRange(1, monthlyCallsColumn).setValue(“Monthly Calls”).setBackground(“#D3D3D3”);
sheet.getRange(2, monthlyCallsColumn).setValue(monthlyCalls);
sheet.getRange(1, monthlySuccessCallsColumn).setValue(“Monthly Successful Calls”).setBackground(“#D3D3D3”);
sheet.getRange(2, monthlySuccessCallsColumn).setValue(monthlySuccessfulCalls);
sheet.getRange(1, monthlyUnsuccessCallsColumn).setValue(“Monthly Unsuccessful Calls”).setBackground(“#D3D3D3”);
sheet.getRange(2, monthlyUnsuccessCallsColumn).setValue(monthlyUnsuccessfulCalls);
// Append total metrics to the top of their respective columns
sheet.getRange(1, totalCallsColumn).setValue(“Total Calls”).setBackground(“#D3D3D3”);
sheet.getRange(2, totalCallsColumn).setValue(totalCalls);
sheet.getRange(1, totalSuccessCallsColumn).setValue(“Total Successful Calls”).setBackground(“#D3D3D3”);
sheet.getRange(2, totalSuccessCallsColumn).setValue(totalSuccessfulCalls);
sheet.getRange(1, totalUnsuccessCallsColumn).setValue(“Total Unsuccessful Calls”).setBackground(“#D3D3D3”);
sheet.getRange(2, totalUnsuccessCallsColumn).setValue(totalUnsuccessfulCalls);
}
This is zehaan, I love automating repetitive tasks with Ai.