telegram mini app和game实现登录功能

接上一篇文章,我们在创建好telegram机器人后,开始开发小游戏或者mini App,那就避免不了登录功能。

公开链接
bot设置教程:https://lengmo714.top/6e79860b.html
参考教程参考教程,telegram已经给我们提供非常多的api,我们在获取用户信息的时候只需要调用对应的api即可。

拉起登录

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

  // 初始化头像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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南锋1

您的打赏是我继续创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值