What is the best way to fetch all messages from a channel and share them on Hastebin using discord.js?

Currently, I am conceptualizing a questioning bot. With this in mind, I want to clarify that once the member's question is answered, the created channel should be closed. Prior to closing the channel, the bot is expected to share a link from hastebin.com containing the chat logs from the channel.

For illustration purposes, envision the following scenario: I open a ticket, a channel is established for private communication between me and the support team. I pose my question and receive a response. Subsequently, the channel is terminated. Before its closure, the bot generates a log and uploads it to hastebin, producing an outcome similar to the image seen in the following link:

https://i.sstatic.net/DIK1g.png

Your assistance is greatly appreciated!

edit: While I am familiar with most of the process, my main challenge lies in extracting the channel log and formatting it for hastebin.

Answer №1

After discussing, it seems like we've really hit on something here. I've made some updates to your code to make it more efficient, and I believe anyone using discord.js will be able to easily grasp what's happening here.

Original Code

    message.channel.fetchMessages().then(messages => {
        console.log(`${messages.size} messages fetched.`);
        messages.array().reverse().forEach(msg => {
            console.log(`[${moment(msg.createdTimestamp).format("DD/MM/YYYY - hh:mm:ss a").replace("pm", "PM").replace("am", "AM")}] ` +
            `[${msg.author.username.toString()}]` + ": " + msg.content);
        });
        
    })

Updated Code

message.channel.fetchMessages().then(async messages => {
    console.log(`${messages.size} messages fetched.`);

    let finalArray = [];

    const putInArray = async (data) => finalArray.push(data);
    const handleTime = (timestamp) => moment(timestamp).format("DD/MM/YYYY - hh:mm:ss a").replace("pm", "PM").replace("am", "AM"); 

    for (const message of messages.array().reverse()) await putInArray(`${handleTime(message.createdTimestamp)} ${message.author.username} : ${message.content}`); 

    console.log(finalArray);
    console.log(finalArray.length);

});

I hope this is helpful for you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for guidance on configuring an email composer in a PhoneGap application

Seeking assistance in troubleshooting the email composer plugin for my PhoneGap app (using JQueryMobile). In my config.xml, I have included the plugin as shown below; <plugin name="cordova-plugin-email-composer" spec="https://github.com/katzer/cordova ...

Tips for preventing JavaScript errors when making cross-domain requests using AJAX

Is there a way to prevent or handle JavaScript errors without causing the script to crash? Error message: No data returned $.ajax({ type : 'GET', dataType : 'jsonp', url : '//cvrapi.dk/api?search=dsfsdfsd&country= ...

Unable to get Bootstrap tooltip functionality to work with jquery.slim when importing through webpack

After installing bootstrap 4.6.0 and jquery 3.6.0 via npm, I encountered a strange issue when trying to use tooltips. The following code snippet is functioning correctly: import jQuery from "jquery/dist/jquery"; import "bootstrap/dist/js/bo ...

Is there a way to divide my time during work hours using Javascript?

This is just a simple example. 9.00 - 18.00 I am looking to modify the schedule as follows: 9.00 - 10.00 10.00 - 11.00 11.00 - 12.00 12.00 - 13.00 13.00 - 14.00 14.00 - 15.00 15.00 - 16.00 16.00 - 17.00 17.00 - 18.00 The current code implementation see ...

Unanticipated commitments fulfilled on the spot

While troubleshooting a setup for managing promise concurrency in handling CPU-intensive asynchronous tasks, I encountered perplexing behavior that has left me puzzled. To regulate the flow, my approach was to initially create an array of Promises and the ...

Looking to replace a background image using javascript?

(apologies for any language mistakes) I have multiple divs with a common background image. I assigned them the same class and set the background image using CSS in style.css which worked perfectly fine. Now, I want to change the background image dynamical ...

What are the best ways to integrate markdown into my Vue.js projects?

Is there a way to utilize markdown within the context of vue.js instead of regular HTML paragraphs? ...

Utilize esbuild to monitor for any modifications, recompile the code, and automatically restart the express server

In my endeavor to develop a basic SSR-powered project using express + react, I find the need to monitor frontend and backend scripts concurrently in the development process. The primary objective is to utilize express routes in directing to react page com ...

When using a function linked to an API request, an uncaught TypeError is thrown: Unable to access the 'includes' property of an undefined value

Utilizing the movie DB API (), I am displaying the results of my call on my page using Vue. The API supplies all the necessary data for me to achieve my objective, as demonstrated in this image https://i.stack.imgur.com/vP4I2.jpg Beneath each show's ...

Sending DOM values to React components as properties

Forgive me if this question seems basic, as I am still learning ReactJs. I have a react component that displays the user's sign-in status: <AccountStatus iconsize="medium" activate={[true,false,true]}/> Image 1 //or using <AccountStatus i ...

Retrieving text from Node.js with the help of regular expressions

I need to extract testcase ids from a list of testcases with titles. Each title includes an id and a description. I want to extract only the id. Here are some examples: TC-ABC-98.1.010_1-Verify the layout credit page TC-RegPMP-1.1.001_2-Verify the [MangerD ...

Can you demonstrate how to incorporate a new line within a for loop?

I have an array of letters and I need to display them on the screen using a for loop. My goal is to make every sixth letter appear on a new line. Here is the code snippet: https://i.stack.imgur.com/lHFqq.jpg <script> export default { data() { ...

JavaScript event listener 'click' not functioning properly

I'm facing an issue with a click event in a script that is associated with a specific div id. When I move the mouse within the div area and click (the cursor remains unchanged), the event listener does not activate. How can I make the div area clickab ...

Creating personalized validation for an AJAX popup in the MVC framework

In my MVC project, I am trying to implement AJAX popup with custom validation. I have created a CustomValidator class and overridden the IsValid() method. However, I am facing an issue where the custom validations are not rendering correctly within the pop ...

Creating a personalized .hasError condition in Angular 4

I am currently in the process of modifying an html form that previously had mandatory fields to now have optional fields. Previously, the validation for these fields used .hasError('required') which would disable the submit button by triggering a ...

How can I transfer data from two queries to Jade using Node.js (Express.js)?

I have a database with two tables - one for storing user information and another for managing friendship connections: setting up a friend list in mysql My goal is to create a profile page using Jade, specifically profile.jade: - each user in users ...

Using NGRX Effects to Load Data for a Specific Item in Angular

On my website, there is a page that displays a range of products from the store managed by a reducer called products. When an action PRODUCTS.LOAD_ALL is dispatched, it triggers an API call through an effect and then sends a PRODUCTS.LOAD_ALL_SUCCESS actio ...

Dealing with ReactJs Unhandled Promise Rejection: SyntaxError - Here's the Solution

Struggling to use the Fetch API in ReactJS to retrieve a list of movies. Encountering an issue, can anyone offer assistance? fetch("https://reactnative.dev/movies.json", { mode: "no-cors", // 'cors' by default }) ...

A step-by-step guide to dynamically adding HTML content on a button click using AngularJS

Can HTML content be added on Button Click event using AngularJS? Here is the code from my index.html: <div class="form-group"> <label for="category"> How Many Questions Do You Want to Add? </label> <div class="col-sm-10"& ...

Transform MVC4 model into a JavaScript JSON object within a cshtml file

I have a model on my cshtml page that I need to convert into a JSON object for use in the JavaScript on the same cshtml page. I am using MVC4. What is the best way to achieve this? ...