How to create a Twitter bot with Twitter API v2 (2024)

When writing this tutorial, the cost of hosting this Twitter bot should be covered by the free credits from the Google Cloud Platform. If this changes, please let us know by selecting the unhappy face at the bottom of the page.

Create your bot account

First, you will need to create a new account for your bot. The account for your bot should be a unique handle that describes your bot’s purpose. You will also want to set your bot’s profile picture and background image. Additionally, you will want to set up the bio of your bot to say it’s a bot and who built it.

For @FactualCat, the bio is as follows:

A #TwitterBot that Tweets cat facts by @JessicaGarson

Authenticate on behalf of your bot

Before you can use the Twitter API v2, you will need a developer account. Once you have a developer account, you will need to create a Project in the developer portal. This tutorial uses v1.1 endpoints. To use v1.1 endpoints, you will need elevated access, which you can apply for from the developer portal.

Each Project contains an App, with which you can generate the credentials required to use the Twitter API. You can learn more about getting started with the Twitter API in the getting started section of our documentation. You can apply for access from your main handle and authenticate on behalf of your account.

To authenticate a new account, you can use a pin-based OAuth flow. A helpful forum post also explains how to authenticate on behalf of a bot account.

Step 1 - Get your OAuth token

You can use a REST Client such as Insomnia or Postman to make a POST request to the request token endpoint. For this endpoint, you will need to use OAuth 1.0a.

https://api.twitter.com/oauth/request_token

After you make the request you will get back a response that looks similar to the one below:

 oauth_token=zlgW3QAAAAAA2_NZAAABfxxxxxxk&oauth_token_secret=pBYEQzdbyMqIcyDzyn0X7LDxxxxxxxxx&oauth_callback_confirmed=true 

Step 2 - Create and go to the authenticate URL

Using the OAuth token you generated in the last step, you can create a URL that you can go to authorize your application. You should be signed in as your bot account when you visit this URL. You will start with the prefix of https://api.twitter.com/oauth/authenticate?oauth_token= and append it with the OAuth token from the previous step.

For this example, the URL you’d visit in your web browser would be similar to the one below but replaced with the credentials generated from the previous step. Authorizing on a browser will return a seven-digit pin as an OAuth verifier in the next step.

https://api.twitter.com/oauth/authenticate?oauth_token=zlgW3QAAAAAA2_NZAAABfxxxxxxk

You can learn more about creating an authenticate URL in our documentation on the subject.

Step 3 - Getting your Access Token and Access Token Secret

You are now ready to get the Access Token and Access Token Secret for your bot account. Next, you will use the POST oauth/access_token endpoint. For this endpoint, you will need to use OAuth 1.0a.

You can now make a POST request to the following endpoint using the OAuth verifier you generated in the previous step and the OAuth token you used in the last step.

https://api.twitter.com/oauth/access_token?oauth_verifier=0535121&oauth_token=zlgW3QAAAAAA2_NZAAABfxxxxxxk

You should get back to a response that is similar to the following:

 oauth_token=62532xx-eWudHldSbIaelX7swmsiHImEL4KinwaGloxxxxxx&oauth_token_secret=2EEfA6BG5ly3sR3XjE0IBSnlQu4ZrUzPiYxxxxxx&user_id=1458900662935343104&screen_name=FactualCat 

The oauth_token you get back is the Access Token for your bot, and the oauth_token_secret is the Access Token Secret for your bot.

Posting your first Tweet on behalf of your bot

Now that you’ve created your Access Token and Access Token Secret, you are now ready to start Tweeting on behalf of your bot. Like how you used OAuth 1.0 in a REST Client such as Insomnia or Postman in the previous steps, you can now do the same but be sure to replace the Access Token and Access Token Secret with the ones you just created. The Consumer Key and Consumer Secret should be the same as they were previously.

You can now make a POST request to the manage Tweets endpoint by entering the following URL into Insomnia or Postman:

https://api.twitter.com/2/tweets

In the body tab of your request, be sure to select the format as JSON and enter in the following payload:

 {"text": "hello"} 

The response should look similar to the following:

 { "data": { "id": "1464995641172582404", "text": "hello" }} 

If you check your bot account, you will see that you have posted your first Tweet on behalf of your bot.

Setting up Google Cloud Functions

Now that you’ve posted your first Tweet on behalf of your bot, you are ready to start configuring your bot to run regularly. First, you will deploy and write your code in Google Cloud Functions and run it at a scheduled time that you determine with Google Cloud Scheduler.

You will first need to set up an environment for the Google Cloud Platform. After you have your environment set up, you can set up a Cloud Function. If you are using Google Cloud Platform for the first time, you will need to set up a credit card before creating an environment. To set up a Cloud Function, you can follow a similar process outlined in the Python quickstart for Cloud Functions. You can first set your cloud region based on your location and select your trigger as “Cloud Pub/Sub” with a new topic.

Creating your environment variables

To avoid directly adding your keys and tokens to your Cloud Function, you can create environment variables. For example, under the “Runtime, build, connections and security settings“ header, you can set up environment variables for your Consumer Key, Consumer Secret, Access Token, and Access Token Secret. Of course, you will want to set these values the same as what you used while posting the Tweet in the previous step.

