4
votes

I'm I'm a beginner with python but I'm trying to make a discord bot who send a welcome message when the member join the server. I want to send an image modified with PILLOW in the chat. I made that :

if message.content == ".welcome":
        member = message.author
        url = member.avatar_url
        hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
               'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
               'Accept-Encoding': 'none',
               'Accept-Language': 'en-US,en;q=0.8',
               'Connection': 'keep-alive'}

        req = urllib2.Request(url, headers=hdr)
        result = urllib2.urlopen(req)
        file = result.read()
        img = Image.open(io.BytesIO(file))

        name = str(member.display_name)
    #    await bot.send_message(testbot, member.avatar_url)
        await bot.send_file(testbot, img)

but I have this error :

Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/client_reqrep.py", line 407, in write_bytes
    result = stream.send(value)
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/helpers.py", line 191, in _gen_form_data
    yield from self._writer.serialize()
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/multipart.py", line 969, in serialize
    yield from part.serialize()
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/multipart.py", line 768, in serialize
    yield from self._maybe_encode_stream(self._serialize_obj())
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/multipart.py", line 781, in _serialize_obj
    return self._serialize_default(obj)
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/multipart.py", line 813, in _serialize_default
    raise TypeError('unknown body part type %r' % type(obj))
TypeError: unknown body part type <class 'PIL.WebPImagePlugin.WebPImageFile'>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.5/site-packages/discord/client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "/home/pi/Desktop/bot.py", line 88, in on_message
    await bot.send_file(testbot, img)
  File "/home/pi/.local/lib/python3.5/site-packages/discord/client.py", line 1235, in send_file
    filename=filename, content=content, tts=tts)
  File "/home/pi/.local/lib/python3.5/site-packages/discord/http.py", line 137, in request
    r = yield from self.session.request(method, url, **kwargs)
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/client.py", line 555, in __iter__
    resp = yield from self._coro
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/client.py", line 202, in _request
    yield from resp.start(conn, read_until_eof)
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/client_reqrep.py", line 640, in start
    message = yield from httpstream.read()
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/streams.py", line 641, in read
    result = yield from super().read()
  File "/home/pi/.local/lib/python3.5/site-packages/aiohttp/streams.py", line 476, in read
    yield from self._waiter
  File "/usr/lib/python3.5/asyncio/futures.py", line 380, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/lib/python3.5/asyncio/tasks.py", line 304, in _wakeup
    future.result()
  File "/usr/lib/python3.5/asyncio/futures.py", line 293, in result
    raise self._exception
aiohttp.errors.ClientRequestError: Can not write request body for https://discordapp.com/api/v6/channels/445990287152644096/messages

if someone know why I have this error...

1

1 Answers

3
votes

First of all, you should not be using urllib or requests to make http requests while dealing with asyncio and coroutines as they are not async-safe (the requests they make are blocking). You should instead use an asynchronous request library (ie. aiohttp) to make requests while using discord.py.

As for your error, send_file takes a file-like object, not a PIL Image, so you'll need to save the image to a file or BytesIO first.

from re import search
import aiohttp

@bot.event
async def on_message(m):
    member = m.author
    url = member.avatar_url
    file_name = search("/(\w+\.\w+)(?:\?.*?)?$", url)
    if file_name is None:
        file_name = "avatar.jpg"  # If there's a problem with my regex
    else:
        file_name = file_name.group(1)

    hdr = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
        'Accept-Encoding': 'none',
        'Accept-Language': 'en-US,en;q=0.8',
        'Connection': 'keep-alive'}

    async with aiohttp.ClientSession() as client:
        async with client.get(url, headers=hdr) as req:
            bytes_image = await req.read()

    with io.BytesIO(bytes_image) as f:
        f.name = file_name
        img = Image.open(f)

    #######
    # do stuff with `img`
    #######

    with io.BytesIO() as f:
        f.name = file_name
        img.save(f)
        f.seek(0)
        await bot.send_file(m.channel, f)