aws lambda

Have you ever wanted to create a Twitter Bot? It’s been on my list of things to do for quite some time, and I’ve never really had a good way to do it. Until today.

等皆你曾经想创建一个Twitter博特? 在我要做的事情上已经有一段时间了,而我从来没有真正有好的方法。 直到今天。

I’ve always thought about making some sort of bot, and I always appreciate getting new quotes to ponder, so it was time to just sit down and do it. I just felt the need to finish a project and get something working.

我一直在考虑制作某种机器人,并且我总是很高兴获得新的报价来思考,因此现在是时候坐下来做这件事了。 我只是觉得需要完成一个项目并使某些工作正常进行。

I’ve been using Twitter for quite some time now. I use it to get daily news updates. I get updates about what’s going on before the news. Really it’s a good resource. Not to continue to gloat, but I think it’s a useful product.

我已经使用Twitter很长时间了。 我用它来获取每日新闻更新。 在新闻发布之前,我会得到最新的消息。 真的,这是很好的资源。 不要继续幸灾乐祸,但我认为这是一个有用的产品。

I also have been using IFTTT for quite some time. It’s another useful platform that I don’t use as much as I can but thought of while working on this — it’s just a trigger. It’s great for little if-else scripting statements and can add a lot of functionality to business workflows and even managing your phone operations.

我也使用IFTTT已有相当一段时间了。 这是另一个有用的平台,我没有尽我所能使用,但在进行此工作时却想到了这–它只是一个触发器。 这对于很少使用if-else脚本语句非常有用,并且可以为业务工作流甚至是管理电话操作添加很多功能。

It’s just a cloud trigger.

这只是一个云触发器。

Lambda
拉姆达

Now I know I need something that will just fire off a single function trigger. The first stack I think of is AWS Lambda. Low and behold, there is even some documentation on setting up a Serverless function and use that to deploy to AWS.

现在我知道我需要一些可以触发单个功能触发器的东西。 我想到的第一个堆栈是AWS Lambda。 低估了,甚至有一些文档介绍了如何设置无服务器功能并将其用于部署到AWS。

NodeJS
节点JS

As I’ve got some experience in NodeJS (and I found a starter for NodeJS here), I think it could be useful to flex some pre-learned knowledge and bang the keys to get this going.

由于我对NodeJS有一定的经验(我在这里找到了NodeJS的入门者 ),所以我认为,充分利用一些预先学习的知识并敲击按键来使它继续进行可能会很有用。

Serverless
无服务器

Since this is going to be in AWS Lambda, a single-use, serverless structure, I thought I could keep this simple with Serverless. This framework helps setting up and managing not only Lambda functions but Google Cloud, Azure, and more! A safe bet to stick with AWS today.

由于这将在一次性使用的无服务器结构AWS Lambda中进行,因此我认为我可以使用Serverless使其保持简单。 该框架不仅有助于设置和管理Lambda功能,而且还可以帮助您设置和管理Google Cloud,Azure等! 今天可以放心使用AWS。

So with that I now have three platforms on my stack:

因此,现在我的堆栈上有了三个平台:

  • AWS Lambda for the hosting适用于托管的AWS Lambda
  • NodeJS for the implementationNodeJS实现
  • Serverless for the deploy and management with AWS无服务器,用于通过AWS进行部署和管理
CloudWatch
CloudWatch

Next, I wanted a way to set up a timer to trigger the function. Luckily AWS has a great tool for that as well: AWS CloudWatch. CloudWatch will be configured with a timed event.

接下来,我想要一种设置计时器以触发功能的方法。 幸运的是,AWS也具有出色的工具:AWS CloudWatch。 CloudWatch将配置有定时事件。

Bringing the total to four on my stack.

将总数增加到4

Note: the time it runs depends on the region you’re in, so be weary of that.

注意:运行时间取决于您所在的地区,因此请对此感到疲倦。

With the stack setup, we can go into some finer details now.

通过堆栈设置,我们现在可以详细介绍一些细节。

触发器需要做什么 (What the Trigger Needs To Do)

  1. Authenticate and connect to Twitter验证并连接到Twitter
  2. Get the daily quote.rest

    获取每日报价

  3. Create the Tweet from the quote JSON data根据报价JSON数据创建推文
  4. Post the Tweet发表推文