Configuring your code

After configuring your Cloud Function, you will be taken to a code page to set your runtime, the programming language, and the version you are using. This example uses Python 3.9 as the runtime environment. You will also want to select the entry point as hello_pubsub.

Editing your main.py file

The main.py file is where the main logic of the code lives. In this file, you will be parsing a cat fact for this bot from catfact.ninja and Tweeting it from the Twitter API.

First, you will need to import the following packages.

 import requestsfrom requests_oauthlib import OAuth1import os 

After you’ve imported your packages, you will want to write a few lines of code to get the environment variables you set while configuring your Cloud Function.

 consumer_key = os.environ.get("CONSUMER_KEY")consumer_secret = os.environ.get("CONSUMER_SECRET")access_token = os.environ.get("ACCESS_TOKEN")access_token_secret = os.environ.get("ACCESS_TOKEN_SECRET") 

After you have the keys and tokens set for your Cloud Function, you can now call the catfact.ninja endpoint to grab a random cat fact.

 def random_fact(): fact = requests.get("https://catfact.ninja/fact?max_length=280").json() return fact["fact"] 

You will also need to place the cat fact into a dictionary so that you can pass it as a JSON payload.

 def format_fact(fact): return {"text": "{}".format(fact)} 

To make the request to the Twitter API, you can use the following function:

 def connect_to_oauth(consumer_key, consumer_secret, acccess_token, access_token_secret): url = "https://api.twitter.com/2/tweets" auth = OAuth1(consumer_key, consumer_secret, acccess_token, access_token_secret) return url, auth 

Now, you are ready to edit the hello_pubsub function to have variables for your fact, payload, url, auth, and request.

 def hello_pubsub(event, context): fact = random_fact() payload = format_fact(fact) url, auth = connect_to_oauth( consumer_key, consumer_secret, access_token, access_token_secret ) request = requests.post( auth=auth, url=url, json=payload, headers={"Content-Type": "application/json"} ) 

You can check out the full version of the code. There is also a version available for testing locally on your machine. You will need to set up the environment variables for the local version to work.

Editing your requirements.txt file

Your requirements.txt file determines what packages you need to install and installs them in your environment for you.

If you go to the requirements.txt file, you will want to edit it to match the following:

 # Function dependencies, for example:# package>=versionrequests==2.18.3requests-oauthlib==1.3.0 

Deploying your function

Once you have your code set, you are now ready to press the button that says “Deploy” to deploy your function. You may want to check out the pricing structure for Cloud Functions.

Scheduling your Tweets with Google Cloud Scheduler

After setting up your Cloud Function, you can use the Cloud Scheduler to determine how often your bot will Tweet. You need to set up a job and how often it will run.

For example, @FactualCat is currently Tweeting every 12 hours using the following notation:

 0 */12 * * * 

You may want to look at the pricing information on the Cloud Scheduler before adjusting the timing.

How to create a Twitter bot with Twitter API v2 (2024)
Top Articles
What Is Piccalilli, Exactly? (Answer: Your New Favorite Condiment)
Christmas Food Around the World | CDA Appliances
Barstool Sports Gif
Where are the Best Boxing Gyms in the UK? - JD Sports
Parke County Chatter
Patreon, reimagined — a better future for creators and fans
Craigslist Pets Longview Tx
Katmoie
Vaya Timeclock
Culver's Flavor Of The Day Wilson Nc
Flixtor The Meg
Noaa Weather Philadelphia
Catsweb Tx State
How Quickly Do I Lose My Bike Fitness?
3656 Curlew St
Craigslist Chautauqua Ny
Revitalising marine ecosystems: D-Shape’s innovative 3D-printed reef restoration solution - StartmeupHK
Mawal Gameroom Download
Aces Fmc Charting
Dump Trucks in Netherlands for sale - used and new - TrucksNL
Drago Funeral Home & Cremation Services Obituaries
Cvs Appointment For Booster Shot
Violent Night Showtimes Near Amc Fashion Valley 18
Lehmann's Power Equipment
Busted Newspaper Fauquier County Va
Clare Briggs Guzman
Air Traffic Control Coolmathgames
Brazos Valley Busted Newspaper
Jermiyah Pryear
Getmnapp
Essence Healthcare Otc 2023 Catalog
Netwerk van %naam%, analyse van %nb_relaties% relaties
Ardie From Something Was Wrong Podcast
Maths Open Ref
Sinai Sdn 2023
What are the 7 Types of Communication with Examples
Timothy Kremchek Net Worth
Muziq Najm
Hell's Kitchen Valley Center Photos Menu
Jason Brewer Leaving Fox 25
Google Flights Orlando
Lbl A-Z
Carteret County Busted Paper
COVID-19/Coronavirus Assistance Programs | FindHelp.org
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
Sherwin Source Intranet
Craigslist Sparta Nj
Congruent Triangles Coloring Activity Dinosaur Answer Key
Lightfoot 247
Elizabethtown Mesothelioma Legal Question
Latest Posts
Article information

Author: Corie Satterfield

Last Updated:

Views: 5852

Rating: 4.1 / 5 (62 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.