Untitled

 avatar
unknown
javascript
2 years ago
2.5 kB
4
Indexable
// Function to fetch messages from the dynamically generated URL
async function fetchMessages() {
  try {
    // Get the current date and format it as 'YYYY-MM-DD'
    const formattedDate = new Date().toLocaleDateString('en-CA').replace(/\//g, '-') + '.html';

    // Construct the URL with the formatted date
    const url = `https://klavogonki.ru/chatlogs/${formattedDate}`;

    // Make a GET request using fetch
    const response = await fetch(url);

    // Check if the request was successful (status code 200)
    if (response.ok) {
      // Parse the response as text
      const htmlContent = await response.text();

      // Call the extractMessages function with the HTML content
      extractMessages(htmlContent);
    } else {
      // If the request was not successful, log the status
      console.error(`Failed to fetch messages. Status: ${response.status}`);
    }
  } catch (error) {
    // Log any errors that occur during the fetch operation
    console.error('Error during fetch:', error);
  }
}

// Function to extract messages
function extractMessages(htmlContent) {
  // Create a temporary container element to parse the HTML content
  const tempContainer = document.createElement('div');
  tempContainer.innerHTML = htmlContent;

  // Select all elements with class 'ts' (time)
  const timeNodes = tempContainer.querySelectorAll('.ts');

  // Iterate over each time node
  timeNodes.forEach((timeNode) => {
    // Get the next sibling of the time node (should be the nickname node)
    const nicknameNode = timeNode.nextElementSibling;

    // Get the next node (should be the text node or other types of nodes)
    const messageNode = nicknameNode.nextSibling;

    // Extract time and nickname
    const time = timeNode.textContent.trim();
    const nickname = nicknameNode.textContent.trim();

    // Check if the node is an anchor element
    if (messageNode.tagName === 'A') {
      // Extract the href attribute value
      const linkText = messageNode.getAttribute('href');

      // Log the link text
      console.log(linkText);
    } else if (messageNode.nodeType === Node.TEXT_NODE) {
      // Extract the message content
      const messageContent = messageNode.nodeValue.trim();

      // Log the combined message without a link
      const combinedMessage = `${time} ${nickname} ${messageContent}`;
      console.log(combinedMessage);
    }
  });
}

// Call the fetchMessages function to start the process
fetchMessages();
Editor is loading...
Leave a Comment