Failed Interaction using discord.js v14

So, i started using discord.js a few weeks ago, and when i started interactions, i got a problem, i have no error in the terminal, but i have “failed to interact”, i don’t know why, i have a few programs, but i use two to get the bot interact rn :
interactionCreate.js :

const { Events, Client } = require('discord.js');
const { ActionRowBuilder, ButtonBuilder, ButtonStyle, SlashCommandBuilder } = require('discord.js');

module.exports = {
    name: Events.InteractionCreate,
    async execute(interaction) {
        const channel = interaction.channel;

        if (interaction.isChatInputCommand()) {
            const command = interaction.client.commands.get(interaction.commandName);

            if (!command) {
                console.error(`No command matching ${interaction.commandName} was found.`);
                return;
            }

            try {
                await command.execute(interaction);
            } catch (error) {
                console.error(`Error executing ${interaction.commandName} command.`);
                console.error(error);
            }
        } else if (interaction.isButton()) {
            const message = interaction.message;
            // interaction.reply("Vous avez désormais commencé votre aventure ! Il est temps pour vous de découvrir les commandes importantes à l'aide de la commande /help");
        } else if (interaction.isStringingSelectMenu()) {
            channel.send("Merci d'appuyer sur le bouton pour commencer votre aventure !");
        }
    }
};

and start.js :

const { SlashCommandBuilder } = require("discord.js");
const { EmbedBuilder } = require("discord.js");
const { ActionRowBuilder, ButtonBuilder, ButtonStyle } = require("discord.js");

module.exports = {
    data: new SlashCommandBuilder()
        .setName('start')
        .setDescription('Commencer votre aventure...'),
    async execute(interaction) {
        console.log('Deferring reply...');
        await interaction.deferReply();
        console.log('Reply deferred');
        const startEmbed = new EmbedBuilder()
            .setColor(0x6a00ff)
            .setTitle("Commencer votre aventure")
            .setDescription(
                "Il est temps pour vous de commencer votre aventure dans le monde du show-business, à essayer de vous faire une place."
            )
            .addFields(
                {
                    name: "Info n°1",
                    value: "Attention, des spoilers sont inclus dans ce jeu !",
                },
                {
                    name: "Info n°2",
                    value:
                        "Il sera strictement impossible de revenir en arrière ! Attention aux choix que vous ferez, ils peuvent avoir de graves répercussions.",
                },
                {
                    name: "Info n°3",
                    value:
                        "Si vous avez un bug ou une erreur, merci de les signaler en message privé à guiireg.",
                },
                {
                    name: "Info n°4",
                    value:
                        "Mais la règle la plus importante, n'oubliez pas de vous amuser, c'est le plus important !",
                }
            )
            .setImage(
                "https://www.melty.fr/wp-content/uploads/meltyfr/2023/01/001_size10-5.jpg.webp"
            );

        const start = new ButtonBuilder()
            .setCustomId(`${interaction.id}_start`)
            .setLabel("Commencer votre partie dès maintenant")
            .setStyle(ButtonStyle.Primary);

        const startafter = ButtonBuilder.from(start)
            .setDisabled(true)
            .setCustomId(`${interaction.id}_after`);

        const row = new ActionRowBuilder().addComponents(start);
        const rowafter = new ActionRowBuilder().addComponents(startafter);

        interaction.editReply({
            embeds: [startEmbed],
            components: [row],
        });

        const filter = (i) => i.customId === `${interaction.id}_start`; // Vérifie l'identifiant de l'interaction
        const collector = interaction.channel.createMessageComponentCollector({
            filter,
        });

        collector.on("collect", async (i) => {
            console.log('Collector event handler called');
            await interaction.followUp(
                "Vous avez désormais commencé votre aventure ! Ilc est temps pour vous de découvrir les commandes importantes à l'aide de la commande /help"
            );

            await interaction.editReply({
                embeds: [startEmbed],
                components: [rowafter],
            });
        });

        collector.on("end", (collected) =>
            console.log(`Collected ${collected.size} items`)
        );
    }
};

I need help, thanks !

i tried changing reply in defferReply, i tried other things, like changing text etc… but nothing worked, i want to not get the bot sending the message twice (which why i used the “//”, and fix the failed to interact

NodeJS simple script keeps increasing memory

I recently found myself debugging a small-medium nodejs app which keeps increasing its memory when I am debugging it using chrome debug tools. Memory keeps increasing a little everytime I take a snapshot, ~1mb/15minutes, but I cannot find any memory leak at all.

I just cut it down to this bunch of code and memory keeps increasing as well. What is going on?

(async () => {
  while (true) {
    await fetch("https://api.coingecko.com/api/v3/ping");
    await sleep(3000);
  }
})();

Sleep function is just a new Promise resolve with setTimeout.

snapshot 9
snapshot 6

How to GET database to call table and its contents in javascript

I’m using Laravel 9, PHP 8. I want to retrieve data from a database table with javascript, please help.
So i want to pin point location using google maps from my table database using $locations?

This is the content (meanwhile i still using markers manually) :

@extends('layouts.sinlanding')
@section('container')
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">GOOGLE MAPS</h1>
<div id="map"></div>
    </div>
    @foreach ($data as $item)
    <script type="text/javascript">
        function initMap() {
            const myLatLng = { lat: -8.636176573413225, lng: 117.23647409339307 }; 
            const map = new google.maps.Map(document.getElementById("map"), {
                zoom: 8,
                center: myLatLng,
            });

            $locations = [
            ['Pelabuhan Bima', -8.446268919183991, 118.71370024353398],
            ['Pelabuhan Lembar', -8.729112623725898, 116.07243886556259],
            ];
  
            var locations = $locations;
  
            var infowindow = new google.maps.InfoWindow();
  
            var marker, i;
              
            for (i = 0; i < locations.length; i++) {  
                  marker = new google.maps.Marker({
                    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                    map: map
                  });
                    
                  google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                      infowindow.setContent(locations[i][0]);
                      infowindow.open(map, marker);
                    }
                  })(marker, i));
  
            }
        }
  
        window.initMap = initMap;
    </script>
    @endforeach
  
    <script type="text/javascript"
        src="https://maps.google.com/maps/api/js?key={{ env('GOOGLE_MAP_KEY') }}&callback=initMap" ></script>
  
@endsection

This is the controller :

`<?php
  
namespace AppHttpControllers;
  
use IlluminateHttpRequest;
use IlluminateRoutingController;
use AppModelsPelabuhan;
  
class GoogleController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $data = Pelabuhan::all();
        return view('sinkopel', [
            'data' => $data,
            'title' => 'Home'
        ]);
    }
}`

I try this but it doesnt work :

`$locations = [
            [$item->nama_pelabuhan, $item->latitude ',' $item->longitude],
            ];`

kinesis connected to multiple shards – wont fully disconnect again

i have an issue where, if i connect to more than one shard, and call client.destroy(), the script keeps running, where i expect it to stop running, as no more connections should stay open.

im using @aws-sdk/client-kinesis (3.369.0), and everything works, i can consume all my events, issue is only stopping the consumption again, i have removed all the unnessary parts of the code, like consuming, as there is no issues there.

setup:

const region = "";
const accountId = "";
const streamName = ""
const consumerName = "";
const streamARN = "arn:aws:kinesis:" + region + ":" + accountId + ":stream/" + streamName;

const client = new KinesisClient({ region });

//recover a consumer or create a new one
const { Consumers } = await client.send(
  new ListStreamConsumersCommand({ streamARN })
);
let consumer = Consumers.find((i) => i.ConsumerName == consumerName);
if (!consumer) {
  const { Consumer } = await client.send(
    new RegisterStreamConsumerCommand({ streamARN, consumerName })
  );
  consumer = Consumer;
}

this works:

// get shards
const { Shards } = await client.send(
  new ListShardsCommand({
    streamARN,
    streamName,
  })
);

