Developing a Currency Converter Telegram Bot in Python

I’m building a Telegram bot using Python 3 that converts currencies. Currently, the bot retrieves exchange rate data and displays a raw JSON response with braces and quotes in the chat. How can I improve the presentation to make it look neater?

import requests


def query_handler(query_msg):
    callback_id, user_identifier, currency_code = telepot.glance(query_msg, flavor='callback_query')
    print('Received callback:', callback_id, user_identifier, currency_code)

    endpoint = "http://api.exchangerate.host/latest?base=USD&symbols="
    reply = requests.get(endpoint + currency_code).json()
    print('Exchange info:', reply)

    if currency_code == 'USD':
        bot.sendMessage(user_identifier, reply)
    elif currency_code == 'GBP':
        bot.sendMessage(user_identifier, reply)

hey try using json.dumps(reply, indent=2) to pretty print the response before sending it. it makes it far more readable and clean in the message. hope it helps!

One alternative method to improve the presentation is to selectively format only the parts of the JSON that are relevant to the user. Instead of dumping the full JSON response, I have manually parsed the returned data into a formatted string that lists the most important values. This not only avoids overwhelming users with raw JSON but also makes the message clearer and more customized. This approach often involves simple string concatenation or using the str.format method after retrieving the necessary data from the response.

I have found that instead of sending the entire raw JSON output, it is much more efficient to extract the relevant data and reformat it before sending it to the chat. In one project, I used Python f-strings to create a concise message that only included the currency code, the exchange rate, and the last update time if available. Besides improving readability, this method gives you room to include error handling or additional context for the data. Using templated messages also makes future adjustments easier and keeps users from being overwhelmed by unnecessary details.