forked from x4nth055/pythoncode-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitly_shortener.py
39 lines (33 loc) · 1.29 KB
/
bitly_shortener.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import requests
import sys
# account credentials
username = "o_3v0ulxxxxx"
password = "your_password_here"
# the URL you want to shorten
url = sys.argv[1]
# get the access token
auth_res = requests.post("https://api-ssl.bitly.com/oauth/access_token", auth=(username, password))
if auth_res.status_code == 200:
# if response is OK, get the access token
access_token = auth_res.content.decode()
print("[!] Got access token:", access_token)
else:
print("[!] Cannot get access token, exiting...")
exit()
# construct the request headers with authorization
headers = {"Authorization": f"Bearer {access_token}"}
# get the group UID associated with our account
groups_res = requests.get("https://api-ssl.bitly.com/v4/groups", headers=headers)
if groups_res.status_code == 200:
# if response is OK, get the GUID
groups_data = groups_res.json()['groups'][0]
guid = groups_data['guid']
else:
print("[!] Cannot get GUID, exiting...")
exit()
# make the POST request to get shortened URL for `url`
shorten_res = requests.post("https://api-ssl.bitly.com/v4/shorten", json={"group_guid": guid, "long_url": url}, headers=headers)
if shorten_res.status_code == 200:
# if response is OK, get the shortened URL
link = shorten_res.json().get("link")
print("Shortened URL:", link)