0%

关于tg机器人和tg小程序

前言

tg应用开发分为机器人和小程序两部分

tg-bot

首先要在telegram的BotFather申请创建机器人,直接输入/newbot按照命令一步一步来就可以了。

成功后你会获得一串HTTP API,这个要保存下来。后续编程开发需要使用。

tgbot程序编写

bot部分参考了这位的博客

技术栈:grammY+node直接启动。以下是具体代码。

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const { Bot, InlineKeyboard } = require('grammy')

const TOKEN = ''; // bot机器人的token

const bot = new Bot(TOKEN);

const app_url='' // tg小程序在tg内的url

// 内联键盘,包含游戏按钮和访问网站按钮
const keyboard = new InlineKeyboard()
.url("开始游戏",app_url).row()

// 设置左侧目录按钮打开网页,这个功能就是让对话框左侧的菜单按钮变成打开网页的按钮
bot.api.setChatMenuButton({
menu_button: {
type: "web_app",
text: "Play",
web_app: {
url: "" // 前端域名
}
}
})

// 设置小程序快捷命令
bot.api.setMyCommands([
{ command: "start", description: "Start the bot" },
{ command: "info", description: "Get user info" },
]);

// 处理/start命令
bot.command("start", async (ctx) => {
const gifUrl = "https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif";
const caption = `Hi ${ctx.update.message.from.first_name}!\n\n这有一款很好玩的小游戏`;

await ctx.replyWithAnimation(gifUrl, {
caption: caption,
reply_markup: keyboard,
});
});

// 处理 /info 命令
bot.command("info", async (ctx) => {
const firstName = ctx.update.message.from.first_name;
const userId = ctx.from.id;

// 初始化头像URL为空字符串
let photoUrl = '';

try {
// 获取用户头像信息
const profilePhotos = await bot.api.getUserProfilePhotos(userId, { limit: 1 });

if (profilePhotos.total_count > 0) {
const fileId = profilePhotos.photos[0][0].file_id;
const file = await bot.api.getFile(fileId);
photoUrl = `https://api.telegram.org/file/bot${TOKEN}/${file.file_path}`;
}
} catch (error) {
console.error("获取头像失败: ", error);
}

// 获取用户登录信息
let userInfo = '';
let id = "";
let name = "";
try {
const chatMember = await bot.api.getChatMember(ctx.chat.id, userId);
id = chatMember.user.id;
name = chatMember.user.first_name;
userInfo = `用户信息:\nID: ${chatMember.user.id}\n名字: ${chatMember.user.first_name}\n用户名: ${chatMember.user.username}\n状态: ${chatMember.status}`;
} catch (error) {
console.error("获取用户信息失败: ", error);
}

if (photoUrl) {
await ctx.reply(`头像链接: ${photoUrl}`);
} else {
await ctx.reply("未能获取你的头像。");
}

await ctx.reply(userInfo || "未能获取你的用户信息。");
});

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

这里面注意的就是api这个类,可以参照着tg的官方文档,找到自己需要的method名,通过method名找到grammY库的案例(或者直接在搜索引擎搜索这个method,也可以找到参数)

tg小程序

tg小程序就是在tg内置的浏览器打开你指定链接的网站。

获取tg信息

然后我们在网站内一般会有获取tg用户信息之类的操作,直接引入<script src="https://telegram.org/js/telegram-web-app.js"></script>这个脚本

然后在前端项目中,通过window.Telegram.WebApp.xxx去调用需要的方法。具体可以参考这篇博客,他对tg小程序的文档作了翻译。

小程序ui

这里采用@telegram-apps/sdk这个包,可以自行去检索一下,他还有很多相关的包例如对react和vue的适配的包。