sreejith2904

Get Recipe Script

Sep 2nd, 2024
629
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. import requests
  2. import random
  3. import json
  4. import sys
  5.  
  6. # Replace these variables with your actual Linkding server URL and API token
  7. LINKDING_SERVER_URL = "http://10.0.0.101:9090"
  8. API_TOKEN = "Token"
  9.  
  10. # Function to retrieve bookmarks by tag
  11. def get_bookmarks_by_tag(tag):
  12.     url = f"{LINKDING_SERVER_URL}/api/bookmarks/?tags={tag}"
  13.     headers = {
  14.         "Authorization": f"Token {API_TOKEN}"
  15.     }
  16.     response = requests.get(url, headers=headers)
  17.     if response.status_code == 200:
  18.         bookmarks = response.json().get("results", [])
  19.         return bookmarks
  20.     else:
  21.         print(f"Failed to retrieve bookmarks by tag. Status code: {response.status_code}")
  22.         print(response.text)
  23.         return []
  24.  
  25. def filter_bookmarks_by_tag(bookmarks, tag):
  26.     tag = tag.lower()
  27.     filtered_bookmarks = [
  28.         bookmark for bookmark in bookmarks
  29.         if tag in [t.lower() for t in bookmark.get("tag_names", [])]
  30.     ]
  31.     return filtered_bookmarks
  32.  
  33.  
  34. # Function to pick 3 random bookmarks and print their fields
  35. def print_random_bookmarks(bookmarks, tag, num=3):
  36.  
  37.     bookmarks = filter_bookmarks_by_tag(bookmarks, tag)
  38.  
  39.     if len(bookmarks) < num:
  40.         print(f"Less than {num} bookmarks found. Printing all available bookmarks:")
  41.         num = len(bookmarks)
  42.  
  43.     random_bookmarks = random.sample(bookmarks, num)
  44.  
  45.     response = {}
  46.     for i, bookmark in enumerate(random_bookmarks):
  47.         response["Title_" + str(i+1)] = bookmark.get("title")
  48.         response["URL_" + str(i+1)] = bookmark.get("url")
  49.         response["Description_" + str(i+1)] = bookmark.get("description", "No description available")
  50.  
  51.     with open('/config/www/recipe_script_output.json', 'w') as f:
  52.         json.dump(response, f)
  53.  
  54.     print(json.dumps(response))
  55.  
  56.  
  57. # Main function
  58. if __name__ == "__main__":
  59.     # Check if the tag is passed as an argument
  60.     if len(sys.argv) > 1:
  61.         tag = sys.argv[1]
  62.     else:
  63.         print("Please provide a tag as a parameter.")
  64.         sys.exit(1)
  65.  
  66.     bookmarks = get_bookmarks_by_tag(tag)
  67.  
  68.     if bookmarks:
  69.         print_random_bookmarks(bookmarks, tag)
  70.     else:
  71.         print("No bookmarks found for the specified tag.")
Advertisement
Add Comment
Please, Sign In to add comment