如何调用触发器 (How Will the Trigger Be Called)

CloudWatch Cron Expression as a trigger for the AWS Lambda. This will be covered when we deploy.

CloudWatch Cron Expression作为AWS Lambda的触发器。 部署时将涵盖此内容。

先决条件 (Pre-Requisites)

  • Twitter account and Twitter Developer AccountTwitter帐户和Twitter开发人员帐户
  • AWS AccountAWS账户
  • NodeJS knowledgeNodeJS知识
  • If you know none of the above, check my links, and start learning!如果您不知道上述任何一项,请检查我的链接,然后开始学习!
Photo by Vine Ramazani on Unsplash
Vine Ramazani在 Unsplash上 拍摄的照片

建立 (Set Up)

Let’s go ahead and crack open a new project. Git or not, I’ve covered a few posts of how to get started with git so we’re going to omit that here.

让我们继续前进,打开一个新项目。 不管是否使用Git,我已经介绍了几篇有关如何开始使用git的文章,因此在这里我们将省略它。

To set up this project, firstly you need the serverless module installed globally:

要设置此项目,首先需要全局安装serverless模块:

npm install serverless -g

Then to set up the current project dir with the AWS-NodeJS template:

然后使用AWS-NodeJS模板设置当前项目目录:

serverless create --template aws-nodejs

Which will create the following files

哪个将创建以下文件

  • handler.js

    handler.js

  • serverless.yml

    serverless.yml

Then we need to add the following packages:

然后,我们需要添加以下软件包:

npm install express body-parser oauth request twit serverless-secrets-plugin de-loggingsystem
  • Express for the test serverExpress for测试服务器
  • body-parser for the test server测试服务器的主体解析器
  • oauth for authenticating the Twitter API用于验证Twitter API的oauth
  • twit for the Twitter APITwitter API简介
  • serverless-secrets-plugin for encrypting/decrypting our .env file

    serverless-secrets-plugin用于加密/解密我们的.env文件

  • de-loggingsystem is a custom logger package I made that helps my prints outde-loggingsystem是我制作的自定义记录程序包,可以帮助打印
Photo by Luca Bravo on Unsplash
Luca Bravo在 Unsplash上的 照片

I am going to give you some scripts that I kept in my package.json file that really helped my workflow and suggest for you as well:

我将为您提供一些保存在package.json文件中的脚本,这些脚本确实有助于我的工作流程并为您提供建议:

package.json
package.json

It’s a little messy, but essentially:

有点混乱,但本质上是:

precommit & commit are used to encrypt the secrets.* file and then for committing to my source control with some clean AngularJS commit messages.

precommit & commit用于加密secrets.*文件,然后使用一些干净的AngularJS commit消息提交到我的源代码管理。

develop is to run the function locally one time.

develop是一次本地运行功能。

predeploy & deploy will decrypt the file before deploying the production data to the AWS Lambda project.

在将生产数据部署到AWS Lambda项目之前, predeploy & deploy将解密文件。

test is to run the testing functions.

test是运行测试功能。

All start:local ‘s should be in a separate terminal.

所有start:local都应在单独的终端中。

Dealing with encrypt or decrypt functions, before the npm command add: PASSWORD=[your password] npm run deploy to pass the key.

在npm命令添加以下内容之前,要处理encryptdecrypt功能: PASSWORD=[your password] npm run deploy来传递密钥。

These functions really helped with my own workflow, and perhaps you can make it even better! If you do, let’s share that knowledge in responses.

这些功能确实对我自己的工作流程有所帮助,也许您可​​以使其变得更好! 如果您这样做,让我们在回应中分享这些知识。

Now that the project has been set up, we can begin to actually code the project and use those libraries.

现在已经建立了项目,我们可以开始实际编码项目并使用这些库了。

Photo by Arnold Francisca on Unsplash
照片由 Arnold Francisca在 Unsplash上 拍摄

码 (Code)

Before we go further, let’s add secrets.* to the .gitignore and create secrets.dev and secrets.prod files with your Twitter app credentials:

在继续之前,让我们将secrets.*添加到.gitignore ,并使用您的Twitter应用程序凭据创建secrets.devsecrets.prod文件:

secrets.prod.yml
secrets.prod.yml

API_URL can vary from dev to prod as we will see in testing later.

API_URL在开发人员和产品之间可能会有所不同,我们稍后将在测试中看到。

Now we can start changing the handler.js file to something more twitter-quote-botty.

现在我们可以开始将handler.js文件更改为更多的twitter-quote-botty了。

我们将逐步进行。 (We’re going to take this step-by-step.)

Let’s add all the modules we need:

让我们添加所需的所有模块:

handler.js
handler.js

These are all the modules we installed earlier, except we don’t have express and we do have https . Express will be used later for our test API server, and the HTTPS module is a NodeJS default.

这些是我们之前安装的所有模块,除了我们没有express和我们拥有https 。 Express稍后将用于我们的测试API服务器,并且HTTPS模块是NodeJS的默认设置。

Now we need to modify the hello function. Go ahead and change it to async :

现在我们需要修改hello函数。 继续并将其更改为async

handler.js
handler.js

Then we can set up our twit config object with our Twitter credentials loaded in from the environment and connect to Twitter.

然后,我们可以使用从环境中加载的Twitter凭证设置twit config对象,并连接到Twitter。

handler.js
handler.js

Therefore, connected to Twitter, we can call the quotes.rest API as a promise, that will be what our AWS Lambda function will return. This one is lengthy, so we will break it into parts:

因此,连接到Twitter后,我们可以将quotes.rest API称为promise,这将是我们的AWS Lambda函数将返回的内容。 这很长,因此我们将其分为几部分:

We create a response (what we return) and tell the variable to await the promise for the object. The promise calls a request function that uses a callback function to handle the request-response.

我们创建一个response (返回的内容),并告诉变量等待对象的promisepromise调用一个request函数,该函数使用回调函数来处理请求-响应。

handler.js
handler.js

Then parse the data from the body of the request-response into a JSON object. I create and load a tag variable with the tags of the quote. Then I use funky backticks (`) to parse the request-response JSON object into a quote-able string, and add all the tags.

然后将请求响应主体中的数据解析为JSON对象。 我用引号的标签创建并加载一个tag变量。 然后,我使用时髦的反引号(`)将请求响应JSON对象解析为可引用的字符串,然后添加所有标签。

handler.js
handler.js

Finally, I try to post the Tweet and if there is a success or failure, the console logs the output:

最后,我尝试发布Tweet,如果成功或失败,控制台将记录输出:

handler.js
handler.js

Here is the final file (with all the logging included I left out before):

这是最终文件(包括我之前遗漏的所有日志记录):

'use-strict';
const https = require('https');
const request = require('request');
const logger = require('de-loggingsystem');
const OAuth2 = require('oauth').OAuth2;
const twit = require('twit');
module.exports.hello = async event => {let config = {consumer_key: process.env.CONSUMER_KEY,consumer_secret: process.env.CONSUMER_SECRET,access_token: process.env.ACCESS_TOKEN,access_token_secret: process.env.ACCESS_TOKEN_SECRET};
const Twitter = new twit(config);
const response = await new Promise((resolve, reject) => {request(process.env.API_URL, function(err, res, body) {logger.log(logger.LogLevel.debug, `Response: ${res}. Body: ${body}`);let data = JSON.parse(body);logger.log(logger.LogLevel.debug, `Parsed rfdc object: ${data.contents.quotes[0].quote}`);var tags = "";for (const [key, value] of Object.entries(data.contents.quotes[0].tags)) {let tag = value;tags += `#${tag} `;};var tweet = `"${data.contents.quotes[0].quote}" - ${data.contents.quotes[0].author}\n\n\n${tags}`;
logger.log(logger.LogLevel.debug, tweet);
Twitter.post('statuses/update', { status: tweet }, function(err, data, response) {if (err) {logger.log(logger.LogLevel.error, `Tweet was not posted. Errorcode: ${err}`, logger.ErrorCode.Error);} else {logger.log(logger.LogLevel.info, `Tweet posted`);}});});});
return response;
};

演示地址

Instead of copy-paste, why not type things in; you remember more of it ⌨️.
为什么不输入内容而不是复制粘贴? 你还记得更多⌨

设置测试 (Set Up Tests)

For testing (well to code the tests) we need a simple JSON quote file to be sent back. We can do this with an Express instance. Create a server.js file with the following:

为了进行测试(对测试进行编码),我们需要将一个简单的JSON报价文件发送回去。 我们可以使用Express实例来做到这一点。 使用以下命令创建server.js文件:

server.js
server.js

Now, I took this from my own example express server, but I took that from an example, and they used a routes/routes.js files, so I do too:

现在,我从自己的示例快速服务器中获取了此信息,但从一个示例中获取了该信息,并且他们使用了routes/routes.js文件,所以我也这样做了:

routes/routes.js
路线/routes.js

Now when you run your tests (using the secrets.dev) your function will call the local server with the API_URL: http://localhost:3000/qod

现在,当您运行测试(使用secrets.dev )时,您的函数将使用API​​_URL调用本地服务器: http://localhost:3000/qod

实际测试 (Actual Testing)

To run the tests, first, you must run the test server. To run the test server, open another terminal to the folder path and run the server with:

要运行测试,首先,您必须运行测试服务器。 要运行测试服务器,请在文件夹路径中打开另一个终端,并使用以下命令运行服务器:

node server.js

I set up an npm test script with the following:

我使用以下命令设置了npm测试脚本:

"test": "sls invoke local -f hello --verbose --stage dev"

Which in turn runs the local function using the dev stage; which in turn uses the secrets.dev file. You should see the quote by Ralph Waldo Emerson sent to Twitter.

依次使用dev阶段运行本地功能; 依次使用secrets.dev文件。 您应该看到Ralph Waldo Emerson发送给Twitter的报价。

Photo by Stanley Dai on Unsplash
斯坦利·戴 ( Stanley Dai)在 Unsplash上 拍摄的照片

部署方式 (Deployment)

You will need to login with your AWS IAM account that you want to use with the project. You can do so with the instructions here.

您将需要使用要用于项目的AWS IAM帐户登录。 您可以按照此处的说明进行操作 。

Serverless handles the deployment.

无服务器处理部署。

We can use the PASSWORD=[your password] npm run deploy script setup before to deploy to our AWS Lambda project setup now. Once it’s deployed, you’ll be able to check the status on the Dashboard.

我们可以先使用PASSWORD=[your password] npm run deploy脚本设置,然后立即部署到我们的AWS Lambda项目设置。 部署完成后,您将可以在仪表板上检查状态。

Now that we’ve set up this project, we need to add a trigger from CloudWatch. To create a new trigger, AWS has some great documentation that will walk you through it. Be sure to check the correct action to run, and double-check your region, or calculate the timezone difference.

现在我们已经设置了这个项目,我们需要从CloudWatch添加触发器。 为了创建一个新的触发器, AWS提供了一些出色的文档 ,将逐步引导您。 确保检查要运行的正确操作,并仔细检查您的区域,或计算时区差异。

When you have your trigger ready, you can test the trigger with some blank data — which will pull from the API and post a tweet without the scheduled time.

准备好触发器后,您可以使用一些空白数据测试触发器-这些数据将从API中提取并发布一条没有计划时间的推文。

Photo by Jingda Chen on Unsplash
Chenjingda Chen在 Unsplash上 拍摄的照片

你做到了! (You did it!)

You made a Twitter quote bot too! I wanted to document this so that others could have fun making bots and other quirky APIs. Perhaps that’s next on the list, connecting this to an AWS API?

您也做了一个Twitter报价机器人! 我想对此进行记录,以使其他人可以玩机器人和其他古怪的API。 也许那是列表中的下一个,将其连接到AWS API?

