Building a Twitter Bot with Vapor

Learn how to build a Twitter bot and create your own tweet automation tools with Vapor and Server Side Swift. By Beau Nouvelle.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Posting a Tweet

Vapor has a few ways to make requests to another service. These are accessible through the client object.
Find // TODO: post tweet and replace it with:

return client.post(tweetURI, headers: headers)

This code uses client to send a POST request to tweetURI and returns a EventLoopFuture<ClientResponse>.

You’re now ready to tweet!

To test, replace all the code inside routes.swift with:

import Vapor

func routes(_ app: Application) throws {
  app.get { req -> EventLoopFuture<ClientResponse> in
    return QuoteManager().tweetQuote(with: req.client)
  }
}

Build and run.

With the server running, open a Terminal window and trigger the tweet with the following curl command:

curl http://localhost:8080

Go to your Twitter feed and check that the tweet has been posted!

Note: Nothing much will happen if you try running the command a second time. Your server will certainly try to send another tweet, but because you’re not using the QuoteManager singleton it will start life again with a full tweetBucket and attempt to send the same tweet twice! This, of course, is something that Twitter ignores.

To set up scheduling, open SendTweetJob.swift. Add this line before the return statement in run(context: QueueContext):

_ = QuoteManager.shared.tweetQuote(with: context.application.client)

Next, you’ll want to change the time of scheduling. Switch over to configure.swift and swap this code:

app.queues.schedule(SendTweetJob())
  .everySecond()

with:

app.queues.schedule(SendTweetJob())
  .daily()
  .at(.noon)

Congratulations! You now have a Twitter bot that will post new tweets on your behalf every day at around lunchtime!

Where to Go From Here?

Download the final project by clicking Download Materials at the top or bottom of the tutorial.

This tutorial is only a brief look at what you can achieve when building Twitter apps. Take a look around at what others have done for inspiration. You can use Twitter apps to automate your presence on Twitter or create something entirely new!

Take it to the next level by trying some new things such as:

  • Adding more quotes. Or tweet something else like daily horoscopes, affirmations or encouragement.
  • Building an app that tweets a daily weather forecast or weekly comic strip. Have your server pull data from another server and send it to Twitter!
  • Keeping your server running indefinitely. Running your server on your main computer is one thing, but if you want to get serious, check out the deployment chapters in the Server Side Swift with Vapor Book

We hope you enjoyed this tutorial, and if you have any questions or comments, please join the forum discussion below!