TelegramWebApp TelegramBot TelegramAPI

问题描述 投票:0回答:1

我尝试通过单击 MainButton 时使用 sendData() 将数据从客户端发送到电报机器人 我的客户端是在电报机器人中设置为菜单按钮的网站 下面提供的服务器是电报机器人服务器,它正在尝试接收此数据并在与用户聊天时回复该数据。 因此,当我单击 MainButton 机器人时,聊天中没有回复任何内容,我不知道这是服务器端如何处理此数据的问题,还是我客户端如何处理按钮上的 clickEvent 的问题,我实际上是如何发送它的,这是混乱的。 因此,服务器端没有 console.log,我在网页端看不到控制台,因为我只能使用它的部署版本来测试它。 我该如何解决这个问题?

import React, { useCallback } from 'react';
import Image from 'next/image';
import { useClickContext } from './Context';
import { sendDataToTelegram } from '../server/sendDataToTelegram';
import { useTelegram } from './TelegramProvider';
import CopiedMessage from './CopiedMessage';

function FullProduct() {
  const { clickedProduct } = useClickContext();
  const { title, url, price } = clickedProduct;
  const { webApp } = useTelegram();
  const tg = webApp;

  const {
    showFullProduct,
    showCopyMessage,
    setShowCopyMessage,
    setShowFullProduct,
    
  } = useClickContext()

  const handleClick = async () => {
    alert('CLICK')
    try {
      await sendDataToTelegram(title,price);
    } catch (error) {
      console.error('Error sending data to Telegram:')
    }
  }
  const onSendData = React.useCallback(()=>{
    const data = {
      title,
      price,
      url,
    }
    tg?.sendData(JSON.stringify(data))
  }, [])

  React.useEffect(()=>{
    tg?.onEvent('mainButtonClicked',onSendData);
    return () => {
      tg?.offEvent('mainButtonClicked',onSendData);
    }
  },[])


  React.useEffect(()=>{
    tg?.MainButton.setParams({
      text: 'Оформить заказ'
    })
  },[])

  const copyTextToClipboard = (text:string) => {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    setShowCopyMessage(true)

    setTimeout(()=>{
      setShowCopyMessage(false)
    },2000)

  }
  
  const handleMainButton = () => {
    tg?.MainButton.hide()
  }


  return (
    <div className='bg-black bg-opacity-50 w-full h-full z-10 fixed top-0 left-0 flex justify-center items-center'>
          <CopiedMessage/>
      <div className='bg-white w-[350px] h-[350px] sm:w-[400px] sm:h-[400px] md:w-[450px] md:h-[450px] xl:w-[600px] xl:h-[600px] relative rounded-3xl select-none flex justify-center items-center flex-col'>
        <div className='absolute top-4 bg-white rounded-tl-3xl rounded-tr-3xl w-[75%] h-16 flex flex-col justify-center items-center'>
            <span className='text-sm text-center w-4/5'>{title}</span>
            <span className='text-xl text-purple-400'>{price}</span>
        </div>
        
        <Image
        alt='product-image'
        src={url}
        width={150}
        height={200}
        loader={({ src }) => src}
        className='absolute md:w-[300px] xl:w-[350px]'
        />
        <h3 className='text-center text-sm absolute bottom-5 w-4/5'>Чтобы заказать пиши менеджеру <span className='text-purple-400 text-lg cursor-pointer' onClick={()=>{copyTextToClipboard('@vidalrain')}}>@vidalrain<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="lucide inline ml-2 lucide-copy"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>
        </span></h3>
        <button className='absolute top-2 left-2' onClick={()=>{setShowFullProduct(!showFullProduct); handleMainButton()}}>
        <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="lucide lucide-circle-x text-purple-400 transition-all hover:scale-125"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>
        </button>
      </div>
    </div>
  );
}

export default FullProduct;





const TelegramBot = require('node-telegram-bot-api');
const config = require('config');
const express = require('express');
const app = express()

const token = config.get('TELEGRAM_TOKEN');
let chatId;
let calcFlag = false;
let findItemFlag = false;
let orderButtonData = {title:'',price:''}

const bot = new TelegramBot(token, { polling: true });

bot.on('message', async (msg) => {
    chatId = msg.chat.id;
    const text = msg.text;

    if (text === '/start') {
        await bot.sendMessage(chatId, 'Привет, это Rain Zone Bot!\nПомогу подобрать одежду и рассчитать стоимость из RUB в CNY, выбери, чем я могу тебе помочь!\nPS: Если тебя интересует наш полный каталог, то жми зеленую кнопку "САЙТ" ниже', {
            reply_markup: {
                inline_keyboard: [
                    [{ text: 'Рассчитать стоимость RUB --> CNY', callback_data: 'calc' }],
                    [{ text: 'Найти конкретный товар по наименованию и цене',callback_data: 'find_item'}],
                    [{ text: 'Сделать заказ (зная наименование товара)',callback_data: 'offer_item'}]
                ]
            }
        });

    }
    if(findItemFlag){
        await bot.sendMessage(msg.from.id, 'Sorry this feature is still in process');
        findItemFlag = false;
    }
    if (calcFlag) {
        const message = msg.text;
        const messageNumber = parseFloat(message) / 12.75;
        await bot.sendMessage(chatId, messageNumber.toFixed(2) + ' CNY');
        calcFlag = false;
    }
    if(msg?.web_app_data?.data){
        try{
            const data = JSON.parse(msg?.web_app_data?.data)
            await  bot.sendMessage(chatId, 'Спасибо за обратную связь')
            await  bot.sendMessage(chatId, data.title)
        } catch (e) {
            console.log(e)
        }

    }
});

app.get('/getChatId', (req,res) => {
    res.json({chatId})
})

app.post('/inmess', (req, res) => {
    const { title, price } = req.body;
    orderButtonData = {title:title, price:price}

    bot.sendMessage(chatId, `Received data:\nTitle: ${title}\nPrice: ${price}`)
    .then(() => {
      console.log('Message sent successfully');
      res.json({ success: true });
    })
    .catch((error) => {
      console.error('Error sending message:', error);
      res.status(500).json({ success: false, error: 'Failed to send message' });
    });

  
    console.log('Received data from the website:', { title, price });
  
    res.json({ success: true });
});

bot.on('callback_query', async (msg) => {
    const buttonData = msg.data; 

    switch (buttonData) {
        case 'calc':
            await bot.sendMessage(msg.from.id, 'Введите сумму в RUB \u2192');
            await bot.sendMessage(msg.from.id, 'Формула здесь-->');
            calcFlag = true;
            break;
        case 'find_item':
            await bot.sendMessage(msg.from.id, 'Введите конкретное наименование товара или его стоимость');
            findItemFlag = true;
            break;
        default:
            break;
    }

    await bot.answerCallbackQuery(msg.id);
});
telegram telegram-bot telegram-webhook
1个回答
0
投票
Short version:
CLIENT BELOW
  const onSendData = React.useCallback(()=>{
    const data = {
      title,
      price,
      url,
    }
    tg?.sendData(JSON.stringify(data))
  }, [])

  React.useEffect(()=>{
    tg?.onEvent('mainButtonClicked',onSendData);
    return () => {
      tg?.offEvent('mainButtonClicked',onSendData);
    }
  },[])

SERVER BELOW
    if(msg?.web_app_data?.data){
        try{
            const data = JSON.parse(msg?.web_app_data?.data)
            await  bot.sendMessage(chatId, 'Спасибо за обратную связь')
            await  bot.sendMessage(chatId, data.title)
        } catch (e) {
            console.log(e)
        }

    }
© www.soinside.com 2019 - 2024. All rights reserved.