summaryrefslogblamecommitdiffstats
path: root/dict.py
blob: 31676d61d4c502e7867021d6535bbfecc99d5e46 (plain) (tree)
1
2
3
4
5
6
7
8
9
10









                                                 
                 














                                                                           
                 














                                                                         
                                   

                                                  
                           




                                                                           
#!/bin/python

import requests
import random
import os
import sys  # Import for potential error handling

# Customizable word list path
WORD_LIST_PATH = "~/.local/share/vocab/words.txt"

def fetch_dict():
    """Retrieves a random word and definition from Urban Dictionary API."""
    url = "http://api.urbandictionary.com/v0/random"

    try:
        response = requests.get(url, timeout=2)
        response.raise_for_status()  # Raise an exception if request failed

        data = response.json()
        word = data['list'][0]['word']
        definition = data['list'][0]['definition']
        return word, definition

    except requests.exceptions.RequestException:
        return None, None

def local_dict():
    """Retrieves a random word from the local word list."""
    try:
        # Expand '~' for the home directory in the path
        word_list_path = os.path.expanduser(WORD_LIST_PATH)

        with open(word_list_path, 'r') as file:
            words = file.readlines()
        # Choose a random word (assuming words are separated by newlines)
        return words[random.randint(0, len(words) - 1)].strip()

    except (FileNotFoundError, PermissionError) as e:
        print(f"Error reading local word list: {e}")
        return None

if __name__ == "__main__":
    word, definition = fetch_dict()

    if not word:  # Check if word retrieval failed
        word = local_dict()

    if word:
        os.system(f"cowsay '{word} -> {definition if definition else ''}'")
    else:
        print("Could not get a word from either source.")