javascript discord bot not working correctly

we have a discord javascript bot, which is not working properly. the bot should distribute coins to the users on a weekly basis, but sometimes it’s not distributing. here is the code of the weekly income and also the github link of the whole discord bot javascript bot (https://github.com/geldmagier/hewerclan):

import { Client } from "discord.js";
import SWAG from "swagcommands";
import User from "../util/database/User";

export default async (instance: SWAG, client: Client) => {
    // alle member suchen
    const weeklyIncome = async () => {
        // wenn es montag ist, dann weekly income hinzufügen (1 = montag)
        const today = new Date();
        if (today.getDay() === 1) {
            // alle user des servers suchen
            const us = await client.guilds.cache
                .get(process.env.SERVER_ID!)
                ?.members.fetch({ force: true });

            us?.forEach(async (u) => {
                const user = new User(u.id);

                // wenn der user kein hewerbox holder ist, dann nichts machen
                if (!u.roles.cache.has(process.env.HEWERBOX_HOLDER_ROLE!)) return;

                const userData = await user.create();

                // weekly income hinzufügen
                if (u.roles.cache.has(process.env.CORPORAL_ROLE!)) {
                    user
                        .add(parseInt(process.env.CORPORAL_WEEKLY_INCOME!))
                        .catch((e) => {});
                } else if (u.roles.cache.has(process.env.SKILLED_ROLE!)) {
                    user
                        .add(parseInt(process.env.SKILLED_WEEKLY_INCOME!))
                        .catch((e) => {});
                } else if (u.roles.cache.has(process.env.EXPERT_ROLE!)) {
                    user
                        .add(parseInt(process.env.EXPERT_WEEKLY_INCOME!))
                        .catch((e) => {});
                } else if (u.roles.cache.has(process.env.MASTERFUL_ROLE!)) {
                    user
                        .add(parseInt(process.env.MASTERFUL_WEEKLY_INCOME!))
                        .catch((e) => {});
                } else if (u.roles.cache.has(process.env.SAGE_ROLE!)) {
                    user.add(parseInt(process.env.SAGE_WEEKLY_INCOME!)).catch((e) => {});
                }
            });

            setTimeout(weeklyIncome, 1000 * 60 * 60 * 24);
        }

        setTimeout(weeklyIncome, 1000 * 60 * 60);
    };

    weeklyIncome();
};

hello, we have a discord javascript bot, which is not working properly. the bot should distribute coins to the users on a weekly basis, but sometimes it’s not distributing. here is the code of the weekly income and also the github link of the whole discord bot javascript bot (https://github.com/geldmagier/hewerclan)

How can I create a FabricJS eraser object from a PNG file?

I hv create fabric canvas and I know I can erase/recover canvas by using fabric.EraserBrush
But I would like to know if it is possible to load eraser from PNG (such as alpha mask or BW)
To load into Object.eraser?

I hv tried using fabric.Eraser.fromObject to load from image but it does not create correct eraser object.

fabric.Image.fromURL('https://www.pngall.com/wp-content/uploads/8/Sample-Watermark.png', o => {
  fabric.Eraser.fromObject(o, a => {
    rect.eraser = a;
    rect.dirty = true;
    canvas.renderAll();
  });
});

Split function in js

I am using split function in javascript that will split arraylist coming from java on the basis of comma. But I am facing an issue where words having comma are splitted into two separated words. How do I overcome this problem.

Example-

[“Technology Science”, “Maths”, “Fundamental,Theory of computation”]

Output using split (,) in js:-

“Technology Science”, “Maths”, “Fundamental”,”Theory of computation”

Expected:-

“Technology Science”, “Maths”, “Fundamental,Theory of computation”

How can I prevent the re-rendering of my component when updating the useState value in a custom React hook?

I am trying to create a custom hook, which returns an array with 2 elements:

– a component, containing an input
– and a function, which is in charge of checking the value of input

Simple! Apparently…

But I can’t get the component not to be re-rerendered every time the value of the “useState” is updated. And that takes the focus off the input.

import React, { useState } from 'react';

const useCustomHook = () => {
  const [textoDelInput, settextoDelInput] = useState('');

  const validarTexto = () => {
    return textoDelInput !== '';
  };

  const InputComponent = () => {
    const handleChange = (event) => {
      settextoDelInput(event.target.value);
    };

    return <input type="text" value={textoDelInput} onChange={handleChange} />;
  };

  return [validarTexto, InputComponent];
};

export default useCustomHook;

My real code is more complex and long, but, it’s the same principle.

Reproduction of the example, in a playground here

In my basic example, the problem could be solved with “useRef”, but not in my real code. Because I don’t always have the possibility to pass a reference to the “input”, since they are components of external libraries.

Could you guide me on why this happens? Please, and give me ideas on what I could try to solve it.

Thank you!

How to extract the array inside the object

const html = test.map((user) => {
    return `
    <div class="user">
    ID: ${user.labels.id}
    </div>
    `;
document.querySelector("#app").insertAdjacentHTML("afterbegin", html);

API URL : https://api.github.com/repos/vercel/next.js/issues

There’s an array inside the object which is labels. And I want to try to extract the object inside “labels” array. But since the method I use only work if it’s an object, how to do it if it’s an array?

Alignment of Array Objects underneath one another

Trying to achieve the following where the parcel is being delivered from point AAA to point DDD.

Condition to display is

  1. First row can be displayed anyhow
  2. For displaying the second row, I need to check similar Origin and Destination which exist in the Array Objects and then display them just underneath.

Problem faced

Line not visible if flex-grow is commented:

  .parcel-item {
    // flex-grow: 1;
    display: flex;
  }

Line is visible if flex-grow: 1, however justify-content: space-between; is not applied

  .parcel-item {
    flex-grow: 1;
    display: flex;
  }

Example on how the UI should look:

AAA——XXX—————-DDD

AAA——BBB——CCC—–DDD

AAA——XXX——CCC—–DDD

AAA————————–DDD

AAA———–BXX———–DDD

AAA—XYZ—BXX—OOO—DDD

enter image description here

I tried a lot but I am unable to think on how to achieve this.

Source code: https://codesandbox.io/s/wonderful-dirac-62j1n9?file=/src/App.tsx

code

import "./styles.css";
import { parcelArray } from "./data";

export default function App() {
  return (
    <div className="container">
      <div className="row">
        <div className="col text-center">
          <div className="parcel-container">
            <>
              {parcelArray.map((parcel: any, index: number) => (
                <div className="parcel-container" key={index}>
                  {Object.entries(parcel).map(
                    ([key, points]: [string, unknown], i: number) => (
                      <div className="parcel-row" key={i}>
                        {/* @ts-ignore */}
                        {points?.map((point: any, j: number) => (
                          <div className="parcel-item" key={`${i}-${j}`}>
                            <div className="parcel-line"></div>
                            <div className="parcel-circle">
                              <div className="parcel-origin">
                                {point.origin}
                              </div>
                            </div>
                          </div>
                        ))}
                        {i === Object.entries(parcel).length - 1 && (
                          <div className="parcel-item">
                            <div className="parcel-line"></div>
                            <div className="parcel-circle">
                              <div className="parcel-origin">
                                {/* @ts-ignore */}
                                {points[points?.length - 1].destination}
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    )
                  )}
                </div>
              ))}
            </>
          </div>
        </div>
      </div>
    </div>
  );
}

NodeJS – Unable to load NPM “joystick-controller” library

I post today this problem because no answer could help me, I devloppe a web server that will be used to control motor for a robot. my problem here is that the server (under nodeJS) loads the html file but not the ‘joystick-controller.js’ script unless load with a url.
I also tried to install the dependency “joystick-controller” with NPM but I can not use it server side. The problem here is that my server will not connect to the internet.
I put my code below

<html lang="en"><head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JoyStick</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            overflow: hidden;
        }

        .world {
            position: fixed;
            top: 0;
            left: 0;
            outline: none;
        }

        .info {
            position: absolute;
            background-color: #e3e3e3;
            padding: 10px;
            border-radius: 5px;
            top: 10px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            flex-wrap: wrap;
            font-size: smaller;
            user-select: none;
            pointer-events: none;
        }

        .right {
            right: 10px;
        }

        .left {
            left: 10px;
        }

        .link {
            position: absolute;
            bottom: 10px;
            right: 50%;
            transform: translateX(50%);
            color: #8a1c09;
            font-weight: bold;
            width: 100%;
            text-align: center;
            z-index: 9999;
        }
    </style>
    <style id="style-p2pxmw28d2r0xgi3z111pzq">
        .joystick-container-p2pxmw28d2r0xgi3z111pzq {
            box-sizing: border-box;
            position: fixed;
            outline: none;
            right: 20%;
            bottom: 20%;
            transform: translate(50%, 50%);
        }
    
        .joystick-controller-p2pxmw28d2r0xgi3z111pzq {
            box-sizing: border-box;
            outline: none;
            opacity: 0.5;
            width: 100px;
            height: 100px;
            border-radius: 50%;
            position: relative;
            outline: 2px solid #4c4c4c77;
            background: radial-gradient(circle,#ebebeb55, #5c5c5c55);
        }
    
        .joystick-p2pxmw28d2r0xgi3z111pzq {
            box-sizing: border-box;
            outline: none;
            position: absolute;
            cursor: grab;
            width: 60px;
            height: 60px;
            z-index: 1;
            border-radius: 50%;
            left: 50%;
            bottom: 50%;
            transform: translate(-50%, 50%);
            background: radial-gradient(#000c, #3e3f46aa);
            transition: border-radius 0.2s ease-in-out;
        }
        </style></head>

<body>
    <div class="info right">
        <p>X: <span id="x2">0</span></p>
        <p>Y: <span id="y2">0</span></p>
        <p>X Leveled: <span id="xLeveled2">0</span></p>
        <p>Y Leveled: <span id="yLeveled2">0</span></p>
        <p>Distance: <span id="distance2">0</span></p>
        <p>Angle: <span id="angle2">0</span></p>
    </div>
    <!--
    <script src="https://cdn.statically.io/gh/cyrus2281/joystick-controller/main/dist/umd/joystick-controller.min.js">
    </script>-->
        
    <script type="module">
        // uncomment for dev. (the CDN uses the global import, no need for module import)
        // import JoystickController from '../src/joystick-controller.js';

        const x2 = document.querySelector("#x2");
        const y2 = document.querySelector("#y2");
        const xLeveled2 = document.querySelector("#xLeveled2");
        const yLeveled2 = document.querySelector("#yLeveled2");
        const distance2 = document.querySelector("#distance2");
        const angle2 = document.querySelector("#angle2");

        window.joystickHandlers = {
            leftJoystickHandler: {
                x: 0,
                y: 0
            },
            rightJoystickHandler: {
                x: 0,
                y: 0
            },
        }

        const rightJoystick = new JoystickController({
                x: "20%",
                y: "20%",
                leftToRight: false,
                opacity: 0.5,
                maxRange: 100,
                joystickClass: "joystick",
                distortion: true,
            },
            (data) => {
                x2.innerHTML = data.x;
                y2.innerHTML = data.y;
                xLeveled2.innerHTML = data.leveledX;
                yLeveled2.innerHTML = data.leveledY;
                distance2.innerHTML = data.distance;
                angle2.innerHTML = data.angle;
                window.joystickHandlers.rightJoystickHandler.x = data.leveledX
                window.joystickHandlers.rightJoystickHandler.y = data.leveledY
            }
        );
    </script>


<div id="joystick-container-iw7mcfl3ofhovoyeu6kn9m" class="joystick-container-iw7mcfl3ofhovoyeu6kn9m "><div id="joystick-controller-iw7mcfl3ofhovoyeu6kn9m" class="joystick-controller-iw7mcfl3ofhovoyeu6kn9m "><div id="joystick-iw7mcfl3ofhovoyeu6kn9m" class="joystick-iw7mcfl3ofhovoyeu6kn9m joystick" style="left: 70px; bottom: 70px; transition: all 0.2s ease-in-out 0s; cursor: grab;"></div></div></div>
<div id="joystick-container-p2pxmw28d2r0xgi3z111pzq" class="joystick-container-p2pxmw28d2r0xgi3z111pzq "><div id="joystick-controller-p2pxmw28d2r0xgi3z111pzq" class="joystick-controller-p2pxmw28d2r0xgi3z111pzq "><div id="joystick-p2pxmw28d2r0xgi3z111pzq" class="joystick-p2pxmw28d2r0xgi3z111pzq joystick" style="left: 50px; bottom: 50px; border-radius: 50%; transition: all 0.2s ease-in-out 0s; cursor: grab; transform: translate(-50%, 50%) rotate(3.5423rad);"></div></div></div>

</body>
</html>

const express = require('express')
const jc = require('joystick-controller')
const fs = require('fs')

/*
var joy0 = new jc(
    {
      maxRange: 70,
      level: 10,
      radius: 50,
      joystickRadius: 30,
      opacity: 0.5,
      leftToRight: false,
      bottomToUp: true,
      containerClass: "joystick-container",
      controllerClass: "joystick-controller",
      joystickClass: "joystick",
      distortion: true,
      x: "25%",
      y: "25%",
    },
    ({ x, y, leveledX, leveledY, distance, angle }) =>
      console.log(x, y, leveledX, leveledY, distance, angle)
  );
  */


const app = express()
const port = 8000

app.get('/', (req,res) => {
    //res.send("<div id='joystick-container-p2pxmw28d2r0xgi3z111pzq' class='joystick-container-p2pxmw28d2r0xgi3z111pzq '><div id='joystick-controller-p2pxmw28d2r0xgi3z111pzq' class='joystick-controller-p2pxmw28d2r0xgi3z111pzq '><div id='joystick-p2pxmw28d2r0xgi3z111pzq' class='joystick-p2pxmw28d2r0xgi3z111pzq joystick' style='left: 50px; bottom: 50px; border-radius: 50%; transition: all 0.2s ease-in-out 0s; cursor: grab; transform: translate(-50%, 50%) rotate(3.5423rad);'></div></div></div>")
    res.writeHead(200, {
        'Content-Type': 'text/html'
      });
    fs.readFile('./index.html',null,(error,data)=>{
        if(error){
            res.end('fill have error')
        }else{
            res.end(data)
        }
    })
})

app.listen(port, () => console.log('app start on : http://localhost:'+port))

Calculator with database

We’re instructed to make a java calculator using Netbeans and we must connect it to an SQL database that save the previous equations or computations we have made using the calculator that we have made.

Here’s the instructions: Calculator with database – Create a simple calculator that stores the equations in a database.

Is it possible to create an inline try without a catch like shown

I have this case where I want to run code that may have an error but I don’t need to catch it.

If the response is not valid JSON then the result should be 0:

I’d like to use this code:

var overallProgress = try {JSON.parse(text)} ? 0; 

Is it possible to the above?

Or something like this:

var overallProgress = try { JSON.parse(text)} catch(error) { 0 }; 
var overallProgress = try { JSON.parse(text)} catch(error) { overallProgress = 0 }; 

There are errors using the code above.

I found this related post below but no answer.

Is try {} without catch {} possible in JavaScript?

For anyone whose eyes I’ve hurt:

var overallProgress = 0; 
try { overallProgress = JSON.parse(text).overallProgress } 
catch(error) { overallProgress = 0 }; 

How to create register use multer with MERN

I built a register used Multer to upload image to cloudinary and used an API to frontend, When i’m submit console displays MulterError: Unexpected field when I tested on Postman it work, I guess the problem is about API.

//Api.js

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const api = createApi({
    baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_BASE_URL }),
    reducerPath: "adminApi",
    tagTypes: [ "Auth"
    ],

    endpoints: (build) => ({
      register: build.mutation({
        query: (formData) => ({
          url: "/auth/register",
          method: "POST",
          body: formData,
        }),
      }),
      login: build.mutation({
        query: ({ email, password }) => ({
          url: 'auth/login',
          method: 'POST',
          body: { email, password },
        }),
    }),
});

export const { useRegisterMutation, useLoginMutation } = api;

//routes.js

import express from "express";
import { login, register, uploadImage} from "../controller/authController.js";
import { parser } from "../config.js";

const router = express.Router();

router.post("/upload", parser.single("image"), uploadImage);
router.post("/register", parser.single("image"), register);
router.post("/login", login);

export default router;

//Controller.js

import Admin from "../models/admin.js"
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import { parser } from "../config.js";


export const register = async (req, res) => {
  try {
    const { firstname, lastname, password, email, type, public_id } = req.body;

    // Check if the user already exists
    const existingUser = await Admin.findOne({ email });
    if (existingUser) {
      return res.status(400).json({ message: "User already exists" });
    }

    const newUser = new Admin({
        firstname,
        lastname,
        password,
        email,
        role: type,
        public_id: req.file.path,
      });

    await newUser.save();

    res.status(201).json(newUser);
  } catch (error) {
    res.status(500).json({ message: "Something went wrong", error: error.message });
  }
};

export const uploadImage = async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ message: "No image file provided" });
    }

    const image = req.file;

    res.status(201).json({ image });
  } catch (error) {
    res.status(500).json({ message: "Something went wrong" });
  }
};

//config.js

import cloudinary from "cloudinary";
import { CloudinaryStorage } from "multer-storage-cloudinary";
import multer from "multer";

cloudinary.v2.config({
  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET,
});

const storage = new CloudinaryStorage({
  cloudinary: cloudinary.v2,
  params: {
    folder: "test1",
    format: async (req, file) => 'jpg', // supports promises as well
  },
});

const fileFilter = (req, file, cb) => {
  const allowedTypes = ["image/jpeg", "image/jpg", "image/png"];

  if (!allowedTypes.includes(file.mimetype)) {
    const error = new Error("Incorrect file type");
    error.code = "INCORRECT_FILETYPE";
    return cb(error, false);
  }
  cb(null, true);
}

export const parser = multer({ storage: storage, fileFilter: fileFilter });

this is my code what’s wrong, how can I fix it?

How to display an image above generated QR code with QRCode React?

I’m working with React and QRCode npm package, this, to generate a QR code. I want to display the logo over the generated QR code, so far the image is displayed like this:

enter image description here

Script code:

const generateQRCode = async (rowData) => {
  const { N_turno, orden, bahia, proceso_t, n_placa, cond_info } = rowData;
  const url = `${BASE_API}/${auth.me.tenant}/documentos/qr/`;
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: `n_orden=${orden}&n_turno=${N_turno}&n_proceso=${proceso_t}`,
  });
  const data = await response.json();

  const qrCanvas = document.createElement('canvas');
  qrCanvas.height = 600; 
  qrCanvas.width = 200

  // draws the code to the canvas
  await QRCode.toCanvas(qrCanvas, data.qr_content, { margin: 15, scale: 10 });

  const image = new Image()

   // logo source
   image.src = 'src/pages/Client/Turns/logo.png'

   // Add text to the canvas
   const ctx = qrCanvas.getContext('2d');
   ctx.font = '25px arial'; // style
   ctx.textAlign = 'center'; // center the text

   // places the text in the defined space
   ctx.fillText(`Driver: ${cond_info}`, qrCanvas.width / 2, qrCanvas.height - 120);
   ctx.fillText(`Order: ${orden}`, qrCanvas.width / 2, qrCanvas.height - 90)
   ctx.fillText(`Plate: ${n_placa}`, qrCanvas.width / 2, qrCanvas.height - 60);
   ctx.fillText(`Turn: ${data.n_turno}`, qrCanvas.width / 2, qrCanvas.height - 30);
   ctx.fillText(`Bay: ${bahia}`, qrCanvas.width / 2, qrCanvas.height - 1)

   // generates qr code and download it to the pc
   const qrImg = qrCanvas.toDataURL();
   const qrContainer = document.createElement('div');
   qrContainer.style.display = 'flex';
   qrContainer.style.flexDirection = 'column';
   qrContainer.style.alignItems = 'center';
   const qrWrapper = document.createElement('div');
   qrWrapper.style.maxWidth = '300px';
   qrWrapper.innerHTML = `
   <img src="${qrImg}" alt="QR code" />`;
   qrContainer.appendChild(qrWrapper);
   const downloadLink = document.createElement('a');
   downloadLink.href = qrWrapper.querySelector('img').src;
   downloadLink.download = `qr-code${rowData.orden}.png`;
   downloadLink.click();
};

