Google Sheet Integration
Last updated
Was this helpful?
Was this helpful?
// --- Define your API key and Chatbot ID here ---
const API_KEY = '<Please replace with your actual API key>';
const CHATBOT_ID = '<Please replace with your actual Chatbot ID>';
// --- --- --- --- --- --- --- --- --- --- --- ---
/**
* Send messages to MaiAgent API and directly return response content.
* API key and Chatbot ID use constants defined at the beginning of the script.
* is_streaming is fixed as false, no conversation and attachments sent.
*
* @param {string} messageContent Message content to send.
* @return {string} "content" field from API response, or error message.
*/
function maiagent(messageContent) {
// Check if API_KEY and CHATBOT_ID are set
if (API_KEY === 'YOUR_API_KEY' || CHATBOT_ID === 'YOUR_CHATBOT_ID') {
const warningMessage = 'Warning: API key or Chatbot ID not yet set in script. Please edit script and replace YOUR_API_KEY and YOUR_CHATBOT_ID.';
Logger.log(warningMessage);
// Can choose to throw error or return warning here to prevent invalid API calls
// throw new Error(warningMessage);
return warningMessage;
}
const url = `https://api.maiagent.ai/api/v1/chatbots/${CHATBOT_ID}/completions/`;
const payload = {
message: {
content: messageContent
},
is_streaming: false
};
const options = {
method: 'post',
contentType: 'application/json',
headers: {
'Authorization': `Api-Key ${API_KEY}`
},
payload: JSON.stringify(payload),
muteHttpExceptions: true // Set to true to handle possible API error messages
};
try {
const response = UrlFetchApp.fetch(url, options);
const responseCode = response.getResponseCode();
const responseBody = response.getContentText();
if (responseCode === 200) {
Logger.log('API call successful:');
Logger.log(responseBody); // Still log complete original response for debugging
try {
const jsonResponse = JSON.parse(responseBody);
if (jsonResponse && typeof jsonResponse.content !== 'undefined') {
return jsonResponse.content; // Directly return content field value
} else {
Logger.log('API response successful but missing "content" field or format mismatch.');
Logger.log(responseBody);
return 'Error: API response successful but missing "content" field.';
}
} catch (parseError) {
Logger.log(`Error parsing API response JSON: ${parseError.toString()}`);
Logger.log(`Original response content: ${responseBody}`);
return `Error: Failed to parse API response - ${parseError.toString()}`;
}
} else {
Logger.log(`API call failed, response code: ${responseCode}`);
Logger.log(`Error response content: ${responseBody}`);
return `Error: ${responseCode} - ${responseBody}`;
}
} catch (e) {
Logger.log(`Exception occurred during API call: ${e.toString()}`);
Logger.log(e.stack); // Log stack trace for more detailed debugging
return `Exception: ${e.toString()}`;
}
}