node.js 的构建工具_如何使用Node.js和Now构建电报机器人

node.js 的构建工具

介绍 ( Introduction )

Serverless deployment, the intriguing topic grabbing a lot of attention from rookies and veterans alike in the tech ecosystem is finally here. In this article we'll be taking a practical approach to serverless deployment, also referred to as FaaS (Function as a Service). Serverless architecture, simply put is a way to build and run applications and services without managing server in infrastructure. Practical approach? We'll be building a telegram weather bot using node.js, which will be hosted on now.

无服务器部署,一个引人入胜的话题,吸引了技术生态系统中的新秀和退伍军人。 在本文中,我们将采用一种无服务器部署的实用方法,也称为FaaS(功能即服务)。 简单地说,无服务器架构是一种无需管理基础架构中的服务器即可构建和运行应用程序和服务的方法。 实用的方法? 我们将使用node.js构建一个电报气象机器人,该机器人现在将托管。

要求 ( Requirements )

使用BotFather注册电报机器人 ( Registering a telegram bot using BotFather )

Yes! you guessed right. BotFather is also a bot. Before we go on to the nitty-gritty of coding our bot, we'll need to create and register the bot with BotFather in order to get an API key. We'll head over to BotFather and follow the steps outlined below to create our bot.

是! 你猜对了。 BotFather也是一个机器人。 在继续对机器人进行编码之前,我们需要创建一个BotFather并将其注册,以获取API密钥。 我们将前往BotFather,并按照以下概述的步骤来创建我们的机器人。

设置项目 ( Setting up the project )

In a directory of your choice, you'll create a new folder that will house our bot. In that folder, we'll initialize our project by running npm init, follow the prompts to initialize the application. In this directory, we'll need two files index.js which will contain our base bot code and the.env file that'll contain our environment variables.

在您选择的目录中,您将创建一个新文件夹,该文件夹将容纳我们的机器人。 在该文件夹中,我们将通过运行npm init初始化项目,并按照提示初始化应用程序。 在此目录中,我们将需要两个文件index.js ,其中将包含基本的bot代码,而.env文件中将包含环境变量。

We'll need to install a few packages, which will come in handy while building our weather bot.

我们将需要安装一些软件包,这些软件包将在构建天气机器人时派上用场。

With all those dependencies installed, we'll head over to openweathermap in other to get an API key to access weather data.

安装了所有这些依赖项后,我们将转到其他的openweathermap以获得获取天气数据的API密钥。

编码我们的机器人 ( Coding our bot )

As complicated as building a bot sounds, we'll be building one in this tutorial with less than 100 lines of code. Yes! that's possible.

尽管构建机器人听起来很复杂,但在本教程中,我们将用不到100行的代码来构建一个机器人。 是! 那是可能的。

Importing our packages

导入我们的包

In the previous section, we installed a few packages. In our index.js file we'll be importing and initializing those packages like so:

在上一节中,我们安装了一些软件包。 在我们的index.js文件中,我们将像这样导入和初始化这些包:

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
require("dotenv").config();
const axios = require("axios");`
app.use(bodyParser.json());
app.use(
  bodyParser.urlencoded({
    extended: true
  })
);
...

Setting up the **.env file**

设置**。 环保文件**

Most people will condemn our use of an env file because we have three variables in there at the moment. But hey! we can't foresee how large our bot can get. It's best practice to have these variables to be defined separately and properly referenced when needed. After getting our openweather and telegram API key and token, we'll add them in our .env file like so.

大多数人会谴责我们使用env文件,因为目前我们在其中有三个变量。 但是,嘿! 我们无法预见我们的机器人能达到多大的规模。 最好的做法是分别定义这些变量,并在需要时正确引用。 取得openweather和电报API密钥和令牌后,我们将其添加到.env文件中,如下所示。

OPENWEATHER_API_KEY = XXXXXXXXXXXXXXXXXXXXX
OPENWEATHER_API_URL = "http://api.openweathermap.org/data/2.5/weather?q="
TELEGRAM_API_TOKEN = XXXXXX:XXXXXXXXXXXXXXX

Major keystrokes

主要按键

After defining our environment variables and importing our packages, we'll go on to writing our bot's base logic. Our bot will make use of three major methods, namely:

定义环境变量并导入包之后,我们将继续编写机器人的基本逻辑。 我们的机器人将使用三种主要方法,即:

Before we code these methods, we'll define two major URL endpoints, our telegram API endpoint and the openweathermap endpoint.

在编码这些方法之前,我们将定义两个主要的URL端点,即电报API端点和openweathermap端点。

let telegram_url = "https://api.telegram.org/bot" + process.env.TELEGRAM_API_TOKEN +"/sendMessage";
let openWeatherUrl = process.env.OPENWEATHER_API_URL;

/start_bot is our apps endpoint, which will be hooked onto the telegram API webhook, we'll talk about this in when our bot is ready for deployment.

/start_bot是我们的应用程序终结点,它将被挂接到电报API Webhook上,我们将在准备好进行部署的bot中讨论这一点。

app.post("/start_bot", function(req, res) {
const { message } = req.body;
let reply = "Welcome to telegram weather bot";
let city_check = message.text.toLowerCase().indexOf('/');
if(message.text.toLowerCase().indexOf("hi") !== -1){
    sendMessage(telegram_url,message,reply,res);
}else if( (message.text.toLowerCase().indexOf("check") !== -1) && (city_check !== -1 ) ){
    city = message.text.split('/')[1];
    get_forecast(city).then( response =>{
        post_forecast(telegram_url,response,message,res)
    });
}else{
    reply = "request not understood, please review and try again.";
    sendMessage(telegram_url,message,reply,res);
    return res.end();`
}
});
...