//subscribe to shards
for (const shard of Shards) {
  const { EventStream } = await client.send(
    new SubscribeToShardCommand({
      ConsumerARN: consumer.ConsumerARN,
      ShardId: shard.ShardId,
      StartingPosition: { Type: "LATEST" },
    })
  );
  console.log("subscribed", shard.ShardId);
  break; // only subscribe to the first one..
}

setTimeout(() => {
  console.log('stopping..')
  client.destroy();
}, 30000)

outputs this, and the script stops (as expected)

subscribed shardId-000000000000
stopping..

where as if i remove the break like so

// get shards
const { Shards } = await client.send(
  new ListShardsCommand({
    StreamARN,
    StreamName,
  })
);

//subscribe to shards
for (const shard of Shards) {
  const { EventStream } = await client.send(
    new SubscribeToShardCommand({
      ConsumerARN: consumer.ConsumerARN,
      ShardId: shard.ShardId,
      StartingPosition: { Type: "LATEST" },
    })
  );
  console.log("subscribed", shard.ShardId);
}

setTimeout(() => {
  console.log('stopping..')
  client.destroy();
}, 30000)

the output is

subscribed shardId-000000000000
subscribed shardId-000000000001
subscribed shardId-000000000002
subscribed shardId-000000000003
stopping..

but the script never stops, i could call process.exit that is not the point, im wondering what i have to do, for it to behave the same as if the break is there.

Issue when the user enters fullscreen

I’ve built a multiplayer game (pixel rush) which doesn’t use any media queries, but it looks good on both desktop and mobile. The issue comes in when the user enters fullscreen.

I’ve commented out this meta tag on my HTML:

<!-- <meta name="viewport" content="width=device-width, initial-scale=1" /> -->

so that my site would keep it form on both mobile and desktop. Because with that everything just overflows. So I just disabled it which was fine. But if you go to my game site there will be a fullscreen button on top left corner. When you click on it, it just makes the site as it looked with that meta tag like everything just overflows.

I add my GitHub code link, have this for reference: my code.

Databales using initComplete not work when the data is not not from ajax but local

I am using the plugin databales to display my data. And now I want to add a select box, its value is from the data. When the data is loaded using ajax, it work well. The code is like this:

