Map tile on Discord with Python


I am currently trying to retrieve a traffic flow map for my area, and I would like to send it to a Discord channel.
The goal is to get the Raster Flow Tile we can see here:

The issue when I try to retrieve it with the code below, VSCode tells me this:
Command raised an exception: OSError: [WinError 6] Descripteur non valide
I guess it can be translated as : OSError: [WinError 6] The handle is invalid

import os
import json
import sys
import discord
import urllib.request

async def fd_road_map_tomtom():
        api_key = os.getenv('TOMTOM_TOKEN')
        api_url = f"[redacted]/[redacted].png?thickness=2&tileSize=512&key={api_key}"
        imageRequest = urllib.request.urlopen(api_url)
        imageBinary =
        image = sys.stdout.buffer.write(imageBinary)
        file = discord.File(image)
        return file

In an other function I have the following, that works well except for the image.

async def trafficFlow(self, ctx):
        choosenTime = None
            embed = await fd_road_cond_tomtom(choosenTime)
            await ctx.send(embed=embed)
            print('Les données n\ont pas pu être récupérées.')
           tomtomMap = await fd_road_map_tomtom()
           await ctx.send('TempsReel.png', file=tomtomMap)

How can this be solved?


Do you have an indication which line caused that?

image = sys.stdout.buffer.write(imageBinary)
file = discord.File(image)

If I’m not wrong… write() returns the number of written bytes, so It’s not a handle to a file.


Thanks for your response. Finally, here is what I did, may someone want the answer. Plus, I also combined the traffic map with the empty background, with the real map background:

import os
import requests
from PIL import Image

async def fd_road_map_tomtom():
    api_key = os.getenv('TOMTOM_TOKEN')
    api_url = f"{tile x here}/{tile y here}.png?thickness=5&tileSize=512&key={api_key}"
    r=requests.get(api_url, stream=True)
    if r.status_code == 200:
        with open('./functions/temp/TomTomTempsReel.png', 'wb') as f:
            print('got here')

            if 6 <= <= 18:   # Daytime map background
                background ='./functions/temp/TomTomJournee.png')
            else:    # Nighttime map background
                background ='./functions/temp/TomTomSoir.png')

            img ='./functions/temp/TomTomTempsReel.png')
            background.paste(img, (0, 0), img)

            file = discord.File('./functions/temp/TomTomTempsReel.png')
        file = discord.File('./functions/temp/TomTomLogo.png')
    return file