The currency command converts an amount from one currency to another using the Fawazahmed0 Currency API.

Usage

!currency <amount> <from_currency> <to_currency>

Aliases: !convert, !conv

Example response

User:

!currency 100 usd eur

Bot:

100.0 USD = 92.50 EUR

Source code

def currency(currency1, currency2, amount):
    try:
        amount = float(amount)
    except (TypeError, ValueError):
        return error_messages["currency"]
 
    currency1 = currency1.lower()
    currency2 = currency2.lower()
 
    available_currencies = requests.get(
        "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies.json"
    )
    if available_currencies.status_code != 200:
        return error_messages["unavailable"]
 
    available_currencies = available_currencies.json()
 
    if currency1 not in available_currencies:
        return f"{error_messages['currency']} ({currency1})"
    if currency2 not in available_currencies:
        return f"{error_messages['currency']} ({currency2})"
 
    raw_response = requests.get(
        f"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/{currency1}.json"
    )
    if raw_response.status_code != 200:
        return error_messages["unavailable"]
 
    raw_response = raw_response.json()
 
    if currency1 not in raw_response or currency2 not in raw_response[currency1]:
        return error_messages["currency"]
 
    rate = raw_response[currency1][currency2]
    converted_amount = rate * amount
    response = (
        choice(output["general"]["currency"])
        .replace(r"{{FROM_AMOUNT}}", str(amount))
        .replace(r"{{FROM_CURRENCY}}", currency1.upper())
        .replace(r"{{TO_AMOUNT}}", f"{converted_amount:.2f}")
        .replace(r"{{TO_CURRENCY}}", currency2.upper())
    )
    return response