【问题标题】:Telegram Bot sendPhoto via node.jsTelegram Bot 通过 node.js 发送照片
【发布时间】:2017-06-06 04:06:48
【问题描述】:

我正在使用此功能通过 node.js 发送照片,但这不起作用。 电报机器人API https://www.npmjs.com/package/telegram-bot-api

var telegram = require('telegram-bot-api');

var api = new telegram({
    token: '<PUT YOUR TOKEN HERE>',
});

api.sendPhoto({
    chat_id: <YOUR CHAT ID>,
    caption: 'This is my test image',

    // you can also send file_id here as string (as described in telegram bot api documentation)
    photo: '/path/to/file/test.jpg'
})
.then(function(data)
{
    console.log(util.inspect(data, false, null));
});

但我有这个错误

 fn = function () { throw arg; };
                           ^
StatusCodeError: 403 - [object Object]

【问题讨论】:

  • 您是否使用任何节点包来实现电报机器人API?如果您没有使用任何电报机器人节点包,则 sendPhoto 函数应包含目标用户 ID 等参数以及 sendPhoto(userId, photo_url) 等照片 url
  • 我正在使用电报机器人 API 模块,但我有这个错误 fn = function () { throw arg; }; ^ StatusCodeError: 403 - [object Object]

标签: javascript java node.js telegram telegram-bot


【解决方案1】:

如电报机器人api documentation 中所述,您可以通过两种不同的方式发送文件:

1- 通过图片网址发送图片:
所以你应该将照片参数设置为图片网址,如下所示

api.sendPhoto({
    chat_id: <YOUR CHAT ID>,
    caption: 'image sent by uploading from url',

    // first you upload image on a url and send url as a parameter
    photo: 'https://whatbook.org/wp-content/uploads/2015/06/Download-Telegram-App-For-PC-Laptop-Windows-XP-7-8-MAC-OS.png'
})
.then(function(data)
{
    console.log(util.inspect(data, false, null));
});

2- 通过file_id发送图片

在电报服务器中上传的每个文件都有一个 id,您可以使用此 id 来避免将图像重新上传到电报服务器,因此在 api 中您应该传递图像文件的 file_id,如下所示:

    api.sendPhoto({
        chat_id: <YOUR CHAT ID>,
        caption: 'the image sent by file_id',

        // it is a file_id that you get when someone upload an image to 
        photo: 'AgADBAADZbo1G14XZAfdtXnWB5anFpRbYRkABMRWzQmdc4EQbPcCAAEC'
    })
    .then(function(data)
    {
        console.log(util.inspect(data, false, null));
    });

【讨论】:

  • 为什么我需要一个聊天ID?当 shomeone 点击/start 按钮时,我想向我的机器人发送照片
【解决方案2】:

我已经找到了问题所在。看起来您正在使用自己的聊天 ID 发送无效的照片。因此,您会收到 403 禁止错误(请参阅 telegram bot errors api

要使用 sendPhoto 功能,您必须使用用户的聊天 ID,而不是您的机器人用户。我对您的代码做了一些修改,以使您清楚。此代码将从 message.chatid 变量中获取用户的聊天 ID。 只需在此代码中替换您的令牌并提及您的 图片网址 并尝试一下。

PS:向这个机器人发送任何消息,它都会发送一张照片作为回应。

var telegram = require('telegram-bot-api');

var api = new telegram({
    token: 'Your BOT token',
    updates: {
                enabled: true,
                get_interval: 1000
             }
});
api.on('message', function(message)
{
    var chat_id = message.chat.id;
        console.log("This is the user's chat id"+chat_id);

api.sendPhoto({
    chat_id : message.chat.id,
    caption: 'This is my test image',
    photo: 'image.jpeg'//replace your image url here
})
.then(function(data)
{
    console.log(data);
});
});

【讨论】:

  • 如果这对您有帮助,请告诉我@Sedric Heidarizarei
  • 很高兴它能帮助你@sedric-heidarizarei
猜你喜欢
  • 1970-01-01
  • 2021-10-03
  • 2021-04-24
  • 2018-11-12
  • 2016-08-12
  • 2015-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多