Following the previous article, after creating a Telegram bot, we began developing a mini game or mini app, which inevitably involves a login feature. This means we need to access user information.
Reference Guide Reference Guide, Telegram provides many APIs, and to retrieve user information, you simply need to call the appropriate API.
Retrieve User Information
Here, the main information retrieved is the user’s avatar, ID, username, name, and status. We use two APIs, getChatMember and getUserProfilePhotos. Usage examples: Retrieve User Avatar:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Initialize avatar URL as an empty string let photoUrl = '';
try { // Get user avatar information const profilePhotos = await bot.api.getUserProfilePhotos(userId, { limit: 1 });
// Retrieve user login information 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 = `User Information:\nID: ${chatMember.user.id}\nName: ${chatMember.user.first_name}\nUsername: ${chatMember.user.username}\nStatus: ${chatMember.status}`; } catch (error) { console.error("Failed to retrieve user information: ", error); }
if (photoUrl) { await ctx.reply(`Avatar URL: ${photoUrl}`); } else { await ctx.reply("Failed to retrieve your avatar."); }
await ctx.reply(userInfo || "Failed to retrieve your user information."); });
// Start the bot bot.start();
Run the Code and Observe the Output
Execute the following command to run the code:
1
deno run --allow-net your-script.ts
Go back to the conversation with your bot and send /start. You will see the bot returning the user login information and avatar, as shown below: ;