Exemplo n.º 1
0
def get_vpr_images_data(data,
                        nImages,
                        dayNow,
                        nImagesForYesterday=None,
                        dataYesterday=None):
    regiao = "BR"
    APIBaseURL = "https://apisat.inmet.gov.br"

    URLsToBeRequested = []

    for hourToday in data[:nImages]:
        URLsToBeRequested.append(
            f"{APIBaseURL}/GOES/{regiao}/VP/{dayNow}/{hourToday['sigla']}")

    if dataYesterday:
        nImages = nImages + nImagesForYesterday

        for hour in dataYesterday[:nImagesForYesterday]:
            URLsToBeRequested.append(
                f"{APIBaseURL}/GOES/{regiao}/VP/{arrow.utcnow().shift(days=-1).format('YYYY-MM-DD')}/{hour['sigla']}"
            )

    responses = list(
        filter(lambda x: x.status_code == 200,
               fgrequests.build(URLsToBeRequested)))
    responseData = [entry.json() for entry in responses]

    return responseData
Exemplo n.º 2
0
def get_vpr_gif(data, nImages, dayNow, nImagesForYesterday=None, dataYesterday=None):
    regiao = "BR"
    APIBaseURL = "https://apisat.inmet.gov.br"

    URLsToBeRequested = []

    for hourToday in data[:nImages]:
        URLsToBeRequested.append(
            f"{APIBaseURL}/GOES/{regiao}/VP/{dayNow}/{hourToday['sigla']}"
        )

    if dataYesterday:
        nImages = nImages + nImagesForYesterday

        for hour in dataYesterday[:nImagesForYesterday]:
            URLsToBeRequested.append(
                f"{APIBaseURL}/GOES/{regiao}/VP/{arrow.utcnow().shift(days=-1).format('YYYY-MM-DD')}/{hour['sigla']}"
            )

    responses = list(
        filter(lambda x: x.status_code == 200, fgrequests.build(URLsToBeRequested))
    )
    data = [entry.json() for entry in responses]

    readImages = []
    for entry in reversed(data[:nImages]):
        loadedImg = loadB64ImageToMemory(entry["base64"])
        readImages.append(imageio.imread(loadedImg))

    uniqueID = uuid.uuid4().hex
    gifFilename = os.path.join("tmp", f"VPR_{uniqueID}.mp4")

    kargs = {"fps": 10, "macro_block_size": None}
    imageio.mimsave(f"{gifFilename}", readImages, "MP4", **kargs)

    return gifFilename
Exemplo n.º 3
0
import fgrequests

urls = ['https://www.google.com']

response = fgrequests.build(urls, verify=False)

assert type(response) == list
Exemplo n.º 4
0
import fgrequests

# Send file through request
urls = ['https://httpbin.org/post']
files = {'file': open('requirements.txt', 'rb')}

response = fgrequests.build(urls, method='POST', files=files)
assert type(response) == list
'''
print(response[0].text)
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}
'''

urls = ['https://httpbin.org/post']
files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}

response = fgrequests.build(urls, method='POST', files=files)
assert type(response) == list
'''
print(response[0].text)
{
  ...
  "files": {
    "file": "some,data,to,send\nanother,row,to,send\n"
  }, 
Exemplo n.º 5
0
import fgrequests

arr = ['https://google.com']

response = fgrequests.build(arr, method='POST', headers={
    'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-us,en;q=0.5',
    'Accept-Encoding': 'gzip,deflate',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
    'Keep-Alive': '300',
    'Connection': 'keep-alive',
    'Cookie': 'PHPSESSID=r2t5uvjq435r4q7ib3vtdjq120',
    'Pragma': 'no-cache',
    'Cache-Control': 'no-cache',
})
assert type(response) == list
Exemplo n.º 6
0
import fgrequests

arr = ['https://wrongdomain.com']

response = fgrequests.build(arr)
assert type(response) == list
Exemplo n.º 7
0
import fgrequests

arr = ['https://wrongdomain.com']

response = fgrequests.build(arr, timeout=3)
assert type(response) == list
Exemplo n.º 8
0
import fgrequests

arr = ['https://google.com']

response = fgrequests.build(arr, method='POST', show_execution_time=True)
assert type(response) == dict
assert type(response['response_list']) == list
Exemplo n.º 9
0
import fgrequests

arr = ['https://gitlab.com/FaridLU/fgrequests']

response = fgrequests.build(arr, allow_redirects=True)
assert response[0].status_code == 200

response = fgrequests.build(arr, allow_redirects=False)
assert response[0].status_code != 200

response = fgrequests.build(arr)
assert response[0].status_code == 200
Exemplo n.º 10
0
import fgrequests

arr = ['https://google.com']

response = fgrequests.build(arr, method='DELETE')
assert type(response) == list
Exemplo n.º 11
0
import fgrequests

arr = ['https://google.com']

response = fgrequests.build(arr, method='POST')
assert type(response) == list
Exemplo n.º 12
0
def cmd_vpr(update, context):
    """Fetch and send latest VPR satellite image to the user."""

    try:
        # "Guess" image from INMET's API
        APIBaseURL = "https://apisat.inmet.gov.br/"
        regiao = "BR"

        # Get current time
        utcNow = arrow.utcnow()
        dayNow = utcNow.format("YYYY-MM-DD")
        minutesNow = utcNow.format("mm")

        # Get round hours
        floorMinutes = int(minutesNow) // 10 * 10
        floorDate = utcNow.replace(minute=floorMinutes)

        # Create headers for requests
        headers = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
        }

        # We do this because retrieving hours from the API takes several seconds, so it is faster to guess endpoints (only three are possible)
        requestURLS = []
        for i in range(1, 4):
            tryDate = floorDate.shift(minutes=-i * 10)
            requestURLS.append(
                f"{APIBaseURL}GOES/{regiao}/VP/{dayNow}/{tryDate.format('HH:mm')}"
            )

        # Request all URLs, filter the most recent one that was successful
        response = list(
            filter(lambda x: x.status_code == 200, fgrequests.build(requestURLS))
        )
        # Get json from the response
        vprData = response[0].json()

        context.bot.send_chat_action(
            chat_id=update.effective_message.chat_id,
            action=telegram.ChatAction.UPLOAD_PHOTO,
        )

        # Load image from base64 to memory
        vprImage = bot_utils.loadB64ImageToMemory(vprData["base64"])

        hourLastImage = arrow.get(vprData["hora"], "HH:mm").to("-03:00").format("HH:mm")
        hourLastImageCaption = f" ({hourLastImage})."

        caption = bot_messages.lastAvailableImageCaption + hourLastImageCaption

        # Send image from memory
        context.bot.send_photo(
            chat_id=update.effective_chat.id,
            reply_to_message_id=update.message.message_id,
            photo=vprImage,
            caption=caption,
            timeout=20000,
        )
    # If no request was successful
    except IndexError:
        try:
            # Request all images from today
            response = requests.get(
                f"{APIBaseURL}GOES/{regiao}/VP/{dayNow}",
                headers=headers,
                allow_redirects=False,
            )

            if response.status_code == 200:
                # Get only the latest image
                data = response.json()[0]
                functionsLogger.info("Successful GET request to API VPR endpoint!")

                context.bot.send_chat_action(
                    chat_id=update.effective_message.chat_id,
                    action=telegram.ChatAction.UPLOAD_PHOTO,
                )

                # Load image from base64 to memory
                vprImage = bot_utils.loadB64ImageToMemory(data["base64"])

                # Send image from memory
                context.bot.send_photo(
                    chat_id=update.effective_chat.id,
                    reply_to_message_id=update.message.message_id,
                    photo=vprImage,
                    caption=bot_messages.lastAvailableImageCaption,
                    timeout=20000,
                )
        # If all else fails
        except IndexError:
            context.bot.send_message(
                chat_id=update.effective_chat.id,
                reply_to_message_id=update.message.message_id,
                text=bot_messages.unavailableImage,
            )