How to detect in Whatsapp-web.js when a number is typing or when it has received a number link and has clicked it

I need to trigger an event when a person has received the link of a bot.This bot is going to send a specific message but the event has to be when the person clicks a link, because this library has events like when the it is ready, when it receives a message. Please let me understand how to use this library because I am new to using javascript libraries. Of course I already made the connection and it is recieving messages pretty well.

const { Client } = require('whatsapp-web.js');

const client = new Client();

 client.on('qr', (qr) => {
    // Generate and scan this code with your phone
    console.log('QR RECEIVED', qr);
   });

  client.on('ready', () => {
     console.log('Client is ready!');
  });

  client.on('message', msg => {
   if (msg.body == '!ping') {
    msg.reply('pong');
  }
  });

  client.initialize();

Generating an interval based on max and min value

i’ve been working on a script in javascript to draw graphic charts and curves based on various type of data on differents mesures on each category like g, kg , tonnes for weight or C° or F for temperature etc and i left the choice of scaling for the user to enter manually the interval wich he want to cover, and this part is done.

Now i want to add an option for auto scaling and generate an optimal interval based on min and max values and by optimal i mean a good reading numbers for intervals.
the datas varies depending on categories and here all the cases of it :

    {min=0, max=45 } => [0,100]  // min= 0 so begin = 0 and 45 is 2 digits so end = 100
    {min=0, max=123 } => [0,200] // begin = 0 , 123 is 3 digits end= 200 
    {min=-45, max=201 } => [-100,300] 
    {min=-1, max=1 } => [-1,1]  
    {min=0.01, max=0.6 } => [0,1]
    {min=-0.8, max=0.9 } => [-1,1]
    {min=-335, max=-12 } => [-400,0] 
         ... and so on
    so i started by the idea of geting numbers of digits using
    
    // if min != 0 && max>=min && max!=0
    // rounding 
    begin=Math.floor(min);
    end=Math.ceil(max);
    // then if end is positive
    // geting the endvalue meaning getting the 10 exponent 
   threshold = Math.pow(10,Math.floor(Math.log10(end)));
    // loop while
       while( end % threshold !=0) end++;
    // else do the rest the same and care for negative values

this way it works but not in all cases if anyone want to improve be my guest thank you.

aws-sdk .SharedIniFileCredentials profile: ‘wasabi’ browser alternative

I am trying to implement S3 file hosting at wasabi using the examples from their docs. While setting up credentials with SharedIniFileCredentials works great in Node, I would need to use the same functionality inside the browser.

Here, I get the following error

aws_sdk__WEBPACK_IMPORTED_MODULE_1___default(…).SharedIniFileCredentials is not a constructor

This is my code (that runs great inside node, but throws an error inside a React component):

import AWS from 'aws-sdk';

export const createS3Client = (): AWS.S3 => {
  const credentials = new AWS.SharedIniFileCredentials({ profile: 'wasabi' });
  AWS.config.credentials = credentials;

  AWS.config.credentials.accessKeyId = process.env.NX_WASABI_KEY;
  AWS.config.credentials.secretAccessKey = process.env.NX_WASABI_SECRET;

  AWS.config.region = process.env.NX_WASABI_REGION;
  const ep = new AWS.Endpoint(process.env.NX_WASABI_ENDPOINT);
  const s3 = new AWS.S3({ endpoint: ep });
  return s3;
};

export const getFile = async (key: string): Promise<Buffer> => {
  const s3 = createS3Client();
  const params = {
    Bucket: process.env.NX_WASABI_BUCKET,
    Key: key,
  };

  const data = await s3.getObject(params).promise();
  return data.Body as Buffer;
};

The main reason why I am trying to do this is because I want to load images stored inside a bucket that are not publicly available into a FE (React) component.

This is the component in question:

import { useEffect, useState } from 'react';
import { getFile } from '../../lib/wasabi';

import Image from 'next/image';

import styles from './PaletteImage.module.scss';

interface Props {
  name: string;
  source: string;
}

