-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
60 lines (48 loc) · 1.9 KB
/
main.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import argparse
import logging
import os
from urllib.parse import urlparse
import requests
from dotenv import load_dotenv
logging.basicConfig(level=logging.INFO)
def shorten_link(url, token):
headers = {'Authorization': f'Bearer {token}'}
long_url = {"long_url": url}
response = requests.post('https://api-ssl.bitly.com/v4/bitlinks', headers=headers, json=long_url)
response.raise_for_status()
return response.json().get('link')
def get_clicks(url, token):
headers = {'Authorization': f'Bearer {token}'}
parsed_url = urlparse(url)
bitlink = f'{parsed_url.netloc}{parsed_url.path}'
response = requests.get(f'https://api-ssl.bitly.com/v4/bitlinks/{bitlink}/clicks/summary',
headers=headers)
response.raise_for_status()
return response.json().get("total_clicks")
def is_bitlink(url, token):
parsed_url = urlparse(url)
bitlink = f'{parsed_url.netloc}{parsed_url.path}'
headers = {'Authorization': f'Bearer {token}'}
response = requests.get(f'https://api-ssl.bitly.com/v4/bitlinks/{bitlink}', headers=headers)
return response.ok
def main():
load_dotenv()
token = os.getenv('BITLY_TOKEN')
parser = argparse.ArgumentParser(
description='Script creates short bitlinks for long urls, and gets clicks on existing bitlinks')
parser.add_argument('url', help='long url or bitlink')
url = parser.parse_args().url
if urlparse(url).netloc:
try:
if is_bitlink(url, token):
print(f'Clicks: {get_clicks(url, token)}')
else:
print(f'Bitlink: {shorten_link(url, token)}')
except ConnectionError as ex:
logging.error(f'Internet Problems: {ex}')
except requests.exceptions.HTTPError:
logging.error(f'What you are looking for cannot be found.')
else:
logging.error(f'Bad Link')
if __name__ == '__main__':
main()