使用电报机器人

时间:2016-11-07 18:42:08

标签: node.js openshift telegram-bot unirest

编辑:在我的覆盆子pi上只测试GET-Request(没有电报api)的代码。我将其写入文件,而不是发送tg消息。我发现魔法发生在这一部分:

req.end(function (res) {
    if (res.error) throw new Error(res.error);

    console.log(res.body);
  });

console.log(res.body)给我这个输出(表格/列的正确名称):

{ test: 
   { columns: [ 'eventID', 'event_desc' ],
     records: 
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object] ] } }

但如果我用fs.appendFile("getrequest.log",res.body + "\n");替换它,我只会得到:

[object Object]

当我使用其他功能时,知道为什么结果会发生变化吗?

原始问题:

我对nodejs和电报机器人api非常陌生。

我尝试的是向URL发出HTTP GET请求,该URL以JSON格式返回数据。我希望机器人将结果发送到聊天中。

我的机器人在openshift上运行,并使用this guide and code sample在NodeJS中编写。为了找出GET请求的代码,我使用了postman。它已经帮助我对此URL发出POST请求。所以我使用unirest和这段代码:

bot.onText(/\/list (.+)/, function (msg, match) {

  var fromId = msg.chat.id;
  var eventDb = match[1];
  var eventURL = "https://api.italianrockmafia.ch/api.php/";
  eventURL += eventDb;
  var unirest = require("unirest");

  var req = unirest("GET", eventURL);

  req.headers({
    "cache-control": "no-cache"
  });

  req.end(function (res) {
    if (res.error) throw new Error(res.error);

    console.log(res.body);
  });
  bot.sendMessage(fromId, req);
});

所以我不确定在bot.sendMessage();中我必须使用哪个值以及必须使用此功能的位置。我尝试了多种组合(reqresres.body)但是没有一种组合。

如果我像上面一样使用代码,则日志显示为message ist empty。 当我将最后一行更改为:

req.end(function (res) {
    bot.sendMessage(fromId, res);
   if (res.error) throw new Error(res.error);

   console.log(res.body);
 }); 

日志只会抛出一个错误的文件标识符/ HTTP URL指定"在电报模块的文件中它自己。此消息显示在每个命令(即使是正在运行的命令)。

所以我的两个问题是:

  • 我需要发送哪个值?
  • 我需要在代码中将bot.sendMessage放入哪里?

我真的在这两个人身上挣扎,所以非常感谢一些帮助!

2 个答案:

答案 0 :(得分:0)

我认为这与inputfile限制

有关
  

为Telegram提供要发送的文件的HTTP URL。电报   将下载并发送文件。照片最大尺寸为5 MB,最大尺寸为20 MB   其他类型内容的最大值。

答案 1 :(得分:0)

原来我不知道如何处理JSON。第8层错误......