You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Telegram Bot后端处理WebApp.SendData()发送的数据?

处理Telegram Web App发送的数据(Go telebot实现)

核心逻辑

用户在Telegram Web App中调用WebApp.SendData()后,Telegram会将数据封装为WebAppData对象,以用户消息的形式发送给机器人。我们需要在代码中监听这类消息事件,解析并处理传入的数据。

修改后的完整代码

package main

import (
	"log"
	"os"
	"time"

	tele "gopkg.in/telebot.v3"
)

func main() {
	pref := tele.Settings{
		Token:  os.Getenv("TOKEN"),
		Poller: &tele.LongPoller{Timeout: 10 * time.Second},
	}

	b, err := tele.NewBot(pref)
	if err != nil {
		log.Fatal(err)
		return
	}

	// 处理/hello命令(可添加触发Web App的按钮)
	b.Handle("/hello", func(c tele.Context) error {
		webAppBtn := &tele.WebApp{
			URL: "你的Web App实际地址",
		}
		replyMarkup := &tele.ReplyMarkup{
			InlineKeyboard: [][]tele.InlineButton{
				{{Text: "打开Web App", WebApp: webAppBtn}},
			},
		}
		return c.Send("点击按钮打开Web App", replyMarkup)
	})

	// 监听并处理Web App发送的数据
	b.Handle(tele.OnWebAppData, func(c tele.Context) error {
		// 获取WebAppData对象
		webAppData := c.Message().WebAppData
		// 提取发送的原始数据
		receivedData := webAppData.Data

		log.Printf("收到Web App数据: %s", receivedData)

		// 根据业务需求处理数据,示例:回复用户
		return c.Replyf("已收到你的数据:%s", receivedData)
	})

	b.Start()
}

关键代码说明

  • 事件监听:使用tele.OnWebAppData作为触发器,这是telebot专门用于接收Web App数据的事件类型。
  • 数据获取:通过c.Message().WebAppData.Data直接获取Web App发送的内容,这对应WebApp.SendData()传入的参数值。
  • 业务扩展:如果发送的是JSON格式数据,可使用encoding/json包解析为结构体:
    import "encoding/json"
    
    type CustomData struct {
        Username string `json:"username"`
        Score    int    `json:"score"`
    }
    
    // 在处理函数中解析
    var data CustomData
    err := json.Unmarshal([]byte(receivedData), &data)
    if err != nil {
        log.Println("数据解析失败:", err)
        return c.Reply("数据格式错误")
    }
    

注意事项

  • 需在BotFather中配置Web App允许的域名,否则Web App无法正常加载。
  • WebApp.SendData()传输的数据由Telegram加密,无需额外处理安全问题。

内容的提问来源于stack exchange,提问作者sandji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 17:45:18