南锋

南奔万里空,脱死锋镝余

telegram获取用户信息

接上一篇文章,我们在创建好telegram机器人后,开始开发小游戏或者mini App,那就避免不了登录功能。这样就需要接入用户的信息。

参考教程参考教程,telegram已经给我们提供非常多的api,我们在获取用户信息的时候只需要调用对应的api即可。

获取用户信息

获取用户信息,我这里主要是获取了用户的头像、id、用户名、名字和状态。
用到2个api,getChatMembergetUserProfilePhotos
用法分别如下:
获取用户头像:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 初始化头像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);
}

获取用户登录信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 || "未能获取你的用户信息。");

完整代码

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
import { Bot, InlineKeyboard } from "https://deno.land/x/grammy@v1.25.0/mod.ts";

const TOKEN = ''; // bot机器人的token
const bot = new Bot(TOKEN);

// 处理 /start 命令
bot.command("start", 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();

运行代码看先现象

执行下面命令,运动代码

1
deno run --allow-net ts脚本.ts

回到和机器人的对话界面,发送/start,我们就可以看到机器人返回的用户登录信息和头像了,如下图:
对话框;

+