node.js开发_使用Node.JS开发Twitter Bot

node.js开发

Today in this article we will learn how to create a Twitter Bot using Node.js and deploying this into Heroku. This bot will enhance our task in Twitter and able to do some task like re-tweet etc. This functions can be achieved by using Twitter API.

今天,在本文中,我们将学习如何使用Node.js创建Twitter Bot,并将其部署到Heroku中。 该机器人将增强我们在Twitter中的任务,并能够执行诸如重推等任务。可以通过使用Twitter API来实现此功能。

Before getting into the topic, let’s see the list of steps that we are going to follow.

在进入本主题之前,让我们看一下要遵循的步骤列表。

  • Apply for developer account in Twitter.

    在Twitter中申请开发者帐户。
  • Create app.

    创建应用。
  • Setup environment.

    设置环境。
  • Implement code.

    实施代码。
  • Avoid duplications of re-tweet.

    避免重复转发。
  • Deployment.

    部署。

Now let’s get deep into the topic.

现在让我们深入探讨该主题。

在Twitter中申请开发者帐户 (Apply for developer account in Twitter)

It is the most important one and difficult one also compared to others.

与其他相比,它是最重要和最困难的一个。

  • Login to Twitter.

    登录到Twitter。
  • Go to developer’s console and apply for a Developer account.

    转到开发者控制台并申请开发者帐户。
  • Select the type of app that you are going to create.

    选择您要创建的应用程序类型。
  • Mention the purpose of your app.

    提及您的应用目的。

Make sure that you have read all the developer agreement and policy before applying. Failing to any of these conditions will lead to rejection of your application.

在申请之前,请确保您已阅读所有开发者协议和政策。 不满足这些条件之一将导致您的申请被拒绝。

建立应用程式 (Create app)

Once your account gets approved by Twitter. Go to your developer console.

一旦您的帐户被Twitter批准。 转到您的开发者控制台。

  • Create an app in apps.twitter.com

    在apps.twitter.com中创建一个应用
  • Fill all the required details.

    填写所有必需的详细信息。
  • Generate a unique API key.

    生成唯一的API密钥。
  • Go to app details and navigate to keys and tokens.

    转到应用程序详细信息,然后导航至键和令牌

  • Keep your API keys confidential.

    对您的API密钥保持机密。

设定环境 (Setup environment)

First install Node.js and npm on your pc using respective commands.

首先使用相应的命令在您的PC上安装N ode.jsnpm

Create a new directory, your- bot-name.

创建一个新目录yourbot -name

Initialize git environment and install all the dependencies twit using npm. Enter the following commands inside your bot directory.

初始化git环境并使用npm安装所有依赖项twit 。 在您的bot目录中输入以下命令。

$ git init
$ npm init
$ npm install twit

Now successfully setup our development environment.

现在成功设置我们的开发环境。

实施代码 (Implement code)

First we have to authenticate twit and link the Twitter app and code using API keys that we are generated before.

首先,我们必须对twit进行身份验证,并使用之前生成的API密钥链接Twitter应用程序和代码。

Create a new file named config.js and paste the code inside it.

创建一个名为config.js的新文件,并将代码粘贴到其中。

module.exports = {
consumer_key: APPLICATION_CONSUMER_KEY_HERE,
consumer_secret: APPLICATION_CONSUMER_SECRET_HERE,
access_token: ACCESS_TOKEN_HERE,
access_token_secret: ACCESS_TOKEN_SECRET_HERE
}

Apply your unique keys from the Twitter dashboard.

从Twitter仪表板应用您的唯一键。

Now let’s write a code for our bot using bot.js.

现在,让我们使用bot.js为我们的机器人编写代码。

const config = require('./config')
const twit = require('twit')
const T = new twit(config)
function retweet(searchText) {
// Params to be passed to the 'search/tweets' API endpoint
let params = {
q : searchText + '',
result_type : 'mixed',
count : 25,
}
T.get('search/tweets', params, function(err_search, data_search, response_search){
let tweets = data_search.statuses
if (!err_search)
{
let tweetIDList = []
for(let tweet of tweets) {
tweetIDList.push(tweet.id_str);
//more code here later...
}
// Call the 'statuses/retweet/:id' API endpoint for retweeting EACH of the tweetID
for (let tweetID of tweetIDList) {
T.post('statuses/retweet/:id', {id : tweetID}, function(err_rt, data_rt, response_rt){
if(!err_rt){
console.log("\n\nRetweeted! ID - " + tweetID)
}
else {
console.log("\nError... Duplication maybe... " + tweetID)
console.log("Error = " + err_rt)
}
})
}
}
else {
console.log("Error while searching" + err_search)
process.exit(1)
}
})
}
// Run every 60 seconds
setInterval(function() { retweet('#DataScience OR #DataVisualization'); }, 60000)

We initialized the twit object using our configuration.

我们使用配置初始化了twit对象。

We pass the parameter to search API

我们将参数传递给搜索API

  • q - search query.

    q-搜索查询。

  • result_type- popular or older tweets.

    result_type-流行或更旧的推文。

  • counts- number of tweets retrieved.

    计数 -检索鸣叫的数量。

The JSON Object is used to retrieve all the tweets and pass each tweets to status/retweet/:id

JSON对象用于检索所有推文,并将每个推文传递到status / retweet /:id

Now test the bot locally using following command.

现在,使用以下命令在本地测试机器人。

node bot.js

避免重复转发 (Avoid duplications of re-tweet)

Add the following code in the for loop in bot.js

bot.js的for循环中添加以下代码

if(tweet.text.startsWith("RT @")) {
if(tweet.retweeted_status) {
tweetIDList.push(tweet.retweeted_status.id_str);
}
else {
tweetIDList.push(tweet.id_str);
}
}
else {
tweetIDList.push(tweet.id_str);
}

Then add this in outside of the loop.

然后将其添加到循环之外。

/ Utility function - Gives unique elements from an array
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
// Get only unique entries
tweetIDList = tweetIDList.filter( onlyUnique )
  • Each tweet has unique id, id_str.

    每个推文都有唯一的ID, id_str。

  • Each re-tweet has different id_str.

    每个重推都有不同的id_str

  • The search API is used to find whether it is original or re-tweeted one.

    搜索API用于查找它是原始的还是重新发布的。
  • This will avoid duplications in our bot.

    这样可以避免我们的漫游器重复。

部署方式 (Deployment)

First create an account in heroku and then create a app name using “your botname”.

首先在heroku中创建一个帐户,然后使用“您的botname”创建一个应用程序名称。

Keep your local directory file name and heroku project name same.

保持本地目录文件名和heroku项目名相同。

Install heroku-cli and create a “Procfile” using the following commands.

使用以下命令安装heroku-cli并创建一个“ Procfile”。

worker: node bot.js

Login into heroku CLI.

登录到heroku CLI。

$ heroku login

Before deploying go to heroku dashboard and start the worker dyno and configure it.

在部署之前,请转到heroku仪表板并启动worker dyno并进行配置。

Deploy into heroku by using these commands.

使用这些命令将其部署到heroku中。

$ heroku git:remote -a your-botname
$ git add
$ git commit -am "Add code"
$ git push heroku master

结论 (Conclusion)

I hope you enjoyed a lot and learnt about how to create a twitter bot using node.js and deploy it using heroku.

我希望您喜欢它,并了解了如何使用node.js创建Twitter机器人并使用heroku进行部署。

Thanks for reading!

谢谢阅读!

普通英语JavaScript (JavaScript In Plain English)

Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

喜欢这篇文章吗? 如果是这样,请订阅我们的YouTube频道解码,以获得更多类似的内容

翻译自: https://medium.com/javascript-in-plain-english/develop-a-twitter-bot-using-node-js-4aae715187a1

node.js开发

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值