-
-
Save michaeltrainor/4711195a462c729bd5a8a10e02c4033f to your computer and use it in GitHub Desktop.
Get a bearer token for Twitter application-only requests in Python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# | |
# Copyright (C) 2015-2018 Bitergia | |
# | |
# This program is free software; you can redistribute it and/or modify | |
# it under the terms of the GNU General Public License as published by | |
# the Free Software Foundation; either version 3 of the License, or | |
# (at your option) any later version. | |
# | |
# This program is distributed in the hope that it will be useful, | |
# but WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
# GNU General Public License for more details. | |
# | |
# You should have received a copy of the GNU General Public License | |
# along with this program; if not, write to the Free Software | |
# Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA. | |
# | |
# Authors: | |
# Valerio Cosentino <valcos@bitergia.com> | |
# | |
from __future__ import print_function | |
import base64 | |
import requests | |
import urllib.parse | |
OAUTH2_TOKEN = 'https://api.twitter.com/oauth2/token' | |
def get_bearer_token(consumer_key, consumer_secret): | |
# enconde consumer key | |
consumer_key = urllib.parse.quote(consumer_key) | |
# encode consumer secret | |
consumer_secret = urllib.parse.quote(consumer_secret) | |
# create bearer token | |
bearer_token = consumer_key + ':' + consumer_secret | |
# base64 encode the token | |
base64_encoded_bearer_token = base64.b64encode(bearer_token.encode('utf-8')) | |
# set headers | |
headers = { | |
"Authorization": "Basic " + base64_encoded_bearer_token.decode('utf-8') + "", | |
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", | |
"Content-Length": "29"} | |
response = requests.post(OAUTH2_TOKEN, headers=headers, data={'grant_type': 'client_credentials'}) | |
to_json = response.json() | |
print("token_type = %s\naccess_token = %s" % (to_json['token_type'], to_json['access_token'])) | |
def main(): | |
consumer_key = input('Enter your consumer key: ') | |
consumer_secret = input('Enter your consumer secret: ') | |
print("***** ***** ***** *****") | |
get_bearer_token(consumer_key, consumer_secret) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment