How can I write a discord.js slash command to query a MySQL database?

I’m quite new to discord.js and js in general. I haven’t been able to figure out how to let a user execute a command to query a MySQL database.

In my index.js file, I’ve been able to successfully connect js to my local MySQL database and it runs a quick test on the table ‘users’ on startup.

require('dotenv/config');
const {Client, IntentsBitField} = require('discord.js');
const {CommandHandler} = require('djs-commander');
const path = require('path');
const mysql = require('mysql');

const client = new Client({
    intents: [
        IntentsBitField.Flags.Guilds, //lets us get info on servers
        IntentsBitField.Flags.GuildMembers, //info on users
        IntentsBitField.Flags.GuildMessages,
        IntentsBitField.Flags.MessageContent,
    ],
});

//lets us write events/commands etc to the other folders to keep this file clean
new CommandHandler({
    client, 
    eventsPath: path.join(__dirname, 'events'),
    commandsPath: path.join(__dirname, 'commands'),
});

//mysql connection
var pool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE,
    port: process.env.DB_PORT
})

var connection = pool.getConnection((err, con) => {
    if (err) {
        console.log("Error DB connect: " + err);
        throw err;
    }
    else {
        connection = con;
        console.log("Connection established.");

        connection.query('SELECT points FROM users',(err, result) => {
            console.log(result);
            //interaction.reply({content: `Result:${result}`})
        });
    }

});

client.login(process.env.TOKEN);

I’ve also been able to create a separate names.js file that executes /names in Discord, albeit, it only produces text.

module.exports = {
    data: {
        name: 'names',
        description: 'gets all the names',
    },

    run: ({interaction}) => {
        //connection.query('SELECT username FROM users',(err, result) => {
        //    console.log(result);
        //    interaction.reply({content: `Result:${result}`})
        //});
        interaction.reply('collecting data');
    },
}

Does anyone know how I can incorporate a query into the result of a /command? In this example, the /names command would return a message with the usernames from the database.

fetch GET returns nothing(204) but works(200) in Chrome DevTools

I am trying to write a GET http call to a site to get game scores. I figured out the x-hsci-auth-token token and it uses Akamai Edge Authorization Token. I get good responses for all but 1 request.

For this one request, I get 204 and “No Content”. But the same request returns valid response in the Chrome’s DevTools. I am not sure what I am missing here.

{
  status: 204,
  statusText: 'No Content',
  headers: Headers {
    'x-hsci-cache-time': '2025-04-05T22:59:49.093Z',
    expires: 'Sat, 05 Apr 2025 22:59:49 GMT',
    'cache-control': 'max-age=0, no-cache, no-store',
    pragma: 'no-cache',
    date: 'Sat, 05 Apr 2025 22:59:49 GMT',
    connection: 'keep-alive',
    'access-control-allow-headers': 'Content-Type,Authorization,x-hsci-auth-token',
    'access-control-expose-headers': 'x-hsci-pwa-cache,x-hsci-cache-time,st-access-token,st-refresh-token',
    'access-control-allow-credentials': 'true',
    'access-control-allow-origin': 'https://www.<website>.com'
  },
  body: null,
  bodyUsed: false,
  ok: true,
  redirected: false,
  type: 'basic',
  url: '<endpoint url>'
}

I saw the browser did a Preflight request. I even tried the same payload with OPTIONS request and got 200 back.

Edit: My main goal so to GET the contents. I was trying OPTIONS to see if there were any issues with the authentication or my headers. Since this works, I am guessing I am missing something else.

{
  status: 200,
  statusText: 'OK',
  headers: Headers {
    'content-type': 'text/html',
    'content-length': '2',
    expires: 'Sat, 05 Apr 2025 23:03:24 GMT',
    'cache-control': 'max-age=0, no-cache, no-store',
    pragma: 'no-cache',
    date: 'Sat, 05 Apr 2025 23:03:24 GMT',
    connection: 'keep-alive',
    'access-control-allow-headers': 'Content-Type,Authorization,x-hsci-auth-token',
    'access-control-expose-headers': 'x-hsci-pwa-cache,x-hsci-cache-time,st-access-token,st-refresh-token',
    'access-control-allow-credentials': 'true',
    'access-control-allow-origin': 'https://www.<website>.com'
  },
  body: ReadableStream { locked: false, state: 'readable', supportsBYOB: true },
  bodyUsed: false,
  ok: true,
  redirected: false,
  type: 'basic',
  url: '<endpoint url>'
}

I am using the same request headers in my fetch() requests. So, not sure why this one particular endpoint returns nothing.

