Home>
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
import requests
from config import token
bot= Bot(token=token)
dp= Dispatcher(bot)
@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
    await message.reply("Hi!\nCommands:\n/btc -bitcoin rate\n/eth -ethereum rate\n/doge -dogecoin rate\n/ltc -litecoin rate")
@dp.message_handler(commands=['btc'])
async def btc(message: types.Message):
    response= requests.get(url="https://min-api.cryptocompare.com/data/price?fsym=BTC&
tsyms=USD")
    await message.reply(response.text)
@dp.message_handler(commands=['eth'])
async def eth(message: types.Message):
    response= requests.get(url="https://min-api.cryptocompare.com/data/price?fsym=ETH&
tsyms=USD")
    print(response.text)
    await message.reply(response.text)
@dp.message_handler(commands=['doge'])
async def eth(message: types.Message):
    response= requests.get(url="https://min-api.cryptocompare.com/data/price?fsym=DOGE&
tsyms=USD")
    print(response.text)
    await message.reply(response.text)
@dp.message_handler(commands=['ltc'])
async def eth(message: types.Message):
    response= requests.get(url="https://min-api.cryptocompare.com/data/price?fsym=LTC&
tsyms=USD")
    print(response.text)
    await message.reply(response.text)
if __name__== '__main__':
    executor.start_polling(dp)

It seems to me that for an asynchronous bot it is better to use an asynchronous library for network requests. If that library does not have a json analogue like requests, then parse the response through the built-in json library: docs.python.org/3/library/json.html#json.loads

gil9red2022-02-14 10:30:48
  • Answer # 1

    I understand you need this:

    @dp.message_handler(commands=['btc'])
    async def btc(message: types.Message):
        response= requests.get(url="https://min-api.cryptocompare.com/data/price?fsym=BTC&
    tsyms=USD")
        result= response.text.replace("{", "") # Replace { character with air
        await message.reply(result)
    
  • Answer # 2

    You don't need to parse the text, but process the response asJSON, because the site returns it

    Actions:

    • Via methodjsonparse the response
    • Pull data by key

    Example:

    import requests
    rs= requests.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&
    tsyms=USD')
    print(rs.text) # As text
    # {"USD":42193.22}
    print(rs.json()) # As parsed JSON
    #{'USD': 42193.22}
    print(rs.json()['USD'])
    # 42191.13
    

    It is possible to extract the value of a dictionary without a key:

    print(list(rs.json().values())[0])
    # 42191.13