const PaletteImage = ({ name, source }: Props) => {
  const [isLoading, setIsLoading] = useState(true); // component needs to load image data on mount
  const [error, setError] = useState<string>();
  const [base64, setBase64] = useState<string>();

  useEffect(() => {
    const parseImage = async () => {
      try {
        const buffer = await getFile(source);
        setBase64(buffer.toString('base64'));
      } catch (e) {
        setError(e.message);
      } finally {
        setIsLoading(false);
      }
    };

    parseImage();
  }, []);

  return (
    <div className={styles.imageContainer}>
      {isLoading ? (
        'loading'
      ) : error ? (
        error
      ) : (
        <Image
          alt={name}
          layout="fill"
          objectFit="contain"
          objectPosition="left top"
          src={`data:image/jpeg;base64, ${base64}`}
        />
      )}
    </div>
  );
};

export default PaletteImage;

Thanks for the help.

AWS cognitoAuthenticationProvider callback is not executing

I’m learning AWS so go easy on me if this is an obvious issue. My goal is to use the Cognito Authorizer in API Gateway to authenticate my users. That part works fine. I can get tokens to the front end and back to the api. What I’m trying to do now is pull some user attributes from the user pool so I can put them in some denormalized fields in Dynamo. It seems the best way to do that is to pull the user attributes on post (if there’s a better way please feel free to answer with that as well), which requires cognitoidentityserviceprovider.listUsers. The problem is the callback never executes. At first I was getting not authorized errors, so I updated the IAM policy, and that went away, now I get the logs outside the callback, but not inside it.

Snippet

let cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});

   
let sub = event.requestContext.authorizer.claims.sub;
let userpool = event.stageVariables.userpool;

const cogParams = {
 UserPoolId: userpool,
 Filter: "sub=""+ sub + """,
 Limit: 1
};


console.log('listing',JSON.stringify(cogParams));

await cognitoidentityserviceprovider.listUsers(cogParams, function(err, data) {
    console.info('entered callback');
      if (err) {
          console.log(err, err.stack); }
      else {
          console.log('data',data);
          }
    console.info('end callback');
});

 console.log('listed');

Expected output

listing {...}
entered callback
data {...}
end callback
listed

Actual Output

listing {...}
listed

I want to hide a popup based on the client id and using html5 local storage

I’m quite new to all of these but here us my problem
I have a popup that has a “don’t show this again” checkbox. When a user checks this, local storage should save the client id (which is in the db) and the checked status of the checkbox. Based on these two factor the popup should be displayed or hidden

Here is my code:

$(document).ready(function () {

    $('#beforelight').css('display', 'block');

    $PopUp = $('#beforelight');

    var hide = JSON.parse(localStorage.getItem('hide'));
    var id = JSON.parse(localStorage.getItem('[[clientdb.id]]'));

    if (hide, id) {
        $PopUp.hide();
    } else {
        // initialize value in case it hasn't been set already
        localStorage.setItem('hide', false);
    }

    $('#checkbox').click(function () {
        $('#beforelight').hide();
        // toggle the boolean by negating its value
        var id = JSON.parse(localStorage.getItem('[[clientdb.id]]'));
        var hide = JSON.parse(localStorage.getItem('hide'));
        localStorage.setItem('hide', !hide);
    });
});

DISCORD.JS Anti Spam System (automod)

I want to do an anti spam system with database, but when I use db it don’t warn it and when I don’t use db, it warn me, do you know why ? The anti spam system will delete all messages spammed. I do a multipurpose Bot discord so someone can help me please ?

Actually I use: [email protected]

the code:

client.on('message', async(message) => {
const db = require('quick.db')
    if(message.author.bot) return;
const usersMap = new Map();
    const msgg = await db.get(`antispammsg_${message.guild.id}`)
    if (msgg == null) msgg == 7

    const temps = db.get(`antispamtemps_${message.guild.id}`)
    if (temps == null) temps = 9000
    const TIME = 5000
const LIMIT = msgg || 7
const DIFF = temps;

    if(usersMap.has(message.author.id)) {
        const userData = usersMap.get(message.author.id);
        const { lastMessage, timer } = userData;
        const difference = message.createdTimestamp - lastMessage.createdTimestamp;
        let msgCount = userData.msgCount;
        console.log(difference);

        if(difference > DIFF) {
            clearTimeout(timer);
            console.log('Cleared Timeout');
            userData.msgCount = 1;
            userData.lastMessage = message;
            userData.timer = setTimeout(() => {
                usersMap.delete(message.author.id);
                console.log('Removed from map.')
            }, TIME);
            usersMap.set(message.author.id, userData)
        }
        else {
            ++msgCount;
            if(parseInt(msgCount) === LIMIT) {

               message.reply("Warning: Spamming in this channel is forbidden.");
              message.channel.bulkDelete(LIMIT);
               
            } else {
                userData.msgCount = msgCount;
                usersMap.set(message.author.id, userData);
            }
        }
    }
    else {
        let fn = setTimeout(() => {
            usersMap.delete(message.author.id);
            console.log('Removed from map.')
        }, TIME);
        usersMap.set(message.author.id, {
            msgCount: 1,
            lastMessage : message,
            timer : fn
        });
    }
})```

Make changes to duplicate of JSON object in array without affecting original element

I’m working on an application which consists of creating different scenes. Each scene is saved in JSON with attributes such as background image etc. Like this:

[
    {
        "sceneId": 0,
        "scenesrc": { "path": "images/image.jpg" },
        "scenename": "test",
        "scenedescription": ""
    },
    {
        "sceneId": 2,
        "scenesrc": { "path": "images/image2.jpg" },
        "scenename": "test",
        "scenedescription": ""
    }
]

Now I’m trying to make a function that duplicates one of the scenes, sets a new ID for the new scene, and push it back to the scenes array.

Here’s my code:

const getSceneById = (scenes, sceneId) => {
        return scenes.find(scene => scene.sceneId === sceneId);
    };

function duplicate(sceneId) {       
    let scenes = [{"sceneId":0,"scenesrc":{"path":"images/image.jpg"},"scenename":"test","scenedescription":""},{"sceneId":2,"scenesrc":{"path":"images/image2.jpg"},"scenename":"test","scenedescription":""}];
    const scene = getSceneById(scenes, sceneId);

    // variable for the duplicated scene
    let newScene = scene;
    newScene.sceneId = 0;

    // make an id for new scene that is larger than any other id
    for (let i = 0; i < scenes.length; i++) {
        if (parseInt(scenes[i].sceneId) > Math.floor(newScene.sceneId)) {
            newScene.sceneId = scenes[i].sceneId+1;
        }
    }

    scenes.push(newScene);
}

duplicate(2);

The problem is that when I add a scene to a new variable and give it an ID, the original scene also gets a new ID. It seems like newScene.sceneId = 0 also sets the same ID to scene. After I run the code, this is how the scenes JSON looks like:

[
    {
        "sceneId": 0,
        "scenesrc": { "path": "images/image.jpg" },
        "scenename": "test",
        "scenedescription": ""
    },
    {
        "sceneId": 0,
        "scenesrc": { "path": "images/image2.jpg" },
        "scenename": "test",
        "scenedescription": ""
    },
    {
        "sceneId": 0,
        "scenesrc": { "path": "images/image2.jpg" },
        "scenename": "test",
        "scenedescription": ""
    }
]

How can I add scene to newScene, so I can change newScene without affecting scene?

Data should be a “String”, “Array of arrays” OR “Array of objects” when trying to create csv file

I am trying to download csv file of table entries.

But every time I try to follow the steps to download the data and export them to CSV format I get this error:

Data should be a “String”, “Array of arrays” OR “Array of objects”

enter image description here

here is my code:

import React, { useEffect, useRef, useState } from "react";
import { CSVLink } from "react-csv";

export default function App() {
const [data, setdata] = React.useState("");
const [tableCellsData, setTableCellsData] = useState([]);
const csvLink=useRef()
const [bDownloadReady, setDownloadReady] = useState(false);

useEffect(() => {
    if (csvLink && csvLink.current && bDownloadReady) {
        csvLink.current.link.click();
        setDownloadReady(false);
    }
}, [bDownloadReady]);

 const getUniqueKeyFromArrayIndex = (rowNum, columnNum) => {
 return `${rowNum}-${columnNum}`;
 };

const onChangeHandler = (e) => {
console.log(e.target.name, e.target.value);

setTableCellsData({
  ...tableCellsData,
  [e.target.name]: e.target.value
 });
};

const generateTable = () => {
let table = [];
for (let i = 0; i < 3; i++) {
  let children = [];
  for (let j = 0; j < 4; j++) {
    children.push(
      <td>
        <input
          name={getUniqueKeyFromArrayIndex(i, j)}
          defaultValue=""
          Value={data}
          onChange={onChangeHandler}
        />
      </td>
    );
  }
  table.push(
    <tr key={i}>
      <td>{children}</td>
    </tr>
  );
}
return table;
};

const tabled=Object.keys(tableCellsData)

function clickHandler(actionType){

if (actionType === ‘DOWNLOAD’) {

setDownloadReady(true);

}

}

 return (
 <>
    <table>{generateTable()}</table>
    <button onClick={(e)=>clickHandler('DOWNLOAD')}>click</button>
    <CSVLink 
                data={tabled} 
                filename="data.csv"
                className="hidden"
                ref={csvLink}
                target="_blank" />
   </>
 );
}

Second button is not working. Problem with Sequence of the IDs

I am having an issue with the buttons. The second button is not working whereas the first button is working fine.
I have embaded two snippets. The Snippet 1 showing error with second button. Snippet 2 with no error.

Q: WHat is the issue?

I am using three IDs for my buttons following the index, which are, #downloadbutton, #download, #timer.

The issue is with the Sequence of these IDs in HTML of the button.

If first button IDs are #downloadbutton0, #download0, #timer0, and second button IDs are #downloadbutton2, #download2, #timer2, the second button does not work. (Please see the Snippet 1)

And if these IDs are in sequence like #downloadbutton0, #download0, #timer0 and #downloadbutton1, #download1, #timer1, both the buttons works fine. (Please see the Snippet 2)

Q: What I want?

I have used these buttons in all my posts which are more than 150 and It will take lots of time amending each and every post.

I am looking for something that can enable the buttons to work even if they are not in sequence. (By amending script)

I will be very thankfull.

  • Snippet 1
//<![CDATA[
document.querySelectorAll(".download_button").forEach(function(item, index) {
  item.addEventListener("click", function(event) {
    event.preventDefault();
    var timeleft = 45;

    var downloadTimer = setInterval(function function1() {
      document.getElementById('download' + index).style.display = "none";
      document.getElementById("timer" + index).innerHTML = "Wait " + timeleft + "";

      if (timeleft <= 0) {
        clearInterval(downloadTimer);
        document.getElementById("timer" + index).innerHTML = ""
        window.open(document.querySelector('#downloadbutton' + index + ' a').href, '_self');
        document.getElementById('download' + index).style.display = "";
      }
      timeleft -= 1;
    }, 1000);
  });
})
//]]>
.download_button {
  border: none;
  margin-top: 10px;
  margin-bottom: 10px;
  padding-top: 10px;
  padding-bottom: 10px;
  width: 195px;
  border-radius: 6px;
  line-height: 28px;
  font-size: 16px;
  font-weight: 700;
  text-transform: uppercase;
  color: #fff;
  transition: 0.4s;
  outline: none;
  margin: 5px;
}

.button-1 {
  background: #f12711;
}
  
.button-2 {
  background: #fe8c00;
}

.button-3 {
  background: #0575E6;
}

.download_button:hover {
  background: #000000;
}

.title {
  font-weight: bold;
  line-height: 22px;
  margin-bottom: 10px;
}

#download0, #download1, #download2 {
  border-radius: 5px;
  color: #fff;
  background-color: #3d3d3d;
  margin: 0 auto;
  width: 130px;
  margin-bottom: 5px;
  cursor: pointer;
}

#download0:hover, #download1:hover, #download2:hover {
  background: #a3a3a3;
  color: #000000;
  transition: 0.2s;
}

#timer0, #timer1, #timer2 {
  border-radius: 5px;
  background: #3d3d3d;
  margin: 0 auto;
  width: 130px;
  margin-bottom: 5px;
}
  
.button-center {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}
<div class="button-center">
  <div id="downloadbutton0" style="text-align: center;">
    <button class="download_button button-1">
      <div class="title">1st Button</div>
      <div class="after-title">
        <div id="download0">DOWNLOAD</div>
        <a
          href="https://www.google.com"
        ></a>
      </div>
      <div id="timer0"></div>
    </button>
  </div>
  <div id="downloadbutton2" style="text-align: center;">
    <button class="download_button button-3">
      <div class="title">2nd Button</div>
      <div class="after-title">
        <div id="download2">DOWNLOAD</div>
        <a
          href="https://www.google.com"
        ></a>
      </div>
      <div id="timer2"></div>
    </button>
  </div>
</div>
  • Snippet 2
//<![CDATA[
document.querySelectorAll(".download_button").forEach(function(item, index) {
  item.addEventListener("click", function(event) {
    event.preventDefault();
    var timeleft = 45;

    var downloadTimer = setInterval(function function1() {
      document.getElementById('download' + index).style.display = "none";
      document.getElementById("timer" + index).innerHTML = "Wait " + timeleft + "";

      if (timeleft <= 0) {
        clearInterval(downloadTimer);
        document.getElementById("timer" + index).innerHTML = ""
        window.open(document.querySelector('#downloadbutton' + index + ' a').href, '_self');
        document.getElementById('download' + index).style.display = "";
      }
      timeleft -= 1;
    }, 1000);
  });
})
//]]>
.download_button {
  border: none;
  margin-top: 10px;
  margin-bottom: 10px;
  padding-top: 10px;
  padding-bottom: 10px;
  width: 195px;
  border-radius: 6px;
  line-height: 28px;
  font-size: 16px;
  font-weight: 700;
  text-transform: uppercase;
  color: #fff;
  transition: 0.4s;
  outline: none;
  margin: 5px;
}

.button-1 {
  background: #f12711;
}
  
.button-2 {
  background: #fe8c00;
}

.button-3 {
  background: #0575E6;
}

.download_button:hover {
  background: #000000;
}

.title {
  font-weight: bold;
  line-height: 22px;
  margin-bottom: 10px;
}

#download0, #download1, #download2 {
  border-radius: 5px;
  color: #fff;
  background-color: #3d3d3d;
  margin: 0 auto;
  width: 130px;
  margin-bottom: 5px;
  cursor: pointer;
}

#download0:hover, #download1:hover, #download2:hover {
  background: #a3a3a3;
  color: #000000;
  transition: 0.2s;
}

#timer0, #timer1, #timer2 {
  border-radius: 5px;
  background: #3d3d3d;
  margin: 0 auto;
  width: 130px;
  margin-bottom: 5px;
}
  
.button-center {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}
<div class="button-center">
  <div id="downloadbutton0" style="text-align: center;">
    <button class="download_button button-1">
      <div class="title">1st Button</div>
      <div class="after-title">
        <div id="download0">DOWNLOAD</div>
        <a
          href="https://www.google.com"
        ></a>
      </div>
      <div id="timer0"></div>
    </button>
  </div>
  <div id="downloadbutton1" style="text-align: center;">
    <button class="download_button button-3">
      <div class="title">2nd Button</div>
      <div class="after-title">
        <div id="download1">DOWNLOAD</div>
        <a
          href="https://www.google.com"
        ></a>
      </div>
      <div id="timer1"></div>
    </button>
  </div>
</div>

prisma – make a field equal to another when it is created

I am working on a project. I have a user model as follows


model User {
  id          Int          @id @default(autoincrement())
  firstName   String?
  lastName    String?
  email       String       @unique
  slug        String       @unique @default()
}

Okay? I just want whenever I push a user to the database the slug to be set automatically to the id field!

I did this before in row SQL but wondering how to do this with Prisma!

I have searched and didn’t find something relevant.

I am using Postgresql as my DB.

any help?

How can I create a translation quiz type game that utilizes a string input and compares the string

I am trying to replicate this websites functionality https://www.spanishdict.com/vocabulary.

I need the string input to affect the html page.

The code from the website is below

<input id="open-input-response" type="text" placeholder="Translate &quot;ticket&quot;" class="input--PBxyYl5t js-bound" action="#" autocorrect="off" autocomplete="off" autocapitalize="none" spellcheck="false" value="">

Im not able to set an initial state in my react-native application

Im making a react-native app and I need to get some data (articles) from a GraphQL server and then, list the articles.

My problem is, when I run my app, the first time my HomeScreen component render, the state is empty and I cant see any of the articles because the response from the server takes some time to load.

I tried to use a condition where I check if the response has no errors and has finished loading, then I save the articles to the state son when I render my articleList, the state can have the articles, but it throws an error:
Too many re-renders. React limits the number of renders to prevent an infinite loop.

All I need is to have an initial state in my application before I render my home component

My code:

const HomeScreen = () => {
  const {loading, error, data} = useQuery(queryRepository.GET_ARTICLES);
  const [articles, setArticles] = useState([]);

  const filterByCategory = name => {
    setArticles(CategoryService.filterByCategoryName(name, data.items));
  };

  if (loading) {
    return <Spinner />;
  } else if (error) {
    return <Error>{error}</Error>;
  } else {
    setArticles(data.items);
  }

  return (
    <View style={globalStyles.container}>
      <View>
        <View style={globalStyles.categoryMenuContainer}>
          <CategoryMenu filterByCategory={filterByCategory} />
        </View>
        <View style={globalStyles.reviewsContainer}>
          <ArticleList articles={articles} />
        </View>
      </View>
    </View>
  );
};

How to execute a python script via javascript file in an electronjs app?

I am trying to call and execute a python script via the following javascript code in an electronjs app

function getProgramstatus(){
    
    const { exec } = require('child_process');

    exec('python python\getProgramstatus.py', (error, stdout, stderr) => {
    });
    
    let jsonData = require('.\js\programstatus.json');
    let itemData = JSON.stringify(jsonData);
    let programstatus = JSON.parse(itemData);
    
    sessionStorage.setItem('programstatus check', programstatus.status);
}

The goal of the python script is to write a value at a json file.

data1={
    "status": "12",
    "time" : time.ctime(start)
}
json_object = json.dumps( data1, indent = 4)

with open('..jsprogramstatus.json', 'w') as outfile:
    outfile.write(json_object)


#print("2")
sys.exit("2")

When i execute the python script via terminal it writes at json file, but when i call it from javascript it doen’t write at json file. Any ideas;

Excute a Javascript each X time

im new on PHP and Javascript

Im coding a progressbar on cards and this bars need to increase his % each 36 seconds by 1%

i was thinking about to type something like this


    var counterBack = moverBar(function(){
                  i++;
                  if(i<100){
                      document.getElementById('<?php echo 'progress' . $row[0] ?>').style.width = i+1+"%";
                      document.getElementById('<?php echo 'progress' . $row[0] ?>').innerHTML = i+1+"%";
                  } else {
                    clearTimeout(counterBack);
                  }

                  }, 36000);

but i assign a ID for each element on my cards to give for each card a diferent progressbar, im coding this with PHP and javascript and this is a error, and i dont know what can i do

(i know that’s not the recomended way, but this pŕogram was coded like this and im a amateur).

thank you