const response = await fetch(BASE_API_URL + path, {
      method: 'GET',
      headers: {
        "x-hsci-auth-token": <edgeAuth token>,
        "Origin": "https://www.<website>.com",
        "Referer": "https://www.<website>.com/",
        "accept": "*/*",
        "accept-encoding": "gzip, deflate, br, zstd",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-site",
        "sec-fetch-dest": "empty",
      },
    })

Javascript web extension not loading on SPA websites unless the page is refreshed

I tried to make a web extension that takes you to another website when you click on the page when you are in a specified subcategory.

It works on traditional websites like https://www.w3schools.com/html/html_intro.asp without the need for refreshing but not on https://www.instagram.com/reels/* and https://www.youtube.com/* it need refreshing in order to work.

manifest.json

{


    "manifest_version": 3,
    "name": "URL redirector",
    "version": "0.0.1",



    "content_scripts": [
      {
          "matches":["https://www.instagram.com/reels/*"],
          "js":["background_script.js"]
      }
  ]



  }

background_script.js

      function myFunction(){

        window.open('https://www.stackoverflow.com/questions/ask','_self');
        }
        
        document.addEventListener("click", myFunction);

I have tried to some solutions like executing the program only once the document is fully loaded but still it needs refreshing for JavaScript to execute

  document.onreadystatechange = () => {
    if (document.readyState === "complete") {

      function myFunction(){

        window.open('https://www.stackoverflow.com/','_self');
        }
        
        document.addEventListener("click", myFunction);
        
   
    }
  };

And tried every solution on this question but still the page needs to be reloaded for JavaScript to load.

How do I get app to export in Index.js here?

The error I am getting is: export ‘default’ (imported as ‘App’) was not found in ‘./App’ (module has no exports)

This is do with something in my index.js, supposedly. Here is my code for that:

  import React from 'react';
  import ReactDOM from 'react-dom/client';
  import './index.css';
  import { App } from './App'
  import reportWebVitals from './reportWebVitals';

  const root = ReactDOM.createRoot(document.getElementById('root'));
  root.render(
   <React.StrictMode>
   <App />
  </React.StrictMode>
  );

Webpack: Inject JS script into html page for development build

I have a local JS file that I need to inject into my HTML pages before React-Dom.

How can I go about injecting this script for local development only?

Heres my webpack set-up:

webpack.dev.js

const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    mode: 'development',
    devtool: 'cheap-module-source-map'
});

Webpack.common.js

const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    entry: {
        popup: path.resolve('src/popup/popup.tsx'),
        options: path.resolve('src/options/options.tsx'),
        background: path.resolve('src/background/background.ts'),
        contentScript: path.resolve('src/contentScript/contentScript.js')
    },
    module: {
        rules: [
            {
                use: 'ts-loader',
                test: /.tsx?$/,
                exclude: /node_modules/
            },
            {
                use: ['style-loader', 'css-loader'],
                test: /.css$/i
            },
            {
                type: 'asset/resource',
                test: /.(jpg|jpeg|png|woff|woff2|eot|ttf|svg)$/
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin({
            cleanStaleWebpackAssets: false
        }),
        new CopyPlugin({
            patterns: [
                {
                    from: path.resolve('src/static'),
                    to: path.resolve('dist/')
                }
            ]
        }),
        ...getHtmlPlugin(['popup', 'options'])
    ],
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: '[name].js',
        path: path.resolve('dist')
    },
    optimization: {
        splitChunks: {
            chunks: 'all'
        }
    }
};

function getHtmlPlugin(chunks) {
    return chunks.map(
        (chunk) =>
            new HtmlPlugin({
                title: 'Test',
                filename: `${chunk}.html`,
                chunks: [chunk]
            })
    );
}

Convert Array of Floats (0.0-1.0) to RGB Color

I want to convert an array of floats to RBG values. The floats range from 0.0-1.0. These floats represent pixels.

I initialize the array using pixel data from the python Pillow package. Some pseudocode illustrate:

image_data = Pillow_package('image') = [12, 235, 63, r2, g2, b2, r3, ...]
for dta in image_data:
decimal_data = (r*256*256 + g*256 + b) / (256**3 + 256**2 + 256) = [0.XX, 0.YY, ...]

I use the following code (JS) to recover the RGB values:

val = val * (256*256*256 + 256*256 + 256)
r = Math.floor(val / (256 * 256))
g = Math.floor((val / 256)) % 256
b = val % 256

And that yields the following:
Initial pixel data

The problem is when I begin the simulation. See here:
Simulation initiated

I used the getSciColor() function from Matthias Müller’s 10 Minute Physics GitHub and got the intended result, but his function ‘bins’ use FEA coloring. See before and at initiation.

