def __init__(self, media, thumb=None, caption=None, parse_mode=DEFAULT_NONE, width=None, height=None, duration=None): self.type = 'animation' if isinstance(media, Animation): self.media = media.file_id self.width = media.width self.height = media.height self.duration = media.duration elif InputFile.is_file(media): self.media = InputFile(media, attach=True) else: self.media = media if thumb: self.thumb = thumb if InputFile.is_file(self.thumb): self.thumb = InputFile(self.thumb, attach=True) if caption: self.caption = caption self.parse_mode = parse_mode if width: self.width = width if height: self.height = height if duration: self.duration = duration
def __init__(self, media, caption=None, width=None, height=None, duration=None, supports_streaming=None, parse_mode=DEFAULT_NONE, thumb=None): self.type = 'video' if isinstance(media, Video): self.media = media.file_id self.width = media.width self.height = media.height self.duration = media.duration elif InputFile.is_file(media): self.media = InputFile(media, attach=True) else: self.media = media if thumb: self.thumb = thumb if InputFile.is_file(self.thumb): self.thumb = InputFile(self.thumb, attach=True) if caption: self.caption = caption self.parse_mode = parse_mode if width: self.width = width if height: self.height = height if duration: self.duration = duration if supports_streaming: self.supports_streaming = supports_streaming
def post(url, data, network_delay=2.): """Request an URL. Args: url: The web location we want to retrieve. data: A dict of (str, unicode) key/value pairs. network_delay: Additional timeout in seconds to allow the response from Telegram to take some time. Returns: A JSON object. """ # Add time to the timeout of urlopen to allow data to be transferred over # the network. if 'timeout' in data: timeout = data['timeout'] + network_delay else: timeout = None if InputFile.is_inputfile(data): data = InputFile(data) request = Request(url, data=data.to_form(), headers=data.headers) else: data = json.dumps(data) request = Request(url, data=data.encode(), headers={'Content-Type': 'application/json'}) result = urlopen(request, timeout=timeout).read() return _parse(result)
def post(self, url, data, timeout=None): """Request an URL. Args: url (:obj:`str`): The web location we want to retrieve. data (dict[str, str|int]): A dict of key/value pairs. Note: On py2.7 value is unicode. timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read timeout from the server (instead of the one specified during creation of the connection pool). Returns: A JSON object. """ urlopen_kwargs = {} if timeout is not None: urlopen_kwargs['timeout'] = Timeout(read=timeout, connect=self._connect_timeout) if InputFile.is_inputfile(data): data = InputFile(data) result = self._request_wrapper( 'POST', url, body=data.to_form(), headers=data.headers, **urlopen_kwargs) else: data = json.dumps(data) result = self._request_wrapper( 'POST', url, body=data.encode(), headers={'Content-Type': 'application/json'}, **urlopen_kwargs) return self._parse(result)
def post(url, data): """Request an URL. Args: url: The web location we want to retrieve. data: A dict of (str, unicode) key/value pairs. Returns: A JSON object. """ try: if InputFile.is_inputfile(data): data = InputFile(data) request = Request(url, data=data.to_form(), headers=data.headers) else: data = json.dumps(data) request = Request(url, data=data.encode(), headers={'Content-Type': 'application/json'}) result = urlopen(request).read() except HTTPError as error: if error.getcode() == 403: raise TelegramError('Unauthorized') message = _parse(error.read()) raise TelegramError(message) return _parse(result)
def post(url, data, timeout=None): """Request an URL. Args: url: The web location we want to retrieve. data: A dict of (str, unicode) key/value pairs. timeout: float. If this value is specified, use it as the definitive timeout (in seconds) for urlopen() operations. [Optional] Notes: If neither `timeout` nor `data['timeout']` is specified. The underlying defaults are used. Returns: A JSON object. """ urlopen_kwargs = {} if timeout is not None: urlopen_kwargs['timeout'] = timeout if InputFile.is_inputfile(data): data = InputFile(data) request = Request(url, data=data.to_form(), headers=data.headers) else: data = json.dumps(data) request = Request(url, data=data.encode(), headers={'Content-Type': 'application/json'}) result = urlopen(request, **urlopen_kwargs).read() return _parse(result)
def __init__(self, media, thumb=None, caption=None, parse_mode=DEFAULT_NONE, duration=None, performer=None, title=None): self.type = 'audio' if isinstance(media, Audio): self.media = media.file_id self.duration = media.duration self.performer = media.performer self.title = media.title elif InputFile.is_file(media): self.media = InputFile(media, attach=True) else: self.media = media if thumb: self.thumb = thumb if InputFile.is_file(self.thumb): self.thumb = InputFile(self.thumb, attach=True) if caption: self.caption = caption self.parse_mode = parse_mode if duration: self.duration = duration if performer: self.performer = performer if title: self.title = title
def send_illust_file(update: Update, context: CallbackContext): illust_id = get_illust_id(context.args[0]) if illust_id == -1: update.effective_message.reply_text("用法:/getfile *Pixiv ID 或链接*") return force_send_all = False try: arg1 = str(context.args[1]) except: pass else: if arg1 == "all": force_send_all = True try: illust = Illust(illust_id) except IllustInitError: return illust.download_original() images = illust.get_downloaded_images() if force_send_all or len( images) > 1 and update.effective_chat.type == "private": page = 0 for image in images: update.effective_message.reply_document(InputFile(BytesIO(image))) page = page + 1 else: update.effective_message.reply_document(InputFile(BytesIO(images[0]))) logger.info(f"成功发送 {illust.id} 原始文件")
def test_send_bytesio_jpg_file(self, bot, chat_id): file_name = 'tests/data/telegram_no_standard_header.jpg' # raw image bytes raw_bytes = BytesIO(open(file_name, 'rb').read()) input_file = InputFile(raw_bytes) assert input_file.mimetype == 'application/octet-stream' # raw image bytes with name info raw_bytes = BytesIO(open(file_name, 'rb').read()) raw_bytes.name = file_name input_file = InputFile(raw_bytes) assert input_file.mimetype == 'image/jpeg' # send raw photo raw_bytes = BytesIO(open(file_name, 'rb').read()) message = bot.send_photo(chat_id, photo=raw_bytes) photo = message.photo[-1] assert isinstance(photo.file_id, str) assert isinstance(photo.file_unique_id, str) assert photo.file_id != '' assert photo.file_unique_id != '' assert isinstance(photo, PhotoSize) assert photo.width == 1280 assert photo.height == 720 assert photo.file_size == 33372
def __init__( self, media: Union[str, FileLike, Document], thumb: FileLike = None, caption: str = None, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, ): self.type = 'document' if isinstance(media, Document): self.media: Union[str, InputFile] = media.file_id elif InputFile.is_file(media): media = cast(IO, media) self.media = InputFile(media, attach=True) else: self.media = media # type: ignore[assignment] if thumb: if InputFile.is_file(thumb): thumb = cast(IO, thumb) self.thumb = InputFile(thumb, attach=True) else: self.thumb = thumb # type: ignore[assignment] if caption: self.caption = caption self.parse_mode = parse_mode
def post(url, data, timeout=None): """Request an URL. Args: url: The web location we want to retrieve. data: A dict of (str, unicode) key/value pairs. timeout: float. If this value is specified, use it as the definitive timeout (in seconds) for urlopen() operations. [Optional] Notes: If neither `timeout` nor `data['timeout']` is specified. The underlying defaults are used. Returns: A JSON object. """ urlopen_kwargs = {} if timeout is not None: urlopen_kwargs['timeout'] = timeout if InputFile.is_inputfile(data): data = InputFile(data) result = _request_wrapper('POST', url, body=data.to_form(), headers=data.headers) else: data = json.dumps(data) result = _request_wrapper('POST', url, body=data.encode(), headers={'Content-Type': 'application/json'}) return _parse(result)
def post(url, data, network_delay=2.): """Request an URL. Args: url: The web location we want to retrieve. data: A dict of (str, unicode) key/value pairs. network_delay: Additional timeout in seconds to allow the response from Telegram to take some time. Returns: A JSON object. """ # Add time to the timeout of urlopen to allow data to be transferred over # the network. if 'timeout' in data: timeout = data['timeout'] + network_delay else: timeout = None try: if InputFile.is_inputfile(data): data = InputFile(data) request = Request(url, data=data.to_form(), headers=data.headers) else: data = json.dumps(data) request = Request(url, data=data.encode(), headers={'Content-Type': 'application/json'}) result = urlopen(request, timeout=timeout).read() except HTTPError as error: if error.getcode() == 403: raise TelegramError('Unauthorized') if error.getcode() == 502: raise TelegramError('Bad Gateway') try: message = _parse(error.read()) except ValueError: message = 'Unknown HTTPError' raise TelegramError(message) except (SSLError, socket.timeout) as error: if "operation timed out" in str(error): raise TelegramError("Timed out") raise TelegramError(str(error)) return _parse(result)
def test_mimetypes(self, caplog): # Only test a few to make sure logic works okay assert InputFile( data_file("telegram.jpg").open("rb")).mimetype == "image/jpeg" # For some reason python can guess the type on macOS assert InputFile(data_file("telegram.webp").open("rb")).mimetype in [ "application/octet-stream", "image/webp", ] assert InputFile( data_file("telegram.mp3").open("rb")).mimetype == "audio/mpeg" # For some reason windows drops the trailing i assert InputFile(data_file("telegram.midi").open("rb")).mimetype in [ "audio/mid", "audio/midi", ] # Test guess from file assert InputFile(BytesIO(b"blah"), filename="tg.jpg").mimetype == "image/jpeg" assert InputFile(BytesIO(b"blah"), filename="tg.mp3").mimetype == "audio/mpeg" # Test fallback assert (InputFile( BytesIO(b"blah"), filename="tg.notaproperext").mimetype == "application/octet-stream" ) assert InputFile( BytesIO(b"blah")).mimetype == "application/octet-stream" # Test string file assert InputFile( data_file("text_file.txt").open()).mimetype == "text/plain"
def test_slot_behaviour(self, recwarn, mro_slots): inst = InputFile(BytesIO(b'blah'), filename='tg.jpg') for attr in inst.__slots__: assert getattr(inst, attr, 'err') != 'err', f"got extra slot '{attr}'" assert not inst.__dict__, f"got missing slot(s): {inst.__dict__}" assert len(mro_slots(inst)) == len(set( mro_slots(inst))), "duplicate slot" inst.custom, inst.filename = 'should give warning', inst.filename assert len(recwarn) == 1 and 'custom' in str( recwarn[0].message), recwarn.list
def test_multiple_multipart_data(self): assert RequestParameter("name", "value", []).multipart_data is None input_file_1 = InputFile("data1", attach=True) input_file_2 = InputFile("data2", filename="custom") request_parameter = RequestParameter( value="value", name="name", input_files=[input_file_1, input_file_2]) files = request_parameter.multipart_data assert files[input_file_1.attach_name] == input_file_1.field_tuple assert files["name"] == input_file_2.field_tuple
def parse_file_input( file_input: Union[FileInput, "TelegramObject"], tg_type: Type["TelegramObject"] = None, filename: str = None, attach: bool = False, ) -> Union[str, "InputFile", Any]: """ Parses input for sending files: * For string input, if the input is an absolute path of a local file, adds the ``file://`` prefix. If the input is a relative path of a local file, computes the absolute path and adds the ``file://`` prefix. Returns the input unchanged, otherwise. * :class:`pathlib.Path` objects are treated the same way as strings. * For IO and bytes input, returns an :class:`telegram.InputFile`. * If :attr:`tg_type` is specified and the input is of that type, returns the ``file_id`` attribute. Args: file_input (:obj:`str` | :obj:`bytes` | :term:`file object` | Telegram media object): The input to parse. tg_type (:obj:`type`, optional): The Telegram media type the input can be. E.g. :class:`telegram.Animation`. filename (:obj:`str`, optional): The filename. Only relevant in case an :class:`telegram.InputFile` is returned. attach (:obj:`bool`, optional): Pass :obj:`True` if the parameter this file belongs to in the request to Telegram should point to the multipart data via an ``attach://`` URI. Defaults to `False`. Only relevant if an :class:`telegram.InputFile` is returned. Returns: :obj:`str` | :class:`telegram.InputFile` | :obj:`object`: The parsed input or the untouched :attr:`file_input`, in case it's no valid file input. """ # Importing on file-level yields cyclic Import Errors from telegram import InputFile # pylint: disable=import-outside-toplevel if isinstance(file_input, str) and file_input.startswith("file://"): return file_input if isinstance(file_input, (str, Path)): if is_local_file(file_input): out = Path(file_input).absolute().as_uri() else: out = file_input # type: ignore[assignment] return out if isinstance(file_input, bytes): return InputFile(file_input, filename=filename, attach=attach) if hasattr(file_input, "read"): return InputFile(cast(IO, file_input), filename=filename, attach=attach) if tg_type and isinstance(file_input, tg_type): return file_input.file_id # type: ignore[attr-defined] return file_input
def __init__(self, media, caption=None, parse_mode=DEFAULT_NONE): self.type = 'photo' if isinstance(media, PhotoSize): self.media = media.file_id elif InputFile.is_file(media): self.media = InputFile(media, attach=True) else: self.media = media if caption: self.caption = caption self.parse_mode = parse_mode
def parse_file_input( file_input: Union[FileInput, 'TelegramObject'], tg_type: Type['TelegramObject'] = None, attach: bool = None, filename: str = None, ) -> Union[str, 'InputFile', Any]: """ Parses input for sending files: * For string input, if the input is an absolute path of a local file, adds the ``file://`` prefix. If the input is a relative path of a local file, computes the absolute path and adds the ``file://`` prefix. Returns the input unchanged, otherwise. * :class:`pathlib.Path` objects are treated the same way as strings. * For IO and bytes input, returns an :class:`telegram.InputFile`. * If :attr:`tg_type` is specified and the input is of that type, returns the ``file_id`` attribute. Args: file_input (:obj:`str` | :obj:`bytes` | `filelike object` | Telegram media object): The input to parse. tg_type (:obj:`type`, optional): The Telegram media type the input can be. E.g. :class:`telegram.Animation`. attach (:obj:`bool`, optional): Whether this file should be send as one file or is part of a collection of files. Only relevant in case an :class:`telegram.InputFile` is returned. filename (:obj:`str`, optional): The filename. Only relevant in case an :class:`telegram.InputFile` is returned. Returns: :obj:`str` | :class:`telegram.InputFile` | :obj:`object`: The parsed input or the untouched :attr:`file_input`, in case it's no valid file input. """ # Importing on file-level yields cyclic Import Errors from telegram import InputFile # pylint: disable=C0415 if isinstance(file_input, str) and file_input.startswith('file://'): return file_input if isinstance(file_input, (str, Path)): if is_local_file(file_input): out = Path(file_input).absolute().as_uri() else: out = file_input # type: ignore[assignment] return out if isinstance(file_input, bytes): return InputFile(file_input, attach=attach, filename=filename) if InputFile.is_file(file_input): file_input = cast(IO, file_input) return InputFile(file_input, attach=attach, filename=filename) if tg_type and isinstance(file_input, tg_type): return file_input.file_id # type: ignore[attr-defined] return file_input
def _requestUrl(self, url, method, data=None): """Request an URL. Args: url: The web location we want to retrieve. method: Either POST or GET. data: A dict of (str, unicode) key/value pairs. Returns: A JSON object. """ if method not in ('POST', 'GET'): raise ValueError( "Method '%s' is neither 'POST' nor 'GET'" % method) if method == 'POST': try: if InputFile.is_inputfile(data): data = InputFile(data) request = Request( url, data=data.to_form(), headers=data.headers ) return urlopen(request).read() else: return urlopen( url, urlencode(data).encode() ).read() except IOError as e: raise TelegramError(str(e)) except HTTPError as e: raise TelegramError(str(e)) except URLError as e: raise TelegramError(str(e)) if method == 'GET': try: return urlopen(url).read() except URLError as e: raise TelegramError(str(e))
def test_mimetypes(self, caplog): # Only test a few to make sure logic works okay assert InputFile(open('tests/data/telegram.jpg', 'rb')).mimetype == 'image/jpeg' assert InputFile(open('tests/data/telegram.webp', 'rb')).mimetype == 'image/webp' assert InputFile(open('tests/data/telegram.mp3', 'rb')).mimetype == 'audio/mpeg' # Test guess from file assert InputFile(BytesIO(b'blah'), filename='tg.jpg').mimetype == 'image/jpeg' assert InputFile(BytesIO(b'blah'), filename='tg.mp3').mimetype == 'audio/mpeg' # Test fallback assert (InputFile( BytesIO(b'blah'), filename='tg.notaproperext').mimetype == 'application/octet-stream' ) assert InputFile( BytesIO(b'blah')).mimetype == 'application/octet-stream' # Test string file with caplog.at_level(logging.DEBUG): assert InputFile(open('tests/data/text_file.txt', 'r')).mimetype == 'text/plain' assert len(caplog.records) == 1 assert caplog.records[0].getMessage().startswith( 'Could not parse file content')
def _prepare_request_payload(data, png_sticker=None, tgs_sticker=None): if png_sticker is not None: if InputFile.is_file(png_sticker): png_sticker = InputFile(png_sticker) data['png_sticker'] = png_sticker if tgs_sticker is not None: if InputFile.is_file(tgs_sticker): tgs_sticker = InputFile(tgs_sticker) data['tgs_sticker'] = tgs_sticker return data
def slave_message_animation(self, msg: EFBMsg, tg_dest: TelegramChatID, msg_template: str, reactions: str, old_msg_id: OldMsgID = None, target_msg_id: Optional[TelegramMessageID] = None, reply_markup: Optional[telegram.ReplyMarkup] = None, silent: bool = None) -> telegram.Message: self.bot.send_chat_action(tg_dest, telegram.ChatAction.UPLOAD_PHOTO) self.logger.debug("[%s] Message is an Animation; Path: %s; MIME: %s", msg.uid, msg.path, msg.mime) if msg.path: self.logger.debug("[%s] Size of %s is %s.", msg.uid, msg.path, os.stat(msg.path).st_size) try: if old_msg_id: if msg.edit_media: self.bot.edit_message_media(chat_id=old_msg_id[0], message_id=old_msg_id[1], media=msg.file) return self.bot.edit_message_caption(chat_id=old_msg_id[0], message_id=old_msg_id[1], prefix=msg_template, suffix=reactions, caption=msg.text) else: return self.bot.send_animation(tg_dest, InputFile(msg.file, filename=msg.filename), prefix=msg_template, suffix=reactions, caption=msg.text, reply_to_message_id=target_msg_id, reply_markup=reply_markup, disable_notification=silent) finally: if msg.file: msg.file.close()
def test_slot_behaviour(self, mro_slots): inst = InputFile(BytesIO(b"blah"), filename="tg.jpg") for attr in inst.__slots__: assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set( mro_slots(inst))), "duplicate slot"
def test_from_input_inputfile(self): inputfile_1 = InputFile("data1", filename="inputfile_1", attach=True) inputfile_2 = InputFile("data2", filename="inputfile_2") request_parameter = RequestParameter.from_input("key", inputfile_1) assert request_parameter.value == inputfile_1.attach_uri assert request_parameter.input_files == [inputfile_1] request_parameter = RequestParameter.from_input("key", inputfile_2) assert request_parameter.value is None assert request_parameter.input_files == [inputfile_2] request_parameter = RequestParameter.from_input( "key", [inputfile_1, inputfile_2]) assert request_parameter.value == [inputfile_1.attach_uri] assert request_parameter.input_files == [inputfile_1, inputfile_2]
def _send_route_plot(self, update, route_id): user_id = update.effective_user.id query = update.callback_query if len(update.effective_message.photo) == 0: update.effective_user.send_chat_action('upload_photo') with self.traffic_scanner.storage.session_scope() as s: route = self.traffic_scanner.storage.get_route(user_id=user_id, route_id=route_id, s=s) if route is None: return report = self.traffic_scanner.storage.make_report(route, s) figure = self.traffic_plotter.plot_traffic_minmax( report.timestamps, report.durations, report.timezone, report.route.title) with io.BytesIO() as buf: figure.savefig(buf, format='png') buf.seek(0) keyboard = self._get_route_inline_markup(route_id) if len(update.effective_message.photo) == 0: plot_file = InputFile(buf) update.effective_message.reply_photo( plot_file, reply_markup=InlineKeyboardMarkup(keyboard)) else: plot_file = InputMediaPhoto(buf) query.edit_message_media(plot_file) query.edit_message_reply_markup( InlineKeyboardMarkup(keyboard)) plt.close(figure)
def _requestUrl(self, url, method, data=None): """Request an URL. Args: url: The web location we want to retrieve. method: Either POST or GET. data: A dict of (str, unicode) key/value pairs. Returns: A JSON object. """ if method == 'POST': try: if self._isFileRequest(data): data = InputFile(data) request = urllib2.Request( url, data=data.to_form(), headers=data.headers ) return urllib2.urlopen(request).read() else: return urllib2.urlopen( url, urllib.urlencode(data) ).read() except urllib.IOError as e: raise TelegramError(str(e)) except urllib2.URLError as e: raise TelegramError(str(e)) if method == 'GET': try: return urllib2.urlopen(url).read() except urllib2.URLError as e: raise TelegramError(str(e)) return 0 # if not a POST or GET request
def post(url, data): """Request an URL. Args: url: The web location we want to retrieve. data: A dict of (str, unicode) key/value pairs. Returns: A JSON object. """ # Add one second to the timeout of urlopen to allow data to be transferred # over the network. if 'timeout' in data: timeout = data['timeout'] + 1. else: timeout = None try: if InputFile.is_inputfile(data): data = InputFile(data) request = Request(url, data=data.to_form(), headers=data.headers) else: data = json.dumps(data) request = Request(url, data=data.encode(), headers={'Content-Type': 'application/json'}) result = urlopen(request, timeout=timeout).read() except HTTPError as error: if error.getcode() == 403: raise TelegramError('Unauthorized') if error.getcode() == 502: raise TelegramError('Bad Gateway') message = _parse(error.read()) raise TelegramError(message) except SSLError as error: if "The read operation timed out" == error.message: raise TelegramError("Timed out") raise TelegramError(error.message) return _parse(result)
def post(url, data, timeout=None, network_delay=2.): """Request an URL. Args: url: The web location we want to retrieve. data: A dict of (str, unicode) key/value pairs. timeout: float. If this value is specified, use it as the definitive timeout (in seconds) for urlopen() operations. [Optional] network_delay: float. If using the timeout specified in `data` (which is a timeout for the Telegram servers operation), then `network_delay` as an extra delay (in seconds) to compensate for network latency. default: 2 [Optional] Notes: If neither `timeout` nor `data['timeout']` is specified. The underlying defaults are used. Returns: A JSON object. """ urlopen_kwargs = {} if timeout is not None: urlopen_kwargs['timeout'] = timeout elif 'timeout' in data: urlopen_kwargs['timeout'] = data['timeout'] + network_delay if InputFile.is_inputfile(data): data = InputFile(data) request = Request(url, data=data.to_form(), headers=data.headers) else: data = json.dumps(data) request = Request(url, data=data.encode(), headers={'Content-Type': 'application/json'}) result = urlopen(request, **urlopen_kwargs).read() return _parse(result)
def __init__(self, media: Union[str, FileLike, PhotoSize], caption: str = None, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE): self.type = 'photo' if isinstance(media, PhotoSize): self.media: Union[str, InputFile] = media.file_id elif InputFile.is_file(media): media = cast(IO, media) self.media = InputFile(media, attach=True) else: self.media = media # type: ignore[assignment] if caption: self.caption = caption self.parse_mode = parse_mode
def test_attach(self, attach): input_file = InputFile("contents", attach=attach) if attach: assert isinstance(input_file.attach_name, str) assert input_file.attach_uri == f"attach://{input_file.attach_name}" else: assert input_file.attach_name is None assert input_file.attach_uri is None
def __init__(self, media, thumb=None, caption=None, parse_mode=DEFAULT_NONE): self.type = 'document' if isinstance(media, Document): self.media = media.file_id elif InputFile.is_file(media): self.media = InputFile(media, attach=True) else: self.media = media if thumb: self.thumb = thumb if InputFile.is_file(self.thumb): self.thumb = InputFile(self.thumb, attach=True) if caption: self.caption = caption self.parse_mode = parse_mode
def input_file(self): """returns a telegram InputFile""" extension = '.webp' if self._animated: extension = '.tgs' self._downloaded_tempfile.seek(0) return InputFile(self._downloaded_tempfile, filename=self._sticker.file_id + extension)
def _requestUrl(self, url, method, data=None): """Request an URL. Args: url: The web location we want to retrieve. method: Either POST or GET. data: A dict of (str, unicode) key/value pairs. Returns: A JSON object. """ if method == "POST": if ( "audio" in data and is_file(data["audio"]) or "document" in data and is_file(data["document"]) or "photo" in data and is_file(data["photo"]) or "video" in data and is_file(data["video"]) ): try: data = InputFile(data) request = urllib.request(url, data=data.to_form(), headers=data.headers) return urllib.request.urlopen(request).read() except urllib.error.URLError as e: raise TelegramError(str(e)) else: try: return urllib.request.urlopen(url, urllib.parse.urlencode(data).encode()).read() except urllib.error.URLError as e: raise TelegramError(str(e)) if method == "GET": try: return urllib.request.urlopen(url).read() except urllib.error.URLError as e: raise TelegramError(str(e)) return 0
def send_img( bot_key=_TELEGRAM_CONFIG.get("bot_key"), chat_id=_TELEGRAM_CONFIG.get("chat_id"), img_path=None, img_binary=None, caption="", ): assert img_path or img_binary try: img_data = ( InputFile(img_binary) if img_binary else InputFile(open(img_path, "rb")) ) result = Bot(token=bot_key).send_photo( chat_id=chat_id, photo=img_data, caption=caption ) return True, result except: logging.error(traceback.format_exc()) return False, traceback.format_exc()
def __init__( self, media: Union[str, FileLike, Video], caption: str = None, width: int = None, height: int = None, duration: int = None, supports_streaming: bool = None, parse_mode: Union[str, DefaultValue] = DEFAULT_NONE, thumb: FileLike = None, ): self.type = 'video' if isinstance(media, Video): self.media: Union[str, InputFile] = media.file_id self.width = media.width self.height = media.height self.duration = media.duration elif InputFile.is_file(media): media = cast(IO, media) self.media = InputFile(media, attach=True) else: self.media = media # type: ignore[assignment] if thumb: if InputFile.is_file(thumb): thumb = cast(IO, thumb) self.thumb = InputFile(thumb, attach=True) else: self.thumb = thumb # type: ignore[assignment] if caption: self.caption = caption self.parse_mode = parse_mode if width: self.width = width if height: self.height = height if duration: self.duration = duration if supports_streaming: self.supports_streaming = supports_streaming