Wednesday, March 15, 2023
HomeReactCreate a Easy Twitter Bot with Node.js by Aman Mittal

Create a Easy Twitter Bot with Node.js by Aman Mittal


Create a Easy Twitter Bot with Node.js

Printed on Nov 23, 2016

9 min learn

How a few Twitter Bot that retweets, favorites, on the premise of hashtags and replies to different customers in the event that they observe it? I made an analogous type of a Twitter Bot (@nodejstweet) that feeds me the most recent or the continuing information/articles/how-to’s on a set of hashtags akin to #Nodejs, #MongoDB, #AngularJS, #IonicFramework, et cetera. On the time I by no means anticipated it having extra followers than me however that has been surpassed.

What this bot will do?

🔗

It is a easy Twitter bot and can retweet, favourite/like randomly on the premise of hashtags as a question that we are going to use and proceed to take action after a sure time frame interval.

What you want?

🔗

  • You will need to have Node.js put in in your system.
  • A Twitter Account.
  • Your bot can be utilizing twit which is an npm module to govern tweets and streams, and to speak with the Twitter API.

Let’s Begin

🔗

Setup an empty listing and initialise it with:$ npm init to configure this net software with package deal.json file. Then create two new information: bot.js & config.js in that listing.

bot.js can be our foremost app file through which we can be writing the supply code of our Twitter Bot, and so in package deal.json edit the foremost discipline to:

Your present listing construction ought to seem like this:

root/project-name

|- bot.js

|- config.js

|- package deal.json

Configuring and granting permissions from Twitter API

🔗

After logging to to your Twitter account, observe to this hyperlink: https://apps.twitter.com/app/new to create a brand new software. Fill out the required fields within the type click on on the button Create Your Twitter Software. After creating the appliance, search for Keys and Entry Tokens underneath the nav-panes and click on on Generate Token Actions after which copy:

  • Client Key
  • Client Secret
  • Entry Token
  • Entry Token Secret

Open the config.js file and paste all 4 values inside it. Expose these values utilizing module.export:

1

2

3

4

5

6

7

8

9module.exports = {

10 consumerconsumer_key: '',

11 consumerconsumer_secret: '',

12 accessaccess_token: '',

13 accessaccess_tokenaccess_token_secret: ''

14};

Now, the Twitter bot’s configuration is step is full. Please observe, for each totally different software, the client key, client secret, access_token and access_token_secret will differ.

Constructing the bot

🔗

Because the configuration step is full, now let’s set up our third requisite that’s Twitter API shopper for node and can assist us to speak to Twitter API and supply an API for all essential actions (akin to retweet and favourite a tweet).

We are going to begin by putting in the dependency we want for our software.

$ npm set up --save twit

After the dependency has completed putting in, go to the bot.js file and require the dependency and config.js file.

1var twit = require(’twit’);

2var config = require(./config.js’);

Move the configuration (client and entry tokens) of our Twitter software in config.js to twit:

1var Twitter = new twit(config);

To date, so good?

PLEASE NOTE: You will need to check with twit documentation for a deep reference.

Retweet Bot

🔗

Let’s write a perform expression that finds the most recent tweets based on the question handed as a parameter. We are going to initialise a params object that may maintain numerous properties to go looking a tweet, however most significantly question or q property that may refine our searches. No matter worth you feed on this property, our bot will search the tweets to retweet based mostly on this standards. You may feed this property values like a twitter handler, to observe a selected twitter account or a #hashtag. For our instance bot, we’ve got discover newest tweets on #nodejs.

That is how the performance of the retweet bot begins:

1var retweet = perform() {

2 var params = {

3 q: '#nodejs, #Nodejs',

4 result_type: 'latest',

5 lang: 'en'

6 }

The opposite two properties: result_type and lang are non-obligatory. On defining the result_type: 'latest' notifies bot to solely seek for the most recent tweets, tweets which have occurred within the time interval since our bot has began or it made the final retweet.

There’s a record of parameters supplied by the Twitter API.

Our subsequent step is to seek for the tweets based mostly on our parameters. For this, we’ll use Twitter.get perform supplied by twit API to GET any of the REST API endpoints. The REST API endpoint is a reference to the Twitter API endpoint we’re going to make a name to seek for tweets. The Twitter.get perform accepts three arguments: API endpoint, params object (outlined by us) and a callback.

1

2

3

4var retweet = perform () {

5 var params = {

6 q: '#nodejs, #Nodejs',

7 result_type: 'latest',

8 lang: 'en'

9 };

10

11

12 Twitter.get('search/tweets', params, perform (err, information) {

13

14 if (!err) {

15

16 var retweetId = information.statuses[0].id_str;

17

18 Twitter.publish(

19 'statuses/retweet/:id',

20 {

21 id: retweetId

22 },

23 perform (err, response) {

24 if (response) {

25 console.log('Retweeted!!!');

26 }

27

28 if (err) {

29 console.log(

30 'One thing went flawed whereas RETWEETING... Duplication perhaps...'

31 );

32 }

33 }

34 );

35 }

36

37 else {

38 console.log('One thing went flawed whereas SEARCHING...');

39 }

40 });

41};

To publish or to retweet the tweet our bot has discovered we use Twitter.publish() methodology to POST any of the REST API endpoints. It additionally takes the identical variety of arguments as Twitter.get().

Now to automate this motion we outlined above, we will use JavaScript’s timer perform setInterval() to go looking and retweet after a selected time frame.

1

2retweet();

3

4setInterval(retweet, 3000000);

Please observe that every one JavaScript’s Timer capabilities take the period of time argument in milliseconds.

Favourite Bot

🔗

Just like retweet bot we will outline and initialise one other perform expression that may search and favourite a tweet randomly. Sure, the distinction right here is to go looking and seize the tweet randomly. We are going to begin by making a parameter object params that may encompass three properties as in retweet() perform expression. The bot will seek for tweets utilizing the identical .get() perform supplied by twit API to GET any of the Twitter API endpoints. In our case, we want search/tweets. Then we’ll retailer the standing of the seek for tweet to favourite in a variable and in a one other variable we’ll apply the random perform by passing the “standing of the search” variable as an argument.

1

2

3

4var favoriteTweet = perform () {

5 var params = {

6 q: '#nodejs, #Nodejs',

7 result_type: 'latest',

8 lang: 'en'

9 };

10

11

12

13 Twitter.get('search/tweets', params, perform (err, information) {

14

15 var tweet = information.statuses;

16 var randomTweet = ranDom(tweet);

17

18

19 if (typeof randomTweet != 'undefined') {

20

21 Twitter.publish(

22 'favorites/create',

23 { id: randomTweet.id_str },

24 perform (err, response) {

25

26 if (err) {

27 console.log('CANNOT BE FAVORITE... Error');

28 } else {

29 console.log('FAVORITED... Success!!!');

30 }

31 }

32 );

33 }

34 });

35};

36

37favoriteTweet();

38

39setInterval(favoriteTweet, 3600000);

40

41

42perform ranDom(arr) {

43 var index = Math.flooring(Math.random() * arr.size);

44 return arr[index];

45}

Observe that the tweets searched by our bot are all saved in an array. Once more, we use JavaScript’s timer perform setInterval()to go looking and favourite the tweet after a selected time frame in milliseconds.

The whole module: bot.js :

1

2var twit = require('twit'),

3 config = require('./config');

4

5var Twitter = new twit(config);

6

7

8

9

10var retweet = perform () {

11 var params = {

12 q: '#nodejs, #Nodejs',

13 result_type: 'latest',

14 lang: 'en'

15 };

16 Twitter.get('search/tweets', params, perform (err, information) {

17

18 if (!err) {

19

20 var retweetId = information.statuses[0].id_str;

21

22 Twitter.publish(

23 'statuses/retweet/:id',

24 {

25 id: retweetId

26 },

27 perform (err, response) {

28 if (response) {

29 console.log('Retweeted!!!');

30 }

31

32 if (err) {

33 console.log(

34 'One thing went flawed whereas RETWEETING... Duplication perhaps...'

35 );

36 }

37 }

38 );

39 }

40

41 else {

42 console.log('One thing went flawed whereas SEARCHING...');

43 }

44 });

45};

46

47

48retweet();

49

50setInterval(retweet, 3000000);

51

52

53

54

55var favoriteTweet = perform () {

56 var params = {

57 q: '#nodejs, #Nodejs',

58 result_type: 'latest',

59 lang: 'en'

60 };

61

62 Twitter.get('search/tweets', params, perform (err, information) {

63

64 var tweet = information.statuses;

65 var randomTweet = ranDom(tweet);

66

67

68 if (typeof randomTweet != 'undefined') {

69

70 Twitter.publish(

71 'favorites/create',

72 { id: randomTweet.id_str },

73 perform (err, response) {

74

75 if (err) {

76 console.log('CANNOT BE FAVORITE... Error');

77 } else {

78 console.log('FAVORITED... Success!!!');

79 }

80 }

81 );

82 }

83 });

84};

85

86favoriteTweet();

87

88setInterval(favoriteTweet, 3600000);

89

90

91perform ranDom(arr) {

92 var index = Math.flooring(Math.random() * arr.size);

93 return arr[index];

94}

Utilization

🔗

To run this bot, go to your terminal:

To keep away from this monotonous course of you should utilize npm scripts or nodemon. It’s also possible to deploy this app on Heroku for a steady integration.

To make use of npm scripts, make this edit underneath scripts in package deal.json :

1{

2 "scripts": {

3 "begin": "node bot.js"

4 }

5}

Then from terminal:

There are numerous methods to jot down a Twitter Bot, this is only one method. Your bot might be sensible and you are able to do numerous issues with it. You simply should check with twit documentation for different RESTful API strategies to govern Twitter API endpoints.

For additional studying take a look at Botwiki.org for numerous forms of bots on huge quantity of platforms. For superior studying, take a look at Botwiki’s record of tutorials of Twitter Bots in several programming languages.


I am a software program developer and a technical author. On this weblog, I write about Technical writing, Node.js, React Native and Expo.

Presently, working at Expo. Beforehand, I’ve labored as a Developer Advocate, and Senior Content material Developer with firms like Draftbit, Vercel and Crowdbotics.



RELATED ARTICLES

Most Popular

Recent Comments