var table = $("#example").DataTable({
  ajax: {
    url: "/api/mydata/",
    dataSrc: "results",
  },
  columns: [
  ...
  ],
  initComplete: function () {
    var cellTypes = table.column(2).data().unique().toArray();
    var selectOptions = cellTypes.map(function (cellType) {
      return '<option value="' + cellType + '">' + cellType + "</option>";
    });
    $("#cellTypeFilter").append(selectOptions.join(""));
    $("#cellTypeFilter").on("change", function () {
      var selectedCellType = $(this).val();
      table.column(2).search(selectedCellType).draw();
    });
   })

The variable cellTypes is the unique value of third column in data, and I have defind select option which id is “cellTypeFilter” before. All things work well at this time.

Howerver, when I change the source of data, and in fact, I want to get the data from localStorge before request from remote server, so I change the code:

var cachedData = localStorage.getItem("cachedDataTableData");
   
var table = $("#example").DataTable({
   data: CacheData
   ...

Other code is the same with above. But this time the select options is empty, and when i print the ‘cellTypes’ inside the initComplete function, i get undefined.

var table = $("#example").DataTable({
   data: CacheData
   ...
initComplete: function () {
   var cellTypes = table.column(2).data().unique().toArray();
   console.log(cellTypes)
   ...

So why can’t I get the vaule when the data is from localStorge, and how can i modify my code to work in both situtation?

Package installed on Angular not working but working on React project because of webpack

The error is the following: You may need an appropriate loader to handle this file type
It is shown for the svg and css files when the application is compiled in Angular with the package installed and called on it. In React I can use the package and works fine.
I have the following in the webpack.config.js of the package:

module: {
        rules: [
            {
                test: /.css$/i,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(?[a-z0-9=.]+)?$/,
                use: ['url-loader'],
            },
        ],
    },

How to make sure my code prints value of the two variables not undefined

The code below is printing undefined which I know why because constructor is running super first and then it is running the render method at that time firstName and lastName is not set. So hence undefined but how can I overcome this problem. How can i make sure it runs after the value is set.

class Animal{
    constructor(){
        this.render();
    }
    
    render(){
        console.log("This will not run");
    }
}

class Dog extends Animal{
    constructor(firstName, lastName){
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    render(){
        console.log(this.firstName, this.lastName);
    }
}

const d = new Dog("Piggy", "Bank");

How can I make my craco.config.js file keeps watching the changes in development build in my cra project?

I am new to webpack and stuck at the part where making a build file using craco.config.js in create-react-app.

Here is the craco.config.js file that I have created.

const path = require('path');
const webpack = require('webpack');
const publicLocation = '../../public/ui';
const publicPath = '/ui/';
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const { whenDev } = require('@craco/craco');

console.log(process.env.NODE_ENV);

module.exports = {
  devServer: {
    devMiddleware: {
      writeToDisk: true,
    },
  },
  webpack: {
    configure: (webpackConfig, { env, paths }) => {
      const isProduction = env === 'production';
      webpackConfig.mode = env;
      webpackConfig.devtool = 'source-map';
      webpackConfig.entry = ['./src/index.tsx', './src/index.scss'];
      webpackConfig.output = {
        pathinfo: false,
        path: path.resolve(__dirname, publicLocation),
        publicPath,
        sourceMapFilename: 'dpg-portal-bundle.js.map',
        filename: 'dpg-portal-bundle.js',
        chunkFilename: isProduction ? '[name].[chunkhash].js' : '[name].dpb-portal-chunk-bundle.js',
      };
      webpackConfig.resolve = {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        modules: [path.resolve(__dirname, 'src'), 'node_modules'],
        fallback: {
          fs: false,
        },
      };
      webpackConfig.plugins = [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify(env),
          'process.env.BASE_URL': JSON.stringify(process.env.BASE_URL),
        }),
        new webpack.SourceMapDevToolPlugin({
          // filename: 'dpg-portal-bundle.js.map',
          // exclude: 'dpb-portal-bundle.js',
        }),
        new MiniCssExtractPlugin({
          filename: 'css/dpg-portal-bundle.css',
          chunkFilename: 'css/[id].css',
        }),
        new CssMinimizerPlugin(),
        ...whenDev(
          () => [
            new ForkTsCheckerWebpackPlugin({
              issue: {
                include: {
                  severity: 'warning',
                },
              },
              async: true,
              typescript: {
                memoryLimit: 8192,
              },
            }),
          ],
          []
        ),
      ];
      webpackConfig.module = {
        rules: [
          {
            test: /.tsx?$/,
            include: path.join(__dirname, 'src'),
            exclude: /(node_modules)|(dist)/,
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
              ignoreDiagnostics: true,
            },
          },
          {
            test: /.(sa|sc|c)ss$/,
            use: [
              MiniCssExtractPlugin.loader,
              {
                loader: 'css-loader',
                options: {
                  sourceMap: true,
                },
              },
              {
                loader: 'sass-loader',
                options: {
                  sourceMap: true,
                  sassOptions: {
                    outputStyle: 'compressed',
                  },
                },
              },
            ],

            exclude: /node_modules/,
          },
          {
            test: /.css$/i,
            use: ['style-loader', 'css-loader'],
          },
          {
            test: /.(jpg|png|svg|gif|ico)$/,
            loader: 'file-loader',
            options: {
              name: '[path][name].[hash].[ext]',
            },
          },
        ],
      };
      webpackConfig.optimization = {
        removeAvailableModules: isProduction,
        removeEmptyChunks: isProduction,
        splitChunks: false,
        minimizer: [
          new TerserPlugin({
            parallel: true,
            terserOptions: {
              sourceMap: true,
              compress: {
                drop_console: isProduction || false,
              },
              ie8: false,
            },
          }),
        ],
      };

      return webpackConfig;
    },
  },
};

If I type command npm run build, It generates two files which are dpg-portal-bunle.js and dpg-portal-bundle.css in public folder located outside cra folder which is user directory(because I want to host my project using lalavel).

enter image description here

What I want to do is generates bundle file in development mode. Therefore I have editted the command in package.json file.

  "scripts": {
    "start": "craco start",
    "test": "craco test",
    "eject": "react-scripts eject",
    "build-prod": "craco build",
    "build-dev": "env NODE_ENV=development craco build"
  },

Command npm run build-dev also works. However here is the issue: after build process, it stops. webpack does not watch and follow the changes I have made. Whenever I change something in my code, I have to build it again.

To solve this issue, I used webpack-dev-server by using command below.

"build-dev": "env NODE_ENV=development BASE_URL='' webpack watch --mode development"

However this emits main.js file which is default generated file by webpack in dist directory.

What should I do to make my craco.config.js file keeps watching my code and generates bundling file?

installing material-react-table breaks my React JS app

I’d like to use material-react-table in my React JS app…

These are the dependencies that I already have and I have been using in my components:

    "dependencies": {
        "@azure/msal-browser": "^2.22.1",
        "@azure/msal-react": "^1.3.1",
        "@emotion/react": "^11.11.1",
        "@emotion/styled": "^11.11.0",
        "@mui/icons-material": "^5.14.0",
        "@mui/material": "^5.14.0",
        "@mui/x-data-grid": "^5.6.1",
        "@testing-library/jest-dom": "^5.16.2",
        "@testing-library/react": "^12.1.4",
        "@testing-library/user-event": "^13.5.0",
        "aws-sdk": "^2.1123.0",
        "axios": "^0.26.1",
        "dotenv": "^16.0.0",
        "fs": "^0.0.1-security",
        "html-entities": "^2.3.3",
        "material-react-table": "^1.14.0",
        "material-table": "^1.69.3",
        "react": "^17.0.2",
        "react-dom": "^17.0.2",
        "react-hook-form": "^7.28.0",
        "react-scripts": "5.0.0",
        "util": "^0.12.4",
        "web-vitals": "^2.1.4"
    }

I am using npm and run this command:

npm install material-react-table @mui/material @mui/icons-material @emotion/react @emotion/styled

After it has completed I am getting “compiled with problems”

many of the messages read:

export 'default' (imported as 'TableRow') was not found in '@mui/material/TableRow' (module has no exports)
export 'default' (imported as 'TableCell') was not found in '@mui/material/TableCell' (module has no exports)
export 'default' (imported as 'Typography') was not found in '../Typography' (module has no exports)
\etc...

I have changed nothing in my code except for installing the package. I have also tried installing just the material-react-table itself w/o the dependences but I am still facing the same problem.

Any tips would be greatly appreciated ! Thanks for looking.

How to select mixed tags?

User wants to select randomly from the h1 tag then span tag then lists. How to highlight those also needs to give provision to make & clear highlight for the selection,so that he can export as document

Needs to highlight all the selected tags in range.

ReactMarkdown SyntaxHighlighter not working with streamed string

I am getting data as stream which i pass to ReactMarkdown but somehow it syntax highlight doesnot work. however the same string when completed i pass to ReactMarkdown it is working as expected.
its seems that i cannot parse partially streamed string with ReactMarkdown ?

here is how i am getting streamed

 const response = await fetch(
    `${publicRuntimeConfig.REACT_APP_API_URL}/api/v1/get_response_stream`,
    {
      method: "POST",
      body: JSON.stringify({
        user_input: user_input,
        topic: router.query.topic,
      }),

      headers: {
        "Content-Type": "application/json",

        authorization: "Bearer " + globaluser.token,
      },
    }
  );
  const reader = response.body.getReader();
  let first = false;
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      //when copied last one and hardcode it. It does work
      console.log(chats, "Done");
      break;
    }
    const text = new TextDecoder().decode(value);
    let updated = text
      ?.replace(/data:/g, "")
      ?.replace(/data: /g, "")
      ?.replace(/s+/g, " ");
    //?.replace(/n/g, "<br>")
    //.trim();
    // console.log(updated);
    if (!first) {
      //add new entry
      setChats((d) => [...d, updated]);
      first = true;
    } else {
      //update last one
      setChats((d) => {
        let existingChats = [...d];
        let newValue = `${
          existingChats[existingChats.length - 1]
        }${updated}`;

        //console.log(newValue);
        existingChats[existingChats.length - 1] = newValue;
        return existingChats;
      });
      bottomRef.current?.scrollIntoView();
    }
  }

here is how i render each chat, The stream one will be last.. Other chat works fine

 {chats.map((chat, i) => 
       <Typography key={i}
          variant='subtitle1'
          sx={{
             whiteSpace: "break-spaces",
          }}
          className='editor'
        >
                         
                          <ReactMarkdown
                            children={chat
                              .replace("then user: ", "")
                              .replace("then system: ", "")
                              .replace("system : ", "")
                              .replace("system: ", "")
                              .replace("user: ", "")
                              .replace(/^(d+).s/gm, "$1\. ")
                              .replace(/^*s/gm, "\* ")}
                            components={{
                              code({
                                node,
                                inline,
                                className,
                                children,
                                ...props
                              }) {
                                const match = /language-(w+)/.exec(
                                  className || ""
                                );
                                return !inline && match ? (
                                  <SyntaxHighlighter
                                    {...props}
                                    children={String(children).replace(
                                      /n$/,
                                      ""
                                    )}
                                    style={dark}
                                    language={match[1]}
                                    PreTag='div'
                                  />
                                ) : (
                                  <code {...props} className={className}>
                                    {children}
                                  </code>
                                );
                              },
                            }}
                          />
      </Typography>
)}

App Script for fetching Facebook post data and appended to a Google Sheet. But it keeps showing error

I have tried to use the below code to collect total impression and total reach for posts on facebook page with app script and google sheet. However, it keeps showing ‘Error: Exception: Request failed for https://graph.facebook.com returned code 400. Truncated server response: {“error”:{“message”:”(#100) The value must be a valid insights metric”,”type”:”OAuthException”,”code”:100,”fbtrace_id”:”Alk7ixUCpK2pVqWDGAFVLu3″}} (use muteHttpExceptions option to examine full response)’

May I ask if anyone know what caused the issue please? thanks!

function collectPostData() {
  var pageId = 'ID'; // Replace with your Facebook Page ID
  var accessToken = 'token'; // Replace with your Facebook Page access token

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  try {
    var posts = getPosts(pageId, accessToken);

    // Append headers to the sheet
    sheet.appendRow(['Post ID', 'Created Time', 'Message', 'Total Impressions', 'Total Reach']);

    // Iterate over each post
    for (var i = 0; i < posts.length; i++) {
      var post = posts[i];

      var impressions = getPostMetric(post.id, 'impressions', accessToken);
      var reach = getPostMetric(post.id, 'reach', accessToken);

      // Append post data to the sheet
      sheet.appendRow([post.id, post.created_time, post.message, impressions, reach]);
    }
  } catch (e) {
    Logger.log('Error: ' + e);
  }
}

function getPostMetric(postId, metricName, accessToken) {
  var url = 'https://graph.facebook.com/v17.0/' + postId + '/insights?metric=' + metricName + '&access_token=' + accessToken;
  var response = UrlFetchApp.fetch(url);
  var data = JSON.parse(response.getContentText());

  if (data.error) {
    throw new Error('Failed to fetch metric ' + metricName + ' for post ' + postId + ': ' + data.error.message);
  }

  return data.data[0].values[0].value;
}

Why console.log is returning diffeent value than alert?

I have this media query

 @@media (max-width: 1490px) {
            .sidebar2 {
                right: -300px !important;
            }

            .sidebar {
                left: -300px !important;
            }

const smallDevice = window.matchMedia("(max-width: 1490px)");
        smallDevice.addListener(handleDeviceChange);
        function handleDeviceChange(e) {
            if (smallDevice.matches) {
                alert($('#sidebar').css('left'));
            }
        }

the value is 0

however when I write $(‘#sidebar’).css(‘left’) in console I get -300

Any reason