Skip to content

Xd #2

@atul-mane01

Description

@atul-mane01

const express = require('express');
const rp = require('request-promise');
const fs = require('fs');
const moment = require('moment');

const app = express();

// Function to retrieve data from xMatters API
async function fetchData() {
const currentTime = moment().toISOString();
const last24hrTime = moment().subtract(24, 'hours').toISOString();
const limit = 100; // Adjust the limit as per your requirement

const options = {
    uri: 'https://your-xmatters-api-url/events',
    qs: {
        startTime: last24hrTime,
        endTime: currentTime,
        limit: limit
        // Add any other required parameters here
    },
    headers: {
        'Authorization': 'Bearer your-auth-token',
        // Add any other headers required for authentication
    },
    json: true
};

try {
    const response = await rp(options);
    return response;
} catch (error) {
    console.error('Error fetching data from xMatters API:', error.message);
    throw error;
}

}

// Function to convert JSON data to CSV format
function convertToCSV(data) {
let csv = '';
// Construct CSV header
csv += Object.keys(data[0]).join(',') + '\n';
// Add data rows
data.forEach(item => {
csv += Object.values(item).join(',') + '\n';
});
return csv;
}

// Function to write CSV data to file
async function writeToCSV(csvData) {
const timestamp = moment().format('YYYYMMDDHHmmss');
const fileName = files/${timestamp}.csv;

return new Promise((resolve, reject) => {
    fs.writeFile(fileName, csvData, (err) => {
        if (err) {
            console.error('Error writing CSV file:', err);
            reject(err);
        } else {
            console.log('CSV file saved:', fileName);
            resolve(fileName);
        }
    });
});

}

// Function to send file to Microsoft Teams channel
async function sendToTeams(filePath) {
const url = 'https://graph.microsoft.com/v1.0/teams/{teamId}/channels/{channelId}/messages';
const token = 'YOUR_ACCESS_TOKEN'; // Replace with your access token
const teamId = 'YOUR_TEAM_ID'; // Replace with your Team ID
const channelId = 'YOUR_CHANNEL_ID'; // Replace with your Channel ID

const fileContent = fs.readFileSync(filePath);

const options = {
    uri: url,
    method: 'POST',
    headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json'
    },
    body: {
        body: {
            content: 'New CSV file',
            subject: 'CSV File',
            attachments: [
                {
                    name: filePath.split('/').pop(),
                    contentType: 'text/csv',
                    contentUrl: `data:text/csv;base64,${fileContent.toString('base64')}`
                }
            ]
        },
        json: true
    }
};

try {
    const response = await rp(options);
    console.log('File sent to Teams successfully:', response);
} catch (error) {
    console.error('Error sending file to Teams:', error.message);
    throw error;
}

}

// Define the endpoint to trigger the script
app.get('/trigger-script', async (req, res) => {
try {
// Calculate time
const currentTime = moment().toISOString();
const last24hrTime = moment().subtract(24, 'hours').toISOString();

    // Fetch data from xMatters API
    const eventData = await fetchData(last24hrTime, currentTime);

    // Convert data to CSV format
    const csvData = convertToCSV(eventData);

    // Write CSV data to file
    const filePath = await writeToCSV(csvData);

    // Send file to Teams
    await sendToTeams(filePath);

    res.send('Script executed successfully!');
} catch (error) {
    console.error('An error occurred:', error.message);
    res.status(500).send('Internal server error');
}

});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server is running on port ${PORT});
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions