Skip to content

6. How do you authenticate to Twitter?

Bogdan Tudorache edited this page Feb 13, 2022 · 13 revisions

In order to authenticate to Twitter in the bot you will need an:

  • 'API Key'
  • 'API Key Secret'
  • 'Access Token'
  • 'Access Token Secret'
  1. But in order to get them first you need to go to the projects portal, create a project and add an app.

So the journey starts here.

image

  1. At the bottom of the page, click on Add App.

image

  1. I already have a Production one, so i will use a Development environment. Next

image

  1. Add App Name. Next

image

SAVE THE BELOW KEYS

and no worries, i have regenerated the below

image

  1. Now to App settings then Keys and Tokens.

We need to generate an Access Key and an Access Token.

image

  1. And save them!

image

  1. And now... the code:
import tweepy
from credentials import twitter_bot_keys
auth = tweepy.OAuthHandler(twitter_bot_keys['API Key'], twitter_bot_keys['API Key Secret'])
auth.set_access_token(twitter_bot_keys['Access Token'], twitter_bot_keys['Access Token Secret'])
api = tweepy.API(auth)

credentials.py is a locally saved file that stores a dictionary with our keys, file has strict permissions and can only be viewed with root.

twitter_bot_keys = {
'API Key': 'xxxxx',
'API Key Secret': 'xxxxxx',
'Bearer token': 'xxxxxx',
'Access Token':'xxxxxx',
'Access Token Secret':'xxxxxxx'
}