[英]How to send messages without user inputs Telegram BOT API
I made a simple bot with Node.js and the Telegram BOT API and the question is how can I send a message each certain time, for example I want to say "hello" every 5 minutes, What do I have to do ? 我使用Node.js和Telegram BOT API制作了一个简单的机器人,问题是如何每隔一定的时间发送一条消息,例如我想每5分钟说一次“ hello”,我该怎么办?
Here is my current code: 这是我当前的代码:
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!');
});
you can do that, 你可以做到的
you can send messages to a specific user or to a specific chat. 您可以将消息发送给特定用户或特定聊天。
But first you need to get the msg.from.id
or 'msg.chat.id'
, store it, and send notifications whenever you need. 但是首先,您需要获取
msg.from.id
或'msg.chat.id'
,进行存储,并在需要时发送通知。
when a user joins your bot, and he press the 'start' button you can trigger that action, on your server: 当用户加入您的漫游器,并且他按下“开始”按钮时,您可以在服务器上触发该操作:
// 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`);
});
Now you can create our time intervals and send to user or char 现在您可以创建我们的时间间隔并发送给用户或char
if(fromId) {
setInterval(() => {
bot.sendMessage(fromId, `message to the user`),
300,000}) // every 5 mins
}
I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.