yagop / node-telegram-bot-api

Telegram Bot API for NodeJS
MIT License
8.17k stars 1.5k forks source link

Repetition Problem With Telegram Bot In Node #1082

Closed kshontop closed 1 year ago

kshontop commented 1 year ago

I am developing a Telegram bot that uses the Coinbase API to allow users to make cryptocurrency payments. Everything is working fine until I encountered a problem with the charge creation loop. After creating a charge and pressing the back button to return to the main menu, if I decide to create a new charge, the bot gets stuck in a strange loop and essentially sends the message once again every time I input something. It's like the code never breaks the switch and always waits for input. I am using Node.js with the node-telegram-bot-api library to create the Telegram bot. If anyone has an idea of what's going wrong, I would be happy to hear it. Thanks in advance!

```
if (query.data === "button3") {
      const username = query.from.username;
      const userId = query.from.id;

      bot.sendMessage(
        chatId,
        "ℹ️ Entrez le montant que vous souhaitez ajouter à votre compte :",
      ).then((message) => { 

        bot.on("message", (replyMessage) => {
          const amount = parseFloat(replyMessage.text.replace(",", "."));

          if (isNaN(amount) || amount < 5) {
            bot.sendMessage(
              chatId,
              "❌ Montant invalide. Le montant minimum est de 5€."
            );
            return;
          }
          const data = JSON.stringify({
            "name": `${username}`,
            "metadata": {
              "customer_id": userId
            },
            "local_price": {
              "amount": amount.toFixed(2),
              "currency": "EUR"
            },
            "pricing_type": "fixed_price"
          });
          const config = {
            method: 'post',
            url: 'https://api.commerce.coinbase.com/charges',
            headers: { 
              'Content-Type': 'application/json', 
              'Accept': 'application/json',
              'X-CC-Api-Key': 'b7db06a4-db83-419f-9677-94de4b06bfa3',
            },
            data: data
          };
          axios(config)
            .then((response) => {
              paymentUrl = response.data.data.hosted_url;
              console.log(`Succès de la charge : ${paymentUrl}`);
              bot.editMessageText(
                `Cliquez sur le lien ci-dessous pour payer ${amount.toFixed(2)}€ : \n\n➡️ ${paymentUrl}`,
                {
                  chat_id: chatId,
                  message_id: message.message_id, 
                  reply_markup: {
                    inline_keyboard: [
                      [{text: "🔎 Vérifier la transaction", callback_data:"verify_charges"}],
                      [{ text: "⬅️ Retour", callback_data: "back" }]
                    ],
                  },
                }
              );
            })
            .catch((error) => {
              console.log("Error creating Coinbase charge:", error);
            });
        });
      });
    }
jals-es commented 1 year ago

Hi, I have the same problem. Any solution?

kshontop commented 1 year ago

Salut, j'ai le même problème. Toute solution?

I haven't found the solution yet

jals-es commented 1 year ago

Salut, j'ai le même problème. Toute solution?

I haven't found the solution yet

I found the solution a few moments ago.

The problem is caused because .on works as declaration, so if you repeat it, it will be declared multiple times.

In your example, you are declaring .on inside .sendMessage, so it will be declared all times that .sendMessage is executed.

You have to be sure that .on is declared once.

kshontop commented 1 year ago

Add me on Discord please Accesed#1111

kshontop commented 1 year ago

Salut, j'ai le même problème. Toute solution ?

je n'ai pas encore trouvé la solution

J'ai trouvé la solution il y a quelques instants.

Le problème est dû au fait que .on fonctionne comme une déclaration, donc si vous le répétez, il sera déclaré plusieurs fois.

Dans votre exemple, vous déclarez .on dans .sendMessage, il sera donc déclaré à chaque fois que .sendMessage sera exécuté.

Vous devez être sûr que .on est déclaré une fois.

please add me

danielperez9430 commented 1 year ago

@ChezVolt you test to use "bot.once('... " is similar to bot.on, but is only call one time and the event removed

kshontop commented 1 year ago

mais

Thanks for the answer do you have discord to talk about it in more detail?