DEV Community

loading...

Using Twitter API and Reshuffle to manage Social Media Contests and Giveaways

alanblee profile image Alan Lee ・6 min read

Social media contests and giveaways can be an incredibly powerful marketing strategy to jumpstart an online conversation about your business. When running one of these campaigns, you can ask your audience to like, follow or retweet as a way of growing your business’s engagement with the customers, which in turn, can lead to increasing the brand’s awareness. Hosting a promotional event gives the people who are not already following you the ability to learn about your business from seeing others engage with an entry. It’s a win-win situation, people have a chance at a free prize, and your brand increases in user engagement and awareness.

So, let’s say your marketing team came up with a great promotional campaign for Twitter and is asking the audience to retweet the post for a chance to win an amazing prize.

The next step is to figure out a way to choose a winner. Depending on how you ask users to enter, there are several ways you can pick winners for your giveaway. Many services are available online where you can copy and paste the campaign tweet URL and it’ll randomly choose a user. This approach will definitely work but may come with downsides. The most common, the service being limited to only driving one user action (retweets, replies, likes).

In this article, I will show you a way to manage a promotional campaign using the Twitter API and handling everything programmatically using Reshuffle. We'll be focusing on ‘retweets’ but you can easily customize the code to your needs with the many endpoints Twitter API has available.

Reshuffle is an open source, lightweight, and event-driven framework that helps you integrate services — these integrations and workflows are created inside a Reshuffle App. The objects that let you interact with these services are called connectors.

Prerequisites

In order to use the Twitter API, you will need a Twitter developer account - apply for access. Go to the app page and create a new Twitter app. When you have an app approved, save the API key and API secret as we will need it later on for configuration. To obtain the API keys check out the documentation.

This example will be using PostgreSQL to store the retweeters’ data. A table labeled ‘tweets’ with the columns of ‘id’ as the primary key and username will be needed. Have the database URL ready for configuration. If you prefer to store the data with a different service like Google Sheets, check the documentation here.

How to Build It

Our goal is to be able to fetch data from all the retweets posted on a specific tweet, and save the user’s screen name and tweet ID to the database. The data stored will count as an entry for the campaign. With the Twitter credentials on hand and a database created, we’re ready to move on to building this.

To get started, first we need to bring in the required packages. Then initiate a Reshuffle app and configure the Twitter, PostgreSQL and Cron connector. If you’re wondering, “Why or what is Cron?”, it’s the tool that will tie this application together, more explanation to come when we make use of it.

Note: If you are connecting to a database protected by ssl, you will need to include an ssl option in the pgsql configuration. Please see documentation for more information.

const { Reshuffle, CronConnector } = require("reshuffle");
const { TwitterConnector } = require("reshuffle-twitter-connector");
const { PgsqlConnector } = require("reshuffle-pgsql-connector");

const app = new Reshuffle();

//cron config
const cronConnector = new CronConnector(app);

//pgsql config
const pg = new PgsqlConnector(app, {
 url: process.env.POSTGRES_URL,
});

//twitter config
const twitter = new TwitterConnector(app, {
 customerKey: process.env.TWITTER_CUSTOMER_KEY,
 customerSecret: process.env.TWITTER_CUSTOMER_SECRET,
});

 // Code listed further down
 // will be inserted here


app.start(8000);
Enter fullscreen mode Exit fullscreen mode

Reshuffle connectors provide events and actions that allow developers to easily build custom workflows and integrations. With the connectors configured, we can now make use of what they can offer.

To get the data on the retweeters, we will use the statuses/retweets/:id.json endpoint from the Twitter API. This is made easy with the Twitter connector GET action, simply pass on the endpoint as an argument along with the ID of the tweet you want to get the retweeters data on.

Tweet IDs can be found in the tweet url:
TweetID img

const retweeters = await twitter.GET("statuses/retweets/1349430236383825921.json");
Enter fullscreen mode Exit fullscreen mode

Running the above line will return a collection similar to this:
Collection img

With that, we’re now able to get a list of retweeters. However, there is an issue here. Twitter will only return a collection of up to 100 user retweets per call and does not have a way to paginate.

We can solve this by periodically calling the API and saving the results to the database. If you recall in the configuration, we also added the Cron connector, here we will make use of it.

As Reshuffle is an events-based system, you develop code to handle these events. The Cron connector can be used to fire an event every "x" amount of time, which lets us call the API
Periodically.

Note: I wrapped the twitter call in a function here to make code inside the event handler a little more neat

const usersRetweeted = () => {
 return Promise.resolve(
   twitter.GET("statuses/retweets/1350179812422258688.json")
 );
};

cronConnector.on({ expression: "25 * * * * *" }, async (event, app) => {
 const userList = await usersRetweeted();
 userList.forEach(async (tweet) => {
   await pg.query(
     `INSERT INTO retweets(id, username) VALUES ('${tweet.id}',   '${tweet.user.screen_name}')
      ON CONFLICT (id) DO NOTHING`
   );
 });
});
Enter fullscreen mode Exit fullscreen mode

Note: If you’re unfamiliar with these cron expressions, visit crontab.guru to help generate one. The example above runs every 25minutes

After the API call, you can see we use the PostgreSQL connector to insert a new row with the retweeter’s data. With the id as the primary key, there won’t be any duplicate retweets saved into the database.

With this, we can run this for as long as the campaign duration. Afterwards, we use the PostgreSQL connector again to retrieve the number of entries so we can randomize and select the winner.

const pickWinner = async () => {
   const {
     rows: [{ count }],
   } = await pg.query("SELECT COUNT(*) FROM retweets");

   const randomNum = Math.random() * count - 1;

   const {
     rows: [{ username }],
   } = await pg.query(
     `SELECT USERNAME FROM retweets LIMIT 1 OFFSET ${Math.abs(randomNum)}`
   );
   return username;
 };
 console.log(await pickWinner());
Enter fullscreen mode Exit fullscreen mode

You can customize this shuffle code to output multiple users, depending on how many winners your giveaway will have. Though you should probably comment out the code above until after the campaign has ended, or you can utilize the HTTP connector that lets you trigger logic when an HTTP endpoint is hit.

Like the other connectors, you will need to require it in the code and configure it like so:

const { Reshuffle, HttpConnector } = require("reshuffle");
 //http config
 const httpConnector = new HttpConnector(app);
Enter fullscreen mode Exit fullscreen mode

Here is an example of how to use this:

httpConnector.on(
 {
   method: "GET",
   path: "/pick-winner",
 },
 async (event, app) => {
   const winner = await pickWinner();
   event.res.json({ winner });
 }
);
Enter fullscreen mode Exit fullscreen mode

When the endpoint is hit, the output should look something like this:
Winner img

With minimal code, I hope you can see how easy it is to set up and manage your campaign with the Twitter API combined with Reshuffle. Try different endpoints to create something unique that fits your giveaway!

Full Documentation of connectors:
Twitter Connector
PostgreSQL Connector
HTTP Connector
Cron Connector

Now, Make it Happen

As your developers and project management teams experience the ease of working with integrated applications, we encourage you to consider where else integrating workflows would benefit your teams. With so many different tools, the more you can consolidate them into one common interface, the easier people can get work done.

Reshuffle is continually listening to what our customers need and desire. Don’t see a Connector to a service you’d like to integrate? Send a tweet to @ReshuffleHQ to let us know which Connector you’d like us to develop next.

Discussion (0)

pic
Editor guide