0

I have a function that checks for the presence of user data in the table, returns the status (true or false) and passes the values to the next function that processes this value and processes the corresponding logic. The status is transmitted correctly and there are no problems with it, even the correct logic of processing all the data and saving them in the table occurs, however, for some reason, the next new user after sending the contact does not receive a response from the user, as if return is passed to the function. I apologize in advance for the quality of the language, I write through a translator. I really hope for your help!

const userTempData = {}; 
//Функция первого сообщения
bot.onText(/\/start/, async (msg) => {
  const chatId = msg.chat.id;
  await functions.checkUserChatId(chatId, bot, db, msg, menubutton, userTempData, userStatuses);
});




//Функция проверки БД на данные
async function CheckUserDB(chatId, db, userStatuses) {
  const selectQuery = `
    SELECT chatId, Имя, Номер_телефона FROM users WHERE chatId = ?
  `;

 try {
    const row = await new Promise((resolve, reject) => {
      db.get(selectQuery, [chatId], (err, row) => {
        if (err) {
          reject(err);
        } else {
          resolve(row);
        }
      });
    });

    const userStatus = { firstuser: false };

    if (!row) {
      userStatus.firstuser = true;
      } else {
      userStatus.firstuser = false;
      }
    userStatuses[chatId] = userStatus;
    return userStatus;
} catch (error) {
  console.error('Ошибка при выполнении запроса: ', error.message);
  }
}

// Функция проверки пользователя на факт общения
async function checkUserChatId(chatId, bot, db, msg, menubutton, userTempData, userStatuses) {

  const phoneNumber = userTempData[chatId]?.phone;
  const name = userTempData[chatId]?.name;
  const numbercar = userTempData[chatId]?.numbercar;
  const modelcar = userTempData[chatId]?.modelcar;

  const startmsg = "Добро пожаловать! Для продолжение работы, нам нужен Ваш номер!";
  const keyphoneKB = {
    keyboard:[
      [{text: 'Отправить контакт', request_contact: true}],
        ],
    resize_keyboard: true,
    one_time_keyboard: true
  };
      const userStatus = await CheckUserDB(chatId, db, userStatuses);

      if (userStatus) {
      bot.sendMessage(chatId, startmsg, {reply_markup: keyphoneKB})
      .then(() => {
        if (!userTempData[chatId]) {
          userTempData[chatId] = {};
        }
        let startdataSaved = false;
        userStatus.firstuser = false;

        bot.on('contact', async (msg) => {
          const chatId = msg.chat.id;
          if (!userTempData[chatId]) {
            return;
          }

            if (!userTempData[chatId].phone) {
              const phoneNumber = msg.contact.phone_number; 
              userTempData[chatId].phone = phoneNumber;

              userTempData[chatId].step = "name"
              bot.sendMessage(chatId, 'Как мы можем к Вам обращаться?', {reply_markup: JSON.stringify({ hide_keyboard: true })});
            }
          });

        bot.on('message', async (msg) => {
          const chatId = msg.chat.id;
          if (!userTempData[chatId]) {
            return;
          }
              if (userTempData[chatId].step === "name") {
                const name = msg.text;
                if (userTempData[chatId]) {
                userTempData[chatId].name = name;
              }

              userTempData[chatId].step = "numbercar"
              bot.sendMessage(chatId, 'Укажите Гос-номер Вашего авто в формате "А111АА111"');
              } else if (userTempData[chatId].step === "numbercar") {
                const numbercar = msg.text;
                if (userTempData[chatId]) {
                userTempData[chatId].numbercar = numbercar;
              }

              userTempData[chatId].step = "modelcar"
              bot.sendMessage(chatId, 'Укажите марку Вашего авто');
              } else if (userTempData[chatId].step === "modelcar") {
                const modelcar = msg.text;
                if (userTempData[chatId]) {
                userTempData[chatId].modelcar = modelcar;
              }

              bot.sendMessage(chatId, 'Спасибо, теперь Вы можете продолжить работу с ботом!', menubutton)

              const insertQuery = `
                INSERT INTO users (chatId, Имя, Номер_телефона, Гос_номер, Модель_авто)
                VALUES (?, ?, ?, ?, ?)
              `;

              const values = [chatId, userTempData[chatId].name, userTempData[chatId].phone, userTempData[chatId].numbercar, userTempData[chatId].modelcar];

              db.run(insertQuery, values, function(err) {
                if (err) {
                  console.error('Ошибка при вставке данных: ', err);
                  return;
                }

                console.log('Данные в таблице');
                startdataSaved = true;
              });
            }
              if (startdataSaved) {
                delete userTempData[chatId];
                firstuser = false;
                return;
                  }
                });
              });
            } else {

      const menumsg = "Мастерская приветствует Вас! Что вы хотите сделать сейчас?";
      const buttonsmenu = [
        [{ text: 'Создать бронь', callback_data: 'reserv' }],
        [{ text: 'Моя бронь', callback_data: 'editreserv' }],
        [{ text: 'Контакты', callback_data: 'contact' }],
      ];

      const keyboardmenu = {
        inline_keyboard: buttonsmenu,
      };

      bot.sendMessage(chatId, menumsg, { reply_markup: keyboardmenu });
            }
          }

I tried to remove the dependency on the status, but this did not affect the logic of the bot in any way. I tried to rewrite the logic of processing received messages and use instead .step conditions (!UserTempData.name), it also does not change the situation:(

0 Answers0