Surprisingly that's all that defines our bot in 18 lines. How does our work?.

令人惊讶的是,这一切都以18行定义了我们的机器人。 我们如何工作?

To get a weather forecast, all we need do is send Check /Lagos, it then returns it's 232 degrees in Lagos. So it looks out for a keyword Check and gets the city, which is stated after the /.

要获得天气预报,我们需要做的就是发送Check /Lagos ,然后返回拉各斯的232度。 因此,它寻找关键字Check并获取城市,该城市在/之后声明。

Demystifying the 18 lines

揭开18行的神秘面纱

In the first four lines, we're parsing our request body and storing it inside a message object. We'll then initialize our welcome message inside the reply variable and check if the text coming from the user contains a forward slash. Following these four lines are three conditions, with the first checking if the message is a simple "Hi" or "hi", if it is, the sendMessage(); method is invoked. This method accepts four parameters which you can see in the code above. The second condition checks if the incoming message contains the check keyword and also contains a city. If this condition evaluates to be true, it calls the get_forecast(); method which returns a response which is a promise we'll pass to our post_forecast(); method. This method is what replies the user with the current weather conditions.

在前四行中,我们将解析请求正文并将其存储在消息对象中。 然后,我们将在Reply变量中初始化欢迎消息,并检查来自用户的文本是否包含正斜杠。 在这四行之后是三个条件,第一个条件是检查消息是简单的“ Hi”还是“ hi”,如果是,则为sendMessage(); 方法被调用。 此方法接受四个参数,您可以在上面的代码中看到。 第二个条件检查传入的消息是否包含check关键字并且还包含城市。 如果此条件的值为真,则调用get_forecast(); 返回响应的方法,该响应是我们将传递给post_forecast();的承诺post_forecast(); 方法。 这种方法可以使用户获得当前的天气状况。

If you got that, which I know you did, can I get an air high five?

如果您知道了,我知道您能做到吗,我能获得高五吗?

Great! going forward, we'll discuss the three methods mentioned above in detail.

大! 展望未来,我们将详细讨论上述三种方法。

function sendMessage(url, message,reply,res){
axios.post(url, {`chat_id: message.chat.id,`
    text: reply
}).then(response => {
    console.log("Message posted");
    res.end("ok");
}).catch(error =>{
    console.log(error);
});
}
...
function get_forecast(city){
    let new_url = openWeatherUrl + city+"&appid="+process.env.OPENWEATHER_API_KEY;
    return axios.get(new_url).then(response => {
        let temp = response.data.main.temp;
        //converts temperature from kelvin to celsuis
        temp = Math.round(temp - 273.15); 
        let city_name = response.data.name;
        let resp = "It's "+temp+" degrees in "+city_name;
        return resp;
    }).catch(error => {
        console.log(error);`
    });
}
...

The resp variable contains a formatted message to be sent to the user.

resp变量包含要发送给用户的格式化消息。

Yeah we didn't forget, our app will be listening in on port 3000

是的,我们没有忘记,我们的应用程序将在端口3000上监听

app.listen(3000, () => console.log("Telegram bot is listening on port 3000!"));

app.listen(3000, () => console.log("Telegram bot is listening on port 3000!"));

使用Now部署我们的机器人 ( Deploying our bot with Now )

As a rule of thumb, telegram bots are deployed over SSL, which now provides. Now is a platform which allows you to host your node applications with ease. You can head over to Zeit.co if you want to know more about Now. Now we'll install one last package in our project.

根据经验,电报僵尸程序是通过现在提供的SSL部署的。 现在是一个平台,可让您轻松托管节点应用程序。 如果您想了解更多有关Now的信息,可以前往Zeit.co。 现在,我们将在项目中安装最后一个软件包。

npm install -g now, this command installs the now CLI package. When the installation is done, we can take our application to the cloud by just typing now in our terminal. When the installation is done, we'll be provided a URL which will be used to create our webhook using cURL like so:

npm install -g now ,此命令将安装now CLI软件包。 安装完成后,只需在终端中输入内容即可将应用程序带到云中。 安装完成后,我们将提供一个URL,该URL将用于使用cURL创建我们的webhook,如下所示:

curl -F "url=https://URL_FROM_NOW/start_bot" https://api.telegram.org/botYOUR_TELEGRAM_API_TOKEN/setWebhook

If successful, you should get this JSON response:

如果成功,您应该获得以下JSON响应:

{
    "ok":true,
    "result":true,
    "description":"Webhook was set"
}

结论 ( Conclusion )

In this tutorial, we’ve built a telegram bot using node.js and also introduced to serverless deployment with now.

在本教程中,我们使用node.js构建了一个电报机器人,并且现在还介绍了无服务器部署。

There’s a lot of cool improvements that could be done with the bot. Feeling adventurous? Fork the project on GitHub, submit a PR and tinker with your little creation.

该机器人可以完成很多很棒的改进。 冒险吗? 在GitHub上分叉该项目,提交PR并修改您的小创意。

翻译自: https://scotch.io/tutorials/how-to-build-a-telegram-bot-using-nodejs-and-now

node.js 的构建工具

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值