Any help is appreciated.

Is a truly international RegExp to find words with contractions possible?

Imagine you need to develop a function that will take a string in any (say major) language and return the words with contractions from that string.

Here is what I have so far:

const contractionRegex = /(bw*[’'`´‛‘’′‵‶❛❜❝❞❮❯❛❜❝❞❨❩❪❫❬❭❮❯❰❱❴❵][w'-]*w)/gi;

It works well, but I’m wondering if I missed anything. Should I include hyphens?

js script not running on load

first time posting here so not too sure how this is going to go but here goes:

i took some code from a video on how to make a cool hacker-esque effect happen to some text when the cursor hovers over it, constantly changing each letter to a random letter. my plan was to adapt it so that it would have the effect when the page loads.

<h1 data-value="test">test</H1>
<link rel="stylesheet" href="format.css">

<script>
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
document.querySelector("h1").onmouseover = event => {
let iterations = 0;
  
const interval = setInterval(() => {
event.target.innerText = event.target.innerText.split("")
    .map((letter, index) => {
        if (index + 4 < iterations / 3) {
            return event.target.dataset.value[index];
        }
  
        return letters[Math.floor(Math.random()*26)]
    })
    .join("");
  
    if(iterations >= (4 + event.target.dataset.value.length) * 3) clearInterval(interval);
    iterations +=1
}, 30);
}
</script>

testing the file below results in the expected result from the video – when the mouse hovers over the text, the effect plays.

to get the effect that i wanted, i changed document.querySelector("h1").onmouseover = event => {... to document.querySelector("h1").onload = event => {... although it just stops the effect from playing altogether. looking it up, i found that using window.onload should wait until everything on the page has loaded but i have absolutely no clue how to implement it without having to rewrite most of the code. i also tried changing it to be in the function text() and called it using <h1 onload="text()"> although that didn’t work either.

this feels like it’s probably an easy fix but i’ve been looking for over an hour now to no avail