接上一篇文章,我們在創建好telegram機器人后,開始開發小游戲或者mini App,那就避免不了登錄功能。
公開鏈接
bot設置教程:https://lengmo714.top/6e79860b.html
參考教程參考教程,telegram已經給我們提供非常多的api,我們在獲取用戶信息的時候只需要調用對應的api即可。
拉起登錄
我這里主要是獲取頭像、id、名字和狀態。
用到2個api,getChatMember
和getUserProfilePhotos
。
用法分別如下:
獲取頭像:
// 初始化頭像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);}
獲取登錄id:
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 || "未能獲取信息。");
完整代碼
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();
運行代碼看先現象
執行下面命令,運動代碼
deno run --allow-net ts腳本.ts