Anywho, what did you like about making this project today? Are there any steps you improved? Let me know! It would be great to hear what others have to say, or tips they might have to speed up the process even more! I’m sure there’s a way to implement most of the deployment in GitHub Actions even (

aws lambda_我如何在一天内在Node.js中构建无服务器的AWS Lambda Twitter机器人相关推荐

  1. aws lambda使用_如何使用AWS Lambda和S3构建无服务器URL缩短器

    aws lambda使用 by Daniel Ireson 丹尼尔·埃里森(Daniel Ireson) 如何使用AWS Lambda和S3构建无服务器URL缩短器 (How to build a S ...

  2. 一文看懂当红Serverless:为何AWS、阿里云和腾讯云都在发力「无服务器架构」

    冠望 发自 凹非寺 量子位 报道 | 公众号 QbitAI 要说目前软件架构中热度十二分的话题,当属Serverless. 通常我们会将其翻译为"无服务器架构". 尽管成天被称为& ...

  3. aws消息服务器,经验分享:我们如何使用AWS构建无服务器架构 - hypertrack

    我们的客户使用HyperTrack无需服务器即可访问实时位置.他们将我们用作实时位置的托管服务.他们不需要构建和管理服务器来摄取,处理,存储,提供和管理与其应用用户的实时位置相关的任何内容. 而我们自 ...

  4. aws lambda_如何为AWS Lambda实施日志聚合

    aws lambda by Yan Cui 崔燕 如何为AWS Lambda实施日志聚合 (How to implement log aggregation for AWS Lambda) Dur­i ...

  5. aws lambda_它会融合吗? 或如何在AWS Lambda中运行Google Chrome

    aws lambda Yes, you read that right: this article is about running Google Chrome (the browser) in AW ...

  6. [翻译] 比较 Node.js,Python,Java,C# 和 Go 的 AWS Lambda 性能

    原文: Comparing AWS Lambda performance of Node.js, Python, Java, C# and Go AWS 最近宣布他们支持了 C# (Net Core ...

  7. 带有AWS Lambda和Java的无服务器FaaS

    什么是无服务器架构? 无服务器架构在由第三方完全管理的临时容器中运行自定义代码. 自定义代码通常只是完整应用程序的一小部分. 也称为函数 . 这为无服务器架构提供了另一个名称,即功能即服务 (FaaS ...

  8. aws lambda_Express.js和AWS Lambda —无服务器的爱情故事

    aws lambda by Slobodan Stojanović 由SlobodanStojanović Express.js和AWS Lambda -无服务器的爱情故事 (Express.js a ...

  9. 金蝶云系统服务器,谁说ERP不能上公有云?金蝶云无服务器版ERP登陆AWS

    [51CTO.com原创稿件]公有云因其弹性可伸缩等特点,赢得了众多中小企业以及互联网用户的青睐.而企业也会选择非核心业务系统先迁移到云端,在满足创新业务快速发展的同时,还保证了核心业务的稳定性.安全 ...

最新文章

  1. Tomcat unable to start within 45 seconds.
  2. Apache用户目录枚举工具apache-users
  3. 信息安全系统设计基础第九周学习总结
  4. 一款好用的JS时间日期插件layDate
  5. WSE 3.0异步调用, MTOM, Custom Policy Trace Assertion
  6. 城市大脑标准体系与评价指标总体框架研究
  7. 公共语言运行库中的程序集-04强命名的程序集
  8. 小米不加入鸿蒙,是华为不给小米用鸿蒙,还是小米拒绝使用鸿蒙?
  9. 李飞飞创建的AI4All启动首次mentorship计划
  10. jsp中EL表达式不好使
  11. 微信html5怎么制作,图文揭秘微信h5怎么制作-朋友圈微信H5页面制作方法
  12. php ucfirst,Arale源码解析(3)——Base模块和Aspect模块
  13. 自助装机配置专家点评2
  14. [爬虫]一个关于课堂派课件的爬虫
  15. JAVA-三种注释方式
  16. 淘宝maven镜像库是个好东西
  17. 有符号数与无符号数的除法(转载)
  18. 深度学习推荐系统实战笔记
  19. 详解python中readlines函数的参数hint
  20. 使用python创建一个windows桌面在线翻译小程序

热门文章

  1. STM32入门教程——串口通讯
  2. OpenSSL密码库算法笔记——第5.3.2章 椭圆曲线点群的建立,释放和复制
  3. C语言练习(三) -----F0803 编程题 2020年
  4. AVD模拟器怎么配置上网
  5. 在线编程+视频面试,工程师“云招聘”的正确打开方式(附源码)
  6. pytorch中tensor前面加~
  7. 达梦数据库连接失败解决方式
  8. 三阶魔方还原方法(白色在上层先法)
  9. mqtt(6):emqtt 配置并启动 使用 admin 查看
  10. 用Spark MLlib进行数据挖掘