如何在没有用户输入的情况下发送消息Telegram BOT API

时间:2018-03-28 14:30:45

标签: javascript node.js api bots telegram

我使用Node.js和Telegram BOT API创建了一个简单的bot,问题是如何每隔一段时间发送一条消息,例如我想每隔5分钟说“你好”,我该怎么做?

这是我目前的代码:

var express     = require('express');
var app         = express();
var bodyParser  = require('body-parser');
const axios     = require('axios')

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({
   extended: true
})); // for parsing application/x-www-form-urlencoded
//This is the route the API will call
app.post('/new-message', function(req, res) {
  const {message} = req.body;

  //Each message contains "text" and a "chat" object, which has an "id" which is the chat id

  axios.get('some_api'+message.text.toLowerCase()+ '/')
  .then(resp => {
       axios.post('https://api.telegram.org/bot<MYTOKEN>/sendMessage', {
        chat_id: message.chat.id,
        text: `*${resp.data[0].name} (#${resp.data[0].symbol})*
        Price USD: ${resp.data[0].price_usd}
        Percent Change 24h: ${resp.data[0].percent_change_24h}
        Market Cap USD: ${resp.data[0].market_cap_usd}`,
        parse_mode:'Markdown'
  })
  .then(response => {
    // We get here if the message was successfully posted
    console.log('Message posted')
    res.end('ok')
  })
  .catch(err => {
    // ...and here if it was not
    console.log('Error :', err)
    res.end('Error :' + err)
  })

  })
  .catch(err => {
    // ...and here if it was not
    console.log('Error :', err)
    res.end('Error :' + err)
})
});

// Finally, start our server
app.listen(3000, function() {
  console.log('Telegram app listening on port 3000!');
});

1 个答案:

答案 0 :(得分:0)

你可以做到,
 您可以向特定用户或特定聊天发送消息。

但是首先,您需要获取msg.from.id'msg.chat.id',进行存储,并在需要时发送通知。

当用户加入您的漫游器,并且他按下“开始”按钮时,您可以在服务器上触发该操作:

// on global scope or wherever
 var fromId=null
 var chatId=null
// trigers when user press 'start' button
bot.onText(/\/start/, function (msg, match) {
   chatId=msg.chat.id;
   fromId = msg.from.id; // store that value and use it as param on sendMessage()
   var name = msg.from.first_name
   bot.sendMessage(fromId, `Welcome dear ${name} have fun`);
});

现在您可以创建我们的时间间隔并将其发送给用户或字符


if(fromId) {
   setInterval(() => {
     bot.sendMessage(fromId, `message to the user`),
     300,000}) // every 5 mins
   }

我希望这会有所帮助。