Home > Enterprise >  Modify sent text in express.js
Modify sent text in express.js

Time:02-14

I'm trying to make a discord command that stores the user's data in an API. The system looks like this: User runs command -> User's tag gets stored in the API and from there I would be able to handle it from another place. My problem is that after the data is being saved once, it doesn't modify it when another user runs the command.

example of me running command user interacted in express.js

I have tried doing res.send() to update it and searched on the web for solutions but none of them worked.

Here is my code:

const express = require('express');
const app = express();
app.use(express.json());

const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });

client.on('ready', () => {
    console.log('client is now ready')
})

client.on('messageCreate', (msg) => {
    if (msg.author.bot) return;

    if (msg.content === 'hey') {
        app.get('/', (req, res) => {
            res.send(`User interacted: ${msg.author.tag}`);
        })
    }
});

client.login(token)

PS: I do not want to use any programs like Postman etc.

CodePudding user response:

To get the most previous author to show up in the get request, you need to store that value. The app.get/app.post/etc.. methods are defining what the sever should send when particular route is hit. They are not used for storing any data. To solve this particular issue you can simply do something like this:

const express = require('express');
const app = express();
app.use(express.json());

const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });

let previousUser = '';

app.get('/', (req, res) => {
    res.send(`User interacted: ${previousUser}`);
})

client.on('ready', () => {
    console.log('client is now ready')
})

client.on('messageCreate', (msg) => {
    if (msg.author.bot) return;

    if (msg.content === 'hey') {
        previousUser = msg.author.tag;
    }
});

client.login(token)

This code will save the previous messages author to a variable previousUser ever time a message is received that has the content 'hey'. From there, anytime you run a get request on the '/' route, it will display that user.

There are many different ways to store data, be it in memory (like above), in a database, or written to a file. I suggest you read up on express, rest apis, and NodeJS before adding more complicated logic to this program

  • Related