Skip to content

Instantly share code, notes, and snippets.

@valeriocos
Created June 7, 2018 12:54
Show Gist options
  • Save valeriocos/7d4d28f72f53fbce49f1512ba77ef5f6 to your computer and use it in GitHub Desktop.
Save valeriocos/7d4d28f72f53fbce49f1512ba77ef5f6 to your computer and use it in GitHub Desktop.

Revisions

  1. valeriocos created this gist Jun 7, 2018.
    61 changes: 61 additions & 0 deletions get-bearer-token-twitter-api
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    #!/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 <[email protected]>
    #

    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()