【问题标题】:How to send messages without user inputs Telegram BOT API如何在没有用户输入的情况下发送消息 Telegram BOT API
【发布时间】:2018-09-07 07:15:15
【问题描述】:

我用 Node.js 和 Telegram BOT API 制作了一个简单的机器人,问题是我如何在每个特定时间发送一条消息,例如我想每 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!');
});

【问题讨论】:

    标签: javascript node.js api bots telegram


    【解决方案1】:

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

    但首先您需要获取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
       }
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2016-02-23
      • 1970-01-01
      • 2016-05-09
      • 2020-11-13
      • 1970-01-01
      • 2012-05-25
      相关资源
      最近更新 更多