-
-
Save mpkocher/e0c3a61a5314a0ce852fca9632053ded to your computer and use it in GitHub Desktop.
This file contains hidden or 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
"""PyBites Amazon book affiliation link generator. | |
Uses the link pasted to clipboard and puts the generated link back onto the | |
clipboard. https://pybit.es/pyperclip.html | |
Set the AMAZON_AFFILIATE_CODE variable to your own Amazon affiliate code. | |
From https://twitter.com/pybites/status/1277141497117323266 | |
Separate concerns and enable other AF codes to be registered and | |
trivially plugged into the system. | |
""" | |
import os | |
import re | |
import subprocess | |
import sys | |
import pyperclip | |
AFFILIATION_CODE = os.environ.get("AMAZON_AFFILIATE_CODE", "pyb0f-20") | |
AFFILIATION_LINK = "http://www.amazon.com/dp/{asin}/?tag={code}" | |
def to_amazon(url, code=AFFILIATION_CODE): | |
if "amazon" not in url or "/dp/" not in url: | |
raise ValueError(f"{url} is not a valid Amazon link") | |
asin = re.sub(r".*/dp/([^/]+).*", r"\1", url) | |
return AFFILIATION_LINK.format(asin=asin, code=code) | |
def _to_mock_af(must_contain): | |
"""Crude util to generate mock AF processors""" | |
def f(url): | |
if must_contain in url: | |
return f"{url}?code=MOCK_CODE" | |
raise ValueError(f"Not a valid URL. Must contain {must_contain}") | |
return f | |
def apply_transform(func) -> str: | |
url = pyperclip.paste() | |
link = func(url) | |
pyperclip.copy(link) | |
return link | |
def main(): | |
names = ["ebay", "spotify", "ubereats"] | |
mocked = [_to_mock_af(n) for n in names] | |
funcs = [to_amazon] + mocked | |
for f in funcs: | |
try: | |
url = apply_transform(f) | |
print(f"Successfully copied link to clipboard: {url}") | |
return 0 | |
except ValueError: | |
pass | |
raise ValueError(f"Unable to assign affiliate code to clipboard") | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment