Browse Source

Add support for uploading avatars.

pull/42/merge
Rapptz 9 years ago
parent
commit
f0617fbb6a
  1. 19
      discord/client.py
  2. 10
      discord/utils.py

19
discord/client.py

@ -48,6 +48,7 @@ import sys
import logging
import itertools
import datetime
from base64 import b64encode
log = logging.getLogger(__name__)
request_logging_format = '{response.request.method} {response.url} has returned {response.status_code}'
@ -1039,18 +1040,34 @@ class Client(object):
This function raises :exc:`HTTPException` if the request failed.
To upload an avatar, a *bytes-like object* must be passed in that
represents the image being uploaded. If this is done through a file
then the file must be opened via ``open('some_filename', 'rb')`` and
the *bytes-like object* is given through the use of ``fp.read()``.
The only image formats supported for uploading is JPEG and PNG.
:param password: The current password for the client's account.
:param new_password: The new password you wish to change to.
:param email: The new email you wish to change to.
:param username: The new username you wish to change to.
:param avatar: A *bytes-like object* representing the image to upload.
"""
avatar_bytes = fields.get('avatar')
avatar = self.user.avatar
if avatar_bytes is not None:
fmt = 'data:{mime};base64,{data}'
mime = utils._get_mime_type_for_image(avatar_bytes)
b64 = b64encode(avatar_bytes).decode('ascii')
avatar = fmt.format(mime=mime, data=b64)
payload = {
'password': password,
'new_password': fields.get('new_password'),
'email': fields.get('email', self.email),
'username': fields.get('username', self.user.name),
'avatar': self.user.avatar
'avatar': avatar
}
url = '{0}/@me'.format(endpoints.USERS)

10
discord/utils.py

@ -25,7 +25,7 @@ DEALINGS IN THE SOFTWARE.
"""
from re import split as re_split
from .errors import HTTPException
from .errors import HTTPException, InvalidArgument
import datetime
@ -65,3 +65,11 @@ def _verify_successful_response(response):
success = code >= 200 and code < 300
if not success:
raise HTTPException(response)
def _get_mime_type_for_image(data):
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
return 'image/png'
elif data.startswith(b'\xFF\xD8') and data.endswith(b'\xFF\xD9'):
return 'image/jpeg'
else:
raise InvalidArgument('Unsupported image type given')

Loading…
Cancel
Save