skip to Main Content

What I want to do is to send a message when the user uses the command

/cotizacion

That message should look like this:

Ultima Actualizacion: content[fecha]
Compra: content[compra]
Venta: content[venta]
Variacion: content[variacion]

What I cannot do is:

  1. Add the text (e.g. Ultima Actualizacion)
  2. Show the information in multiple lines (as shown above)

I have tried everything, using, or + and I’m really lost, as I am new to Python.

from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import requests
import re

def get_cotizacion():
    content = requests.get('https://mercados.ambito.com/dolar/oficial/variacion').json()
    fecha = content['fecha']
    compra = content['compra']
    venta = content['venta']
    variacion = content['variacion']
    cotizacion = (fecha+ compra+ venta+ variacion)
    return cotizacion

def cotizacion(bot, update):
    cotizacion = get_cotizacion()
    chat_id = update.message.chat_id
    bot.send_message(chat_id=chat_id, text= cotizacion)

def main():
    updater = Updater('#######')
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('cotizacion',cotizacion))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

2

Answers


  1. I only know python so i can just tell you how to build a string from your json as i know nothing about the telegram bot. I´ll assume that the content is a string (if not you might need to convert it)

    You can do this:

    cotizacion = "Ultima Actualizacion: " + content[fecha] + n + "Compra: " + ...
    

    n represents a line break and + adds mutliple strings together

    You can convert numbers etc. to strings with str(my_number) – this might help if your json returns something other than a string
    It wont work with lists though so check your data types.

    If you dont want to hard code it like this you might want to use a dict like this:
    {
    “Ultima Actualizacion”: “fecha”,
    “Compra”: “compra”,

    }

    There are probably better solutions but these are the first ones that came to my mind =)

    Login or Signup to reply.
  2. You can use ‘n’ for new line. So your code could be like this.

    cotizacion = 'n'.join('Ultima Actualizacion: ' + fecha, 'Compra: ' + compra, 'Venta: ' + venta, 'Variacion: ' + variacion)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search