You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Telegram API上传个人头像遇"Api is not a constructor"错误求助

解决Telegram个人账号上传头像时"Api is not a constructor"错误

问题根源

你当前使用的telegram-bot-api是专为机器人账号设计的库,不支持个人用户账号的认证与操作,且该库中根本不存在Api构造函数,这就是报错的直接原因。个人账号需要使用官方推荐的gramjs库(npm包名为telegram)。

解决方案步骤

1. 替换依赖包

先卸载错误的包,安装正确的gramjs及配套依赖:

npm uninstall telegram-bot-api
npm install telegram input mime-types

2. 重写适配个人账号的代码

以下是完整的可运行代码,包含会话持久化、账号认证、头像上传功能:

const { TelegramClient, StringSession, Api } = require('telegram');
const input = require('input');
const fs = require('fs');

// 替换为你的API ID和Hash(从my.telegram.org获取)
const apiId = 123456;
const apiHash = 'your_api_hash_here';
// 会话存储文件,用于持久化登录状态
const SESSION_FILE = 'session.txt';

// 读取已保存的会话(首次运行无文件则忽略)
let sessionString = '';
try {
    sessionString = fs.readFileSync(SESSION_FILE, 'utf8');
} catch (e) {}

const client = new TelegramClient(new StringSession(sessionString), apiId, apiHash, {
    connectionRetries: 5,
});

async function main() {
    await client.start({
        phoneNumber: async () => await input.text('请输入你的手机号:'),
        password: async () => await input.text('请输入两步验证密码(如果有):'),
        phoneCode: async () => await input.text('请输入收到的验证码:'),
        onError: (err) => console.error('认证错误:', err),
    });

    // 保存会话到文件,下次启动无需重新认证
    fs.writeFileSync(SESSION_FILE, client.session.save());
    console.log('会话已保存,下次启动可直接登录');

    // 上传头像:替换为你的图片路径
    try {
        const result = await client.invoke(new Api.UploadProfilePhoto({
            file: await client.uploadFile({
                file: './test.png',
                workers: 1,
            }),
        }));
        console.log('头像上传成功:', result);
    } catch (error) {
        console.error('上传失败:', error);
    }
}

main().catch(console.error);

关键说明

  • 会话管理:使用StringSession持久化登录状态,避免每次运行都重复输入验证码
  • 认证流程:gramjs的client.start()会自动处理完整的个人账号认证流程(手机号、验证码、两步验证)
  • 头像上传:通过client.invoke(new Api.UploadProfilePhoto())调用官方API,client.uploadFile()负责处理本地文件的上传准备

原代码的其他错误点

  • 错误引入FileBox、InputFile等不存在于telegram-bot-api的对象
  • 手动修改client.auth.user的方式不符合Telegram库的规范
  • 错误使用仅支持机器人的telegram-bot-api处理个人账号认证

内容的提问来源于stack exchange,提问作者user20372902

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:16:06