我一直遵循Soham Kamani's Telegram bot tutorial,并设法按照教程中的步骤设置机器人并进行响应。
在过去的一周中,我添加了代码来告诉该机器人我想做什么,然后尝试通过将其上传到新的now服务器并相应地更改Webhook来对其进行测试。
但是,该机器人完全没有响应。而且,当我尝试使用原始服务器还原更改并进行测试时,该机器人仍然没有响应。
我不确定自己在做什么错,下面是我的代码片段:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const axios = require('axios')
/*
Various functions and variables for the bot here
that are used below
*/
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
let outputString = "";
if (message.text.toLowerCase().indexOf('start') === 0) {
outputString = newGame() + "\n\n Reply with a number to move it: " + printValidMoves();
axios.post('https://api.telegram.org/<bot ID here>/sendMessage', {
chat_id: message.chat.id,
text: outputString
})
.then(response => {
// We get here if the message was successfully posted
console.log('Message posted')
return res.end('ok')
})
.catch(err => {
// ...and here if it was not
console.log('Error :', err)
return res.end('Error :' + err)
})
}
else if (ValidTileNum.indexOf(message.text.toLowerCase()) !== -1) {
let tuple = ValidTileMoves[ValidTileNum.indexOf(message.text.toLowerCase())];
swapTiles(Grid, BlankSpace[i], BlankSpace[j], tuple[0], tuple[1]);
if (isSolved())
{
outputString = printGrid(Grid) + "\n\n YOU WIN!";
}
else
{
outputString = printGrid(Grid) + "\n\n Reply with a number to move it: " + printValidMoves();
}
axios.post('https://api.telegram.org/<bot ID here>/sendMessage', {
chat_id: message.chat.id,
text: outputString
})
.then(response => {
// We get here if the message was successfully posted
console.log('Message posted')
return res.end('ok')
})
.catch(err => {
// ...and here if it was not
console.log('Error :', err)
return res.end('Error :' + err)
})
}
/*
if (message.text.toLowerCase().indexOf('start') === 0) {
axios.post('https://api.telegram.org/<bot ID here>/sendMessage', {
chat_id: message.chat.id,
text: outputString
})
.then(response => {
// We get here if the message was successfully posted
console.log('Message posted')
return res.end('ok')
})
.catch(err => {
// ...and here if it was not
console.log('Error :', err)
return res.end('Error :' + err)
})
}
*/
//else
res.end()
});
// Finally, start our server
app.listen(3000, function() {
console.log('Telegram app listening on port 3000!');
});
以下是我的package.json文件:
{
"name": "my-telegram-bot",
"version": "1.0.0",
"description": "Testing out a telegram bot",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start" : "node index.js"
},
"author": "Wen Yao",
"license": "ISC",
"dependencies": {
"axios": "^0.17.1",
"body-parser": "^1.18.2",
"express": "^4.16.2"
}
}