Creating a Telegram Bot with Python

I’m currently developing a currency converter bot for Telegram using Python 3. Here’s my code snippet:

def handle_query(message):
    query_id, user_id, currency = telepot.glance(message, flavor='callback_query')
    print('Received Query:', query_id, user_id, currency)

api_url = "http://api.fixer.io/latest?base=SGD&symbols="
requested_currency = currency
response = requests.get(api_url + requested_currency)
data = response.json()
print(data)

if(currency == 'SGD'):
    bot.sendMessage(user_id, data)

elif (currency == 'EUR'):
    bot.sendMessage(user_id, data)

This displays data in my Telegram chat like {‘rates’: {‘EUR’: 0.62177}, ‘base’: ‘SGD’, ‘date’: ‘2017-09-18’}. How can I format the output to remove the curly braces and quotes for better readability?

try using python’s f-strings to format the output or the .format() method. You could extract values from the json and print them neatly. Something like: bot.sendMessage(user_id, f"{currency} rate is {data['rates'][currency]}"). This will remove the brackets and make it more readable in the chat :slightly_smiling_face:

In addition to formatting the output, you might want to further improve user experience by adding some additional context in your response message. Consider including the date of the conversion rate in your message so users have a clear reference. You can achieve this by using the date information from the API response. For example, you can modify your response to be: bot.sendMessage(user_id, f"As of {data['date']}, the {currency} rate is {data['rates'][currency]}"). This ensures users know how current the rate is.

hey, you could also use the .strip() method in a creative way to clean the output. First, convert the dictionary to a string and then use .strip('{', '}', '"') on it to remove unwanted characters. this isn’t the most efficient, but totally works for simple cases. :sweat_smile:

Another approach you can try is to construct the message in parts to provide a cleaner, structured output. Start by extracting the specific values you want to display. For instance, extract the rate and date separately and then construct a response message.

Here’s an example:

rate = data['rates'][currency]
date = data['date']
message = f"Currency conversion: 1 SGD = {rate} {currency} on {date}"
bot.sendMessage(user_id, message)

This approach makes the message more readable and user-friendly by eliminating unnecessary characters and directly pointing out pertinent information.