南锋

南奔万里空,脱死锋镝余

telegram获取用户发送的消息并上报给服务器

最近做的tg mini app投放后发现一些用户的操作异常,但是又不知道为什么,于是加上了这个功能,看用户是否给bot机器人发送了反馈消息,我们没有收到。

思路

bot接收到用户发送的消息,然后将消息转发给服务器,从而达到我们的目的

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { Bot, InlineKeyboard } from "https://deno.land/x/grammy@v1.25.0/mod.ts";
const TOKEN = ''; //你的机器人token
const bot = new Bot(TOKEN);
const serverUrl = ""; // 你的服务器地址
bot.on("message:text", async (ctx) => {
const messageText = ctx.message.text;
const chatId = ctx.message.chat.id;
const firstName = ctx.update.message.from.first_name;
const eventtime = (await getCurrentTime()).toString();
const payload = {
uid: chatId,
message: messageText,
};
// 将数据发送到服务器
try {
const response = await fetch(serverUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 解析服务器响应
const responseData = await response.json();
console.log("服务器响应:", responseData);
} catch (error) {
console.error("发送消息到服务器失败:", error);
}
});

// 启动机器人
bot.start();
+