1
0
mirror of https://github.com/eternnoir/pyTelegramBotAPI.git synced 2023-08-10 21:12:57 +03:00

Merge pull request #929 from mrpes/patch-3

Support for sending PIL images in sendPhoto / sendChatPhoto as photo argument.
This commit is contained in:
Badiboy 2020-07-31 11:06:31 +03:00 committed by GitHub
commit 9a3f370dce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 6 deletions

View File

@ -329,10 +329,12 @@ def send_photo(
method_url = r'sendPhoto' method_url = r'sendPhoto'
payload = {'chat_id': chat_id} payload = {'chat_id': chat_id}
files = None files = None
if not util.is_string(photo): if util.is_string(photo):
files = {'photo': photo}
else:
payload['photo'] = photo payload['photo'] = photo
elif util.is_pil_image(photo):
files = {'photo': util.pil_image_to_file(photo)}
else:
files = {'photo': photo}
if caption: if caption:
payload['caption'] = caption payload['caption'] = caption
if reply_to_message_id: if reply_to_message_id:
@ -743,10 +745,12 @@ def set_chat_photo(token, chat_id, photo):
method_url = 'setChatPhoto' method_url = 'setChatPhoto'
payload = {'chat_id': chat_id} payload = {'chat_id': chat_id}
files = None files = None
if not util.is_string(photo): if util.is_string(photo):
files = {'photo': photo}
else:
payload['photo'] = photo payload['photo'] = photo
elif util.is_pil_image(photo):
files = {'photo': util.pil_image_to_file(photo)}
else:
files = {'photo': photo}
return _make_request(token, method_url, params=payload, files=files, method='post') return _make_request(token, method_url, params=payload, files=files, method='post')

View File

@ -19,6 +19,13 @@ except ImportError:
import queue as Queue import queue as Queue
import logging import logging
try:
import PIL
from io import BytesIO
pil_imported = True
except:
pil_imported = False
logger = logging.getLogger('TeleBot') logger = logging.getLogger('TeleBot')
thread_local = threading.local() thread_local = threading.local()
@ -159,6 +166,19 @@ def async_dec():
def is_string(var): def is_string(var):
return isinstance(var, string_types) return isinstance(var, string_types)
def is_pil_image(var):
return pil_imported and isinstance(var, PIL.Image.Image)
def pil_image_to_file(image, extension='JPEG', quality='web_low'):
if pil_imported:
photoBuffer = BytesIO()
image.convert('RGB').save(photoBuffer, extension, quality=quality)
photoBuffer.seek(0)
return photoBuffer
else:
raise RuntimeError('PIL module is not imported')
def is_command(text): def is_command(text):
""" """
Checks if `text` is a command. Telegram chat commands start with the '/' character. Checks if `text` is a command. Telegram chat commands start with the '/' character.