const min = 0.0
const max = 1.0
val = Math.min(Math.max(val, min), max - .0001)
let d = max - min
val = d == 0.0 ? 0.5 : (val - min) / d
let m = .25
let num = Math.floor(val / m)
let s = (val - num * m) / m

switch (num) {
  case 0 : r = 0.0; g = s; b = 1.0; break;
  case 1 : r = 0.0; g = 1.0; b = 1.0-s; break;
  case 2 : r = s; g = 1.0; b = 0.0; break;
  case 3 : r = 1.0; g = 1.0 - s; b = 0.0; break;
}

I believe I need to relate his ‘bins’ from the switch function to my intended color ‘scale’, but I 1) don’t understand what they do and 2) don’t know if that’s possible. I think that would solve–what appears to be–a blending issue I am running into. Could someone explain 1) and maybe start me down 2) assuming it is possible? Thanks.

How to have 20 buttons with different texts when pressed in JavaScript?

I have about 20 buttons in my HTML code and I want to write a JavaScript code that changes the content of a button when it is pressed. Every button needs to have its specific content that it will change into when pressed. Any help is appreciated, I currently have written this but I would like a better solution:

for (let i = 0; i < btnOpenPage.length; i++) {
    btnOpenPage[i].addEventListener("click", openPage);
}
    
if (document.getElementsByClassName("second").clicked === true) {
    document.querySelector(".continut").innerHTML = `text for btn 2`;
}
    
if (document.getElementsByClassName("third").clicked === true) {
    document.querySelector(".continut").innerHTML = `text for btn 3`;
}
    
btnClosePage.addEventListener("click", closePage);
overlay.addEventListener("click", closePage);

React-chartjs-2 bar chart only shows first dataset when passing batch API response

**Description:**

I’m building a Shariah Compliance Investment Dashboard using React and `react-chartjs-2`.

I fetch data for multiple stock tickers (e.g., “IBM, KO”) from an API. The response contains valid financial ratios for each ticker. The problem is that the chart only displays the bar for the first ticker (e.g., IBM), even though the API response and console log show data for both tickers.

**Expected Behavior:**

Each company should have its own dataset and bar in the chart.

**Actual Behavior:**

Only the first ticker’s data is plotted. The second (and others) are ignored.

I’ve confirmed that my state (`complianceData`) includes valid data for each ticker and that it’s mapped into datasets, but the chart renders only one dataset.

**What I tried:**

– Confirmed that the API returns valid JSON with entries for each ticker

– Verified in the console that all ticker data is present

– Used `Object.entries(complianceData).map(([symbol, details]) => ({…}))`

– Created dynamic datasets using Chart.js, but only the first one displays

– Tried flattening, spreading, and restructuring the chart data

**Expected:**

I expect each ticker to be shown as a separate bar in the chart.

**Screenshot Evidence:**

– API response JSON

– Console.log output

– Chart rendering only first bar

(See attachments below)

API response JSON

Console.log output

Chart rendering only first bar

npm run dev is not working shows blank screen but npm run build, npm run start shows fine

I am trying to just edit the index.js

export default function Home() {
  return (
    <div>
      <h1>Hello</h1>
    </div>
  );
}

/styles/globals.css has


:root {
  --background: #ffffff;
  --foreground: #171717;
}

@theme inline {
  --color-background: var(--background);
  --color-foreground: var(--foreground);
  --font-sans: var(--font-geist-sans);
  --font-mono: var(--font-geist-mono);
}

@media (prefers-color-scheme: dark) {
  :root {
    --background: #0a0a0a;
    --foreground: #ededed;
  }
}

body {
  background: var(--background);
  color: var(--foreground);
  font-family: Arial, Helvetica, sans-serif;
}

_app.js has:

import "@/styles/globals.css";

export default function App({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

When I do npm run build it is showing a blank page in console the error

Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING 

pops up. Tried hard reset, removing and adding all node modules, clearing .next cache and npm cache as well. node and next are up to date

Github Copilot – Javascript gives different binary representation

From my 64-bit machine, when I am in node REPL, I get a certain result with the below javascript code

> const asBinary = BigInt(7306822938861727746).toString(2)
undefined
> asBinary
'110010101100111000011001011111111101011100001110111000000000000' -- (A)

The same when tried from Github CoPilot goes like this

Me
Convert 7306822938861727746 to binary treating it as a 64-bit decimal

GitHub Copilot
The binary representation of 7306822938861727746 treated as a 64-bit decimal is:

0110010101011111010101101011110011111101000000000000000010 -- (B)

Me
Convert 7306822938861727746 to binary treating it as a BigInt in Javascript

GitHub Copilot
To convert 7306822938861727746 to binary treating it as a BigInt in JavaScript, you can use the following code:

const binaryRepresentation = BigInt("7306822938861727746").toString(2);
console.log(binaryRepresentation);// Output: 
11001010101111101010110101111001111110100000000000000010  -- (C)

Github CoPilot is consistent in its responses (B) and (C), when you exclude the leading zero in its first result (B).

(A) differs from both (B) and (C) when starting with the 9th place from the left.

How can this be explained?

Function gets wrong value when been called Apps Script

So Im trying to make a function what searches for empty cell. Funny enough it works perfectly in other script but refuses in main one. It seemes like for some reason when I call a function which requires Sheet and Range in order to work, Range is taken by function correctly (example: ‘C4:C34’). But the sheet is not. It becomes just “Sheet” in log. But I do give a function “sheet3”. Ive tried to give sheet`s name with ‘ ‘, to rename “sheet3” to “sheettrd” but nothing seems to help.

Here is the function itself:

function findEmptyCell(sheet, range) {
  var checkRange = transformCords(range);
  Logger.log(sheet);
  Logger.log(range);
  Logger.log(checkRange);
  for (var i = checkRange[1][0]; i < checkRange[1][1]; i++) {
    if ((sheet.getRange(checkRange[0][0] + i).isBlank())) {
      return sheet.getRange(checkRange[0][0] + i).getA1Notation();
    }
  }
}

And where I call it:

var startPos = transformCords(findEmptyCell(sheet3, 'С4:С34'));
for (let i = 0; i < 4; i++) {
  sheet3.getRange(arrDay[i]+startPos[1])
  .setValue(sheet1.getRange('K' + (40 + i)).getValue());
}

Here is the error what appears

And if its important:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName('Журнал');  
var sheet2 = ss.getSheetByName('Бар');  
var sheet3 = ss.getSheetByName('Итоги');

Why doesn’t my JavaScript code change the content when a button is clicked

I want to set each button to display a specific text, I don’t know what I’m doing wrong if someone can help me. When I press any button it only gives me the text text for btn 3

for (let i = 0; i < btnOpenPage.length; i++) {
btnOpenPage[i].addEventListener("click", openPage);
}

if (document.getElementsByClassName("first").length > 0) {
document.querySelector(".continut").textContent = `text for btn 1`;
}

if (document.getElementsByClassName("second").length > 0) {
document.querySelector(".continut").innerHTML = `text for btn 2`;
}

if (document.getElementsByClassName("third").length > 0) {
document.querySelector(".continut").innerHTML = `text for btn 3`;
}

PieChart animation not playing when setting large state array

I have a react component, which gets some data from backend and shows the result in a piechart.


function SiteInfo() {

    const [url, setUrl] = React.useState('Loading...')
    const [title, setTitle] = React.useState('Loading...')
    const [uptime, setUptime] = React.useState(0)
    const [uptimeData, setUptimeData] = React.useState([])
    const [online, setOnline] = React.useState(false)
    const [latency, setLatency] = React.useState(-1)

    const [searchParams, _] = useSearchParams()
    const siteid = searchParams.get('siteid')

    React.useEffect(() => {
        (async () => {
            const response = await fetch(`http://localhost:3000/siteinfo/${siteid}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
                }
            })
            const siteinfo = await response.json()
            const sitedata = siteinfo.sitedata
            console.log(sitedata.uptimeData)
            setUrl(sitedata.site)
            setTitle(sitedata.title)
            setUptime(sitedata.uptime)
            setUptimeData(sitedata.uptimeData)
            setOnline(sitedata.uptimeData.at(-1).up)
            setLatency(sitedata.uptimeData.at(-1).latency)
        })()
    }, [siteid])
    
    return (
        // ...
                <div>
                    <PieChart width={500} height={300} >
                        <Pie
                            cx='50%'
                            cy='50%'
                            data={[
                                {
                                    name: 'Up',
                                    value: uptime,
                                    fill: '#3CFF60',
                                    stroke: '#29D849',
                                },
                                {
                                    name: 'Down',
                                    value: 100 - uptime,
                                    fill: '#FA8080',
                                    stroke: '#F82D2D',
                                }
                            ]}
                            dataKey='value'
                        >
                        <LabelList dataKey='name' position='outside' />
                        </Pie>
                        <Tooltip />
                    </PieChart>
                </div>
         // ...
    )
}

There is an animation associated with the piechart which appears normally when I remove the line setUptimeData(sitedata.uptimeData), but when the line is present, the animation does not play. Even though uptimeData is not related to the Pie chart in any way.

One thing to be noted is that the field sitedata.uptimeData is a big array of objects (almost 20 elements), maybe it is somehow taking long to set the state and resetting the animation midway. However I cannot find a way to confirm this or an alternative way to set the state.

I am using recharts for the piechart.

Any help will be greatly appreciated.

Is there a way to run JavaScript from a GitHub repository in an MV3 extension?

I’ve been trying to develop an extension called Mod Tamer (https://github.com/KittenCoder/mod-tamer) for Taming.IO. It is a mod store that partially relies on the downloading of JavaScript from the repository. I’ve been wanting to make it work on the latest versions of Chrome so I have to do it in MV3 but according to the developer docs, you can’t run “remote JavaScript” from an extension. Is there any way I could get around this? Like, could I somehow have the script execute the other script or should I take a userscript installer (TamperMonkey) sort of approach or just add the new mod to the source code and update each time? (I haven’t actually done the extension yet.)

I haven’t actually tried anything but according to everything I’ve seen on the web, you can’t do it.

Project architecture for geolocated data on a map [closed]

I have a programming question around the project architecture for geolocated data on a map.
My goal is to have a map that displays realtime data (timeframe: days/weeks) as markers on a map.
As example lets use traffic reports (incidents, jams, blockages, …) around the driver of a vehicle.
The map has no bounds, so all datapoints can be located all around the world.

The user has the option to pan and zoom the map and see a selection of markers most relevant to the current bounds.
But now I’m wondering how to efficiently load this data initially and update on panning/zooming.

Therefore, my question is:
Are there architectures/approaches already documented (papers, packages, documentation) on how to tackle this problem? My main point of concern is the server side of things.

Context

There are too many datapoints to load all markers at once and do the calculations on the client. Clustering or prioritisation would therefore have to be made dynamically on the server side.

Users are able to like/dislike datapoints which should change their visibility.

Current approach

Client

At first I initialise the map and center it on the user.
Based on the current zoom level I split the map in different tiles and calculate which of them are currently in the viewport. Then I make a call to the api to fetch all data relevant to these tiles.
On panning I calculate which tiles are added to the viewport and selectively load more data on demand.

load data based on tile calculation

For zooming I’m not yet sure.
When zooming out, I can probably keep the existing markers and hide those which are not relevant at the new zoom level.
For zooming in, I’ll probably have to make a complete refetch of data for all tiles, to load data for more detailed zoom levels.

Server

For the server side, I’m honestly a bit unsure at this point in time. I have ideas, but feel like I should not reinvent the wheel.

Priority at zoom levels

My main problem is the calculation of the priority at different zoom levels.
Because users can vote on each datapoint, the marker visibilities are pretty dynamic and keep changing every few minutes/hours. Voting effects the markers own visibility as well as its priority relative to others. Therefore the visibility of markers would either need to be calculated every time a tile is requested or an index that stores the visibilities would constantly be updated.

Querying of tiles

I currently calculate different sized tiles for different zoom levels. In order to be able to move data between different sized tiles, the tile sizes are always doubled and halved.
The next higher level therefore always combines 2×2 smaller tiles and a smaller level splits the current tile in 4 parts (2×2).

Tile sizing

But I’m not yet sure, how to connect lat/long positions to all the different sizes of tiles in the db/queries. Theoretically I could only store the smallest tile for each datapoint, because larger tiles can be calculated based on it. But this would lead to large WHERE tileId IN (2x10, 3x10, 4x10, 5x10, ...) queries. Alternatively I could have one individual column for each tile size and query the current column for the current tile size, but this would increase the size of each row in database.

Environment

  • API: PHP, Laravel, (maybe EleasticSearch)
  • Client: Angular, Google / Apple Maps / Open Streetmap

Conclusion

So far.. this is my status quo. Currently I feel like I could start and build a system that would work, but reach its limitations quickly.

And I feel like this is a relatively common problem and I don’t want to reinvent the wheel. I was wondering if there are any infos how the big guys solved this, like:

  • Google Maps
  • Apple Maps
  • Open Streetmap

  • They have integrated location markers which are rendered based on zoom levels.
    Most of their places are less dynamic, but at some point in time their visibility needs to be calculated. And data needs to be queried constantly.

Therefore, I would really appreciate any inputs that could help me expand my concept and build a reasonable architecture. Preferably one that is not too complex to initially set up, but can be extended / scaled on demand, in case more and datapoints/-types are added.

Everything helps:

  • Keywords to search the web with – I already did a lot of researching, but feel like there are resources which I was so far not able to find
  • Concepts to tackle this problem
  • Packages or services that provide help (preferably open source and free to use)