Tips for assigning a postgres query to a variable when working with node.js, integrating Discord bot with postgres

My friend and I have been brainstorming a business idea that involves using Discord as our platform. While I am somewhat new to coding, I do have some knowledge in Discord.js, Java, and HTML.

Here’s the plan:

  • We will have a website where users can purchase a subscription.
  • Upon purchasing the subscription, a unique code will be generated for verification purposes.
  • This code will grant access to enter our server on Discord.
  • The generated code will also trigger the Discord.js bot to assign a specific role to the user.

I could really use some advice on how to get started and what steps to take next. I'm willing to share some of my code and ideas if necessary. My main hurdle right now is figuring out how to generate a code and seamlessly integrate it with Discord.js and HTML.

(Updated content follows...)

I've embarked on this project and encountered two major issues.

bot.on('message', async message => {
  if (message.author.bot) return;
  if (message.channel.id === "*********************") {
    if (message.content === "/clear") return;
    let MessageContent = message.content;
    client.query(`SELECT * FROM public."GeneratedCodes" WHERE generated_codes = '${MessageContent}'`)
      .then(results => {
        if (MessageContent === results.rows) {
          let msg = message.reply(`***Code worked!*** ${results.rows}`)
          msg.then(message => {
            message.delete({
              timeout: 3000
            })
          })
        } else {
          let msg = message.reply("Code ***DIDN'T*** work :(")
          msg.then(message => {
            message.delete({
              timeout: 3000
            })
          })
        }
      })
      .catch(e => console.log(e))
  }
});

My current challenge is creating a query (using PostgreSQL) where the selected value matches message.content. However, I'm struggling to compare message.content to results.rows. Is there a way for me to store

client.query(SELECT * FROM public."GeneratedCodes" WHERE generated_codes = '${MessageContent}')?
in a variable to properly compare it to another variable?

Answer №1

Finally cracked the code after a wild journey...

To anyone exploring this solution, here's a heads-up... It's intricate, so make sure to watch the tutorials and reach out for assistance if needed.

Let's break down the solution step by step:

1. Step one involves setting up a Postgres database, using the link provided:

https://www.youtube.com/watch?v=KH4OsSCZJUo&t

2. Next, importing randomly generated codes via a .csv file is necessary, Utilize the website below for this task:

Importing a .csv file to Postgres simplifies the process. Refer to the video linked below for guidance:

https://www.youtube.com/watch?v=KTcEg35Xd38

3. Once your Postgres database is set up, proceed with the following steps:

-Begin by watching this tutorial on how to utilize the npm install pg library and connect your node.js to the Postgres database:

https://youtu.be/ufdHsFClAk0

Afterward, implement the provided code to validate the inserted code in the Discord message.content against the database:

    // Code snippet goes here

4. Let's analyze the code section by section:

~The initial line `bot.on('message' => async message {}) :

This piece triggers the Discord bot upon receiving a new message within the server.

~Lines 2 - 11 encompass embeds created to enhance the appearance of the bot's response (In-depth tutorial available upon request).

~From line 12 - 14 are conditional statements defining when the code should execute:

-First if: if(message.author.bot) return; Prevents execution if the message sender is a bot.

-Second if:

if(message.channel.id === "720993727811813406")
Restricts the code to run in specific channels only.

-Third if:

if(message.content === "/clear") return;
Skips running the code for certain commands included in messages.

~Line 15

let MessageContent = message.content;
stores the sent message for future use.

~Line 16 onwards handles query execution and result comparison (Refer to above tutorials for clarity).

4. Following result comparison, customize the bot's actions like sending specified Embeds or assigning roles to users.

If you have any queries, feel free to ask, and I'll consider creating explanatory videos!

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

Function not being triggered by button

We are struggling to get a button to trigger a function upon being clicked. Is there a reason why the function is not being called? <body> <button onclick="instagramclick()">Login to instagram</button> <button onclick="myFunction( ...

Leverage the power of dynamic type implementations within Angular framework

Recently, I developed a typescript module that contains type definitions and JavaScript implementations in the dist folder. This typescript module serves as an npm package dependency hosted on an internal HTTP link. Below is a basic diagram depicting the c ...

When utilizing the http.post method, the req.body is not being populated as expected

I am puzzled by the fact that the req.body appears to be empty... app.js utilizes the body-parser middleware() var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/in ...

Does bringing in an object and utilizing it within an Array result in the initial item becoming undefined?

I am currently working on importing a few files to create an object: // otis.ts export const otisHeadline = 'Realizing the office of the future for UTC'; export const otisPreview = toCloudinaryUrl('otisPreview1.png'); export const otis ...

Error: EPERM - Sorry, cannot perform operation, unable to access TestAutomationcypress.json'

When attempting to execute the Test Runner for Cypress for the first time using the command - node_modules.bin\cypress open An unexpected error is encountered - Error: EPERM: operation not allowed, opening \TestAutomation\cypress.json' ...

Ensure that all promises are executed with their inner functions

Is there a way to retrieve multiple HTML bodies simultaneously and only start working with the content once all results are available? I have a callback solution that currently works, here is the code: const request = require('request') const ...

What caused the failure of this discord.js query to mongoose?

Why is the code not working when trying to submit data to MongoDB using a discord.js command? const subregis = "!reg ign: "; client.on("message", msg => { if (msg.content.includes(subregis)){ const user = new User({ ...

Playback on iPhone devices and Safari experiences a 50% reduction with AudioWorklet

I recently developed a basic audio recorder that utilizes the AudioWorkletAPI. While the playback functions smoothly on Chrome, it seems to have issues on Safari and iPhone devices (including Chrome on iPhone) where half of the audio is missing. Specifical ...

Shutting down a React Semantic UI modal using a combination of a button and a close

I've created a Modal where users must fill out forms and save the entered information by clicking a button within the Modal. However, I'm facing an issue - even though I can close the Modal using the open prop on the Modal component, I'm una ...

Avoiding the occurrence of moiré patterns when using pixi.js

My goal is to create a zoomable canvas with rectangles arranged in a grid using pixi.js. Despite everything working smoothly, I'm facing heavy moire effects due to the grid. My understanding of pixi.js and webgl is limited, but I suspect that the anti ...

Determining the compatible Node.js version for a specific package

If I am using express.js v3.16.9, how can I determine the compatible node version in order to decide if I need to upgrade or downgrade? ...

Is it possible for node.js and JS Frameworks to utilize ES6 straight away?

After learning that ES6 has been launched and is now supported by many web browsers, I am curious to know if I can utilize ES6 features and syntax directly in the latest version of node.js and popular JavaScript frameworks such as angular.js or react.js. ...

Using AJAX to submit a single form

Within my HTML view, I have multiple forms that are displayed using a PHP foreach loop. One of the form examples is as follows: <form method="POST" class="like-form-js"> <input type="hidden" name="post_id" value="<?= $post['i ...

Exploring the distinctions between facebook-bot-messenger and messenger-node on NPM

Could someone kindly explain the variances between these two modules : facebook-bot-messenger messenger-node Appreciate it! ...

What methods are available to change one JSON format into another?

I am receiving JSON data from a Laravel API in the following format: [ { "id":48, "parentid":0, "title":"Item 1", "child_content":[ { "id":49, "parentid":48, "title":"Itema 1 ...

What is the best way to globally import KaTeX in Vue.js for my document?

When dealing with static htmls, I usually include the following code in the <head> tag: <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9c2c8ddccd1e99987989987 ...

Is there a way to implement an X icon in Material UI Modals to close them instead of relying on clicking outside the modal?

In my React app, I am utilizing the Material UI Modal component which occupies around 95% of the screen. To improve user experience, I want to include a small "X" icon in the upper right corner of the modal for closing it. Although I am passing down the sa ...

Alignment customization in Exceljs for richText cells

"exceljs": "^3.9.0" In order to create a spreadsheet with cells containing two different values, each aligned differently (one left and one right), I am looking for a solution similar to the image shown in this screenshot: https://i.ss ...

Learn how to dynamically swap background images in Vue.js when hovering over different elements

I am facing an issue where I need to change a background image upon hovering over four different elements, with one unique image for each element. Here is what I have attempted: HTML: <div class="projects"> <a v-on:mouseover="hover=myimage1" ...

Adding default parameters in AngularJS Route-UI is a useful feature for setting up

Using angular UI-Router in my app, I've set up my base language as English. I have both English and Hebrew locals, and I want to avoid adding parameters to the URL if the language is English. For instance: Home English --> http://example.com/ ...