repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
delph-in/pydelphin
delphin/repp.py
REPP.from_config
def from_config(cls, path, directory=None): """ Instantiate a REPP from a PET-style `.set` configuration file. The *path* parameter points to the configuration file. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. Args: path (str): the path to the REPP configuration file directory (str, optional): the directory in which to search for submodules """ if not exists(path): raise REPPError('REPP config file not found: {}'.format(path)) confdir = dirname(path) # TODO: can TDL parsing be repurposed for this variant? conf = io.open(path, encoding='utf-8').read() conf = re.sub(r';.*', '', conf).replace('\n',' ') m = re.search( r'repp-modules\s*:=\s*((?:[-\w]+\s+)*[-\w]+)\s*\.', conf) t = re.search( r'repp-tokenizer\s*:=\s*([-\w]+)\s*\.', conf) a = re.search( r'repp-calls\s*:=\s*((?:[-\w]+\s+)*[-\w]+)\s*\.', conf) f = re.search( r'format\s*:=\s*(\w+)\s*\.', conf) d = re.search( r'repp-directory\s*:=\s*(.*)\.\s*$', conf) if m is None: raise REPPError('repp-modules option must be set') if t is None: raise REPPError('repp-tokenizer option must be set') mods = m.group(1).split() tok = t.group(1).strip() active = a.group(1).split() if a is not None else None fmt = f.group(1).strip() if f is not None else None if directory is None: if d is not None: directory = d.group(1).strip(' "') elif exists(joinpath(confdir, tok + '.rpp')): directory = confdir elif exists(joinpath(confdir, 'rpp', tok + '.rpp')): directory = joinpath(confdir, 'rpp') elif exists(joinpath(confdir, '../rpp', tok + '.rpp')): directory = joinpath(confdir, '../rpp') else: raise REPPError('Could not find a suitable REPP directory.') # ignore repp-modules and format? return REPP.from_file( joinpath(directory, tok + '.rpp'), directory=directory, active=active )
python
def from_config(cls, path, directory=None): """ Instantiate a REPP from a PET-style `.set` configuration file. The *path* parameter points to the configuration file. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. Args: path (str): the path to the REPP configuration file directory (str, optional): the directory in which to search for submodules """ if not exists(path): raise REPPError('REPP config file not found: {}'.format(path)) confdir = dirname(path) # TODO: can TDL parsing be repurposed for this variant? conf = io.open(path, encoding='utf-8').read() conf = re.sub(r';.*', '', conf).replace('\n',' ') m = re.search( r'repp-modules\s*:=\s*((?:[-\w]+\s+)*[-\w]+)\s*\.', conf) t = re.search( r'repp-tokenizer\s*:=\s*([-\w]+)\s*\.', conf) a = re.search( r'repp-calls\s*:=\s*((?:[-\w]+\s+)*[-\w]+)\s*\.', conf) f = re.search( r'format\s*:=\s*(\w+)\s*\.', conf) d = re.search( r'repp-directory\s*:=\s*(.*)\.\s*$', conf) if m is None: raise REPPError('repp-modules option must be set') if t is None: raise REPPError('repp-tokenizer option must be set') mods = m.group(1).split() tok = t.group(1).strip() active = a.group(1).split() if a is not None else None fmt = f.group(1).strip() if f is not None else None if directory is None: if d is not None: directory = d.group(1).strip(' "') elif exists(joinpath(confdir, tok + '.rpp')): directory = confdir elif exists(joinpath(confdir, 'rpp', tok + '.rpp')): directory = joinpath(confdir, 'rpp') elif exists(joinpath(confdir, '../rpp', tok + '.rpp')): directory = joinpath(confdir, '../rpp') else: raise REPPError('Could not find a suitable REPP directory.') # ignore repp-modules and format? return REPP.from_file( joinpath(directory, tok + '.rpp'), directory=directory, active=active )
Instantiate a REPP from a PET-style `.set` configuration file. The *path* parameter points to the configuration file. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. Args: path (str): the path to the REPP configuration file directory (str, optional): the directory in which to search for submodules
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/repp.py#L282-L340
delph-in/pydelphin
delphin/repp.py
REPP.from_file
def from_file(cls, path, directory=None, modules=None, active=None): """ Instantiate a REPP from a `.rpp` file. The *path* parameter points to the top-level module. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. A REPP module may utilize external submodules, which may be defined in two ways. The first method is to map a module name to an instantiated REPP instance in *modules*. The second method assumes that an external group call `>abc` corresponds to a file `abc.rpp` in *directory* and loads that file. The second method only happens if the name (e.g., `abc`) does not appear in *modules*. Only one module may define a tokenization pattern. Args: path (str): the path to the base REPP file to load directory (str, optional): the directory in which to search for submodules modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations """ name = basename(path) if name.endswith('.rpp'): name = name[:-4] lines = _repp_lines(path) directory = dirname(path) if directory is None else directory r = cls(name=name, modules=modules, active=active) _parse_repp(lines, r, directory) return r
python
def from_file(cls, path, directory=None, modules=None, active=None): """ Instantiate a REPP from a `.rpp` file. The *path* parameter points to the top-level module. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. A REPP module may utilize external submodules, which may be defined in two ways. The first method is to map a module name to an instantiated REPP instance in *modules*. The second method assumes that an external group call `>abc` corresponds to a file `abc.rpp` in *directory* and loads that file. The second method only happens if the name (e.g., `abc`) does not appear in *modules*. Only one module may define a tokenization pattern. Args: path (str): the path to the base REPP file to load directory (str, optional): the directory in which to search for submodules modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations """ name = basename(path) if name.endswith('.rpp'): name = name[:-4] lines = _repp_lines(path) directory = dirname(path) if directory is None else directory r = cls(name=name, modules=modules, active=active) _parse_repp(lines, r, directory) return r
Instantiate a REPP from a `.rpp` file. The *path* parameter points to the top-level module. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. A REPP module may utilize external submodules, which may be defined in two ways. The first method is to map a module name to an instantiated REPP instance in *modules*. The second method assumes that an external group call `>abc` corresponds to a file `abc.rpp` in *directory* and loads that file. The second method only happens if the name (e.g., `abc`) does not appear in *modules*. Only one module may define a tokenization pattern. Args: path (str): the path to the base REPP file to load directory (str, optional): the directory in which to search for submodules modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/repp.py#L343-L376
delph-in/pydelphin
delphin/repp.py
REPP.from_string
def from_string(cls, s, name=None, modules=None, active=None): """ Instantiate a REPP from a string. Args: name (str, optional): the name of the REPP module modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations """ r = cls(name=name, modules=modules, active=active) _parse_repp(s.splitlines(), r, None) return r
python
def from_string(cls, s, name=None, modules=None, active=None): """ Instantiate a REPP from a string. Args: name (str, optional): the name of the REPP module modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations """ r = cls(name=name, modules=modules, active=active) _parse_repp(s.splitlines(), r, None) return r
Instantiate a REPP from a string. Args: name (str, optional): the name of the REPP module modules (dict, optional): a mapping from identifiers to REPP modules active (iterable, optional): an iterable of default module activations
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/repp.py#L379-L392
delph-in/pydelphin
delphin/repp.py
REPP.deactivate
def deactivate(self, mod): """ Set external module *mod* to inactive. """ if mod in self.active: self.active.remove(mod)
python
def deactivate(self, mod): """ Set external module *mod* to inactive. """ if mod in self.active: self.active.remove(mod)
Set external module *mod* to inactive.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/repp.py#L400-L405
delph-in/pydelphin
delphin/repp.py
REPP.apply
def apply(self, s, active=None): """ Apply the REPP's rewrite rules to the input string *s*. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called Returns: a :class:`REPPResult` object containing the processed string and characterization maps """ if active is None: active = self.active return self.group.apply(s, active=active)
python
def apply(self, s, active=None): """ Apply the REPP's rewrite rules to the input string *s*. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called Returns: a :class:`REPPResult` object containing the processed string and characterization maps """ if active is None: active = self.active return self.group.apply(s, active=active)
Apply the REPP's rewrite rules to the input string *s*. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called Returns: a :class:`REPPResult` object containing the processed string and characterization maps
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/repp.py#L410-L424
delph-in/pydelphin
delphin/repp.py
REPP.trace
def trace(self, s, active=None, verbose=False): """ Rewrite string *s* like `apply()`, but yield each rewrite step. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called verbose (bool, optional): if `False`, only output rules or groups that matched the input Yields: a :class:`REPPStep` object for each intermediate rewrite step, and finally a :class:`REPPResult` object after the last rewrite """ if active is None: active = self.active return self.group.trace(s, active=active, verbose=verbose)
python
def trace(self, s, active=None, verbose=False): """ Rewrite string *s* like `apply()`, but yield each rewrite step. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called verbose (bool, optional): if `False`, only output rules or groups that matched the input Yields: a :class:`REPPStep` object for each intermediate rewrite step, and finally a :class:`REPPResult` object after the last rewrite """ if active is None: active = self.active return self.group.trace(s, active=active, verbose=verbose)
Rewrite string *s* like `apply()`, but yield each rewrite step. Args: s (str): the input string to process active (optional): a collection of external module names that may be applied if called verbose (bool, optional): if `False`, only output rules or groups that matched the input Yields: a :class:`REPPStep` object for each intermediate rewrite step, and finally a :class:`REPPResult` object after the last rewrite
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/repp.py#L426-L443
delph-in/pydelphin
delphin/repp.py
REPP.tokenize
def tokenize(self, s, pattern=None, active=None): """ Rewrite and tokenize the input string *s*. Args: s (str): the input string to process pattern (str, optional): the regular expression pattern on which to split tokens; defaults to `[ \t]+` active (optional): a collection of external module names that may be applied if called Returns: a :class:`~delphin.tokens.YyTokenLattice` containing the tokens and their characterization information """ if pattern is None: if self.tokenize_pattern is None: pattern = r'[ \t]+' else: pattern = self.tokenize_pattern if active is None: active = self.active return self.group.tokenize(s, pattern=pattern, active=active)
python
def tokenize(self, s, pattern=None, active=None): """ Rewrite and tokenize the input string *s*. Args: s (str): the input string to process pattern (str, optional): the regular expression pattern on which to split tokens; defaults to `[ \t]+` active (optional): a collection of external module names that may be applied if called Returns: a :class:`~delphin.tokens.YyTokenLattice` containing the tokens and their characterization information """ if pattern is None: if self.tokenize_pattern is None: pattern = r'[ \t]+' else: pattern = self.tokenize_pattern if active is None: active = self.active return self.group.tokenize(s, pattern=pattern, active=active)
Rewrite and tokenize the input string *s*. Args: s (str): the input string to process pattern (str, optional): the regular expression pattern on which to split tokens; defaults to `[ \t]+` active (optional): a collection of external module names that may be applied if called Returns: a :class:`~delphin.tokens.YyTokenLattice` containing the tokens and their characterization information
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/repp.py#L445-L466
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
SendableMessageBase._apply_update_receiver
def _apply_update_receiver(self, receiver, reply_id): """ Updates `self.receiver` and/or `self.reply_id` if they still contain the default value. :param receiver: The receiver `chat_id` to use. Either `self.receiver`, if set, e.g. when instancing `TextMessage(receiver=10001231231, ...)`, or the `chat.id` of the update context, being the id of groups or the user's `from_peer.id` in private messages. :type receiver: None | str|unicode | int :param reply_id: Reply to that `message_id` in the chat we send to. Either `self.reply_id`, if set, e.g. when instancing `TextMessage(reply_id=123123, ...)`, or the `message_id` of the update which triggered the bot's functions. :type reply_id: DEFAULT_MESSAGE_ID | int """ if self.receiver is None: self.receiver = receiver # end if if self.reply_id is DEFAULT_MESSAGE_ID: self.reply_id = reply_id
python
def _apply_update_receiver(self, receiver, reply_id): """ Updates `self.receiver` and/or `self.reply_id` if they still contain the default value. :param receiver: The receiver `chat_id` to use. Either `self.receiver`, if set, e.g. when instancing `TextMessage(receiver=10001231231, ...)`, or the `chat.id` of the update context, being the id of groups or the user's `from_peer.id` in private messages. :type receiver: None | str|unicode | int :param reply_id: Reply to that `message_id` in the chat we send to. Either `self.reply_id`, if set, e.g. when instancing `TextMessage(reply_id=123123, ...)`, or the `message_id` of the update which triggered the bot's functions. :type reply_id: DEFAULT_MESSAGE_ID | int """ if self.receiver is None: self.receiver = receiver # end if if self.reply_id is DEFAULT_MESSAGE_ID: self.reply_id = reply_id
Updates `self.receiver` and/or `self.reply_id` if they still contain the default value. :param receiver: The receiver `chat_id` to use. Either `self.receiver`, if set, e.g. when instancing `TextMessage(receiver=10001231231, ...)`, or the `chat.id` of the update context, being the id of groups or the user's `from_peer.id` in private messages. :type receiver: None | str|unicode | int :param reply_id: Reply to that `message_id` in the chat we send to. Either `self.reply_id`, if set, e.g. when instancing `TextMessage(reply_id=123123, ...)`, or the `message_id` of the update which triggered the bot's functions. :type reply_id: DEFAULT_MESSAGE_ID | int
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L14-L32
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
TextMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_message( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id text=self.text, chat_id=self.receiver, reply_to_message_id=self.reply_id, parse_mode=self.parse_mode, disable_web_page_preview=self.disable_web_page_preview, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_message( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id text=self.text, chat_id=self.receiver, reply_to_message_id=self.reply_id, parse_mode=self.parse_mode, disable_web_page_preview=self.disable_web_page_preview, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L140-L152
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
TextMessage.to_array
def to_array(self): """ Serializes this TextMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(TextMessage, self).to_array() array['text'] = u(self.text) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_web_page_preview is not None: array['disable_web_page_preview'] = bool(self.disable_web_page_preview) # type bool if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
def to_array(self): """ Serializes this TextMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(TextMessage, self).to_array() array['text'] = u(self.text) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_web_page_preview is not None: array['disable_web_page_preview'] = bool(self.disable_web_page_preview) # type bool if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
Serializes this TextMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L155-L201
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
PhotoMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_photo( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id photo=self.photo, chat_id=self.receiver, reply_to_message_id=self.reply_id, caption=self.caption, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_photo( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id photo=self.photo, chat_id=self.receiver, reply_to_message_id=self.reply_id, caption=self.caption, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L385-L397
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
AudioMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_audio( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id audio=self.audio, chat_id=self.receiver, reply_to_message_id=self.reply_id, caption=self.caption, parse_mode=self.parse_mode, duration=self.duration, performer=self.performer, title=self.title, thumb=self.thumb, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_audio( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id audio=self.audio, chat_id=self.receiver, reply_to_message_id=self.reply_id, caption=self.caption, parse_mode=self.parse_mode, duration=self.duration, performer=self.performer, title=self.title, thumb=self.thumb, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L682-L694
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
AudioMessage.to_array
def to_array(self): """ Serializes this AudioMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(AudioMessage, self).to_array() if isinstance(self.audio, InputFile): array['audio'] = self.audio.to_array() # type InputFile elif isinstance(self.audio, str): array['audio'] = u(self.audio) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.duration is not None: array['duration'] = int(self.duration) # type int if self.performer is not None: array['performer'] = u(self.performer) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
def to_array(self): """ Serializes this AudioMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(AudioMessage, self).to_array() if isinstance(self.audio, InputFile): array['audio'] = self.audio.to_array() # type InputFile elif isinstance(self.audio, str): array['audio'] = u(self.audio) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.duration is not None: array['duration'] = int(self.duration) # type int if self.performer is not None: array['performer'] = u(self.performer) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
Serializes this AudioMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L697-L767
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
DocumentMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_document( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id document=self.document, chat_id=self.receiver, reply_to_message_id=self.reply_id, thumb=self.thumb, caption=self.caption, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_document( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id document=self.document, chat_id=self.receiver, reply_to_message_id=self.reply_id, thumb=self.thumb, caption=self.caption, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L979-L991
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
VideoMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_video( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id video=self.video, chat_id=self.receiver, reply_to_message_id=self.reply_id, duration=self.duration, width=self.width, height=self.height, thumb=self.thumb, caption=self.caption, parse_mode=self.parse_mode, supports_streaming=self.supports_streaming, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_video( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id video=self.video, chat_id=self.receiver, reply_to_message_id=self.reply_id, duration=self.duration, width=self.width, height=self.height, thumb=self.thumb, caption=self.caption, parse_mode=self.parse_mode, supports_streaming=self.supports_streaming, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L1301-L1313
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
AnimationMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_animation( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id animation=self.animation, chat_id=self.receiver, reply_to_message_id=self.reply_id, duration=self.duration, width=self.width, height=self.height, thumb=self.thumb, caption=self.caption, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_animation( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id animation=self.animation, chat_id=self.receiver, reply_to_message_id=self.reply_id, duration=self.duration, width=self.width, height=self.height, thumb=self.thumb, caption=self.caption, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L1626-L1638
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
AnimationMessage.to_array
def to_array(self): """ Serializes this AnimationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(AnimationMessage, self).to_array() if isinstance(self.animation, InputFile): array['animation'] = self.animation.to_array() # type InputFile elif isinstance(self.animation, str): array['animation'] = u(self.animation) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.duration is not None: array['duration'] = int(self.duration) # type int if self.width is not None: array['width'] = int(self.width) # type int if self.height is not None: array['height'] = int(self.height) # type int if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
def to_array(self): """ Serializes this AnimationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(AnimationMessage, self).to_array() if isinstance(self.animation, InputFile): array['animation'] = self.animation.to_array() # type InputFile elif isinstance(self.animation, str): array['animation'] = u(self.animation) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.duration is not None: array['duration'] = int(self.duration) # type int if self.width is not None: array['width'] = int(self.width) # type int if self.height is not None: array['height'] = int(self.height) # type int if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
Serializes this AnimationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L1641-L1709
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
VoiceMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_voice( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id voice=self.voice, chat_id=self.receiver, reply_to_message_id=self.reply_id, caption=self.caption, parse_mode=self.parse_mode, duration=self.duration, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_voice( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id voice=self.voice, chat_id=self.receiver, reply_to_message_id=self.reply_id, caption=self.caption, parse_mode=self.parse_mode, duration=self.duration, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L1921-L1933
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
VoiceMessage.to_array
def to_array(self): """ Serializes this VoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VoiceMessage, self).to_array() if isinstance(self.voice, InputFile): array['voice'] = self.voice.to_array() # type InputFile elif isinstance(self.voice, str): array['voice'] = u(self.voice) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.duration is not None: array['duration'] = int(self.duration) # type int if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
def to_array(self): """ Serializes this VoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VoiceMessage, self).to_array() if isinstance(self.voice, InputFile): array['voice'] = self.voice.to_array() # type InputFile elif isinstance(self.voice, str): array['voice'] = u(self.voice) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.duration is not None: array['duration'] = int(self.duration) # type int if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
Serializes this VoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L1936-L1991
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
VideoNoteMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_video_note( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id video_note=self.video_note, chat_id=self.receiver, reply_to_message_id=self.reply_id, duration=self.duration, length=self.length, thumb=self.thumb, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_video_note( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id video_note=self.video_note, chat_id=self.receiver, reply_to_message_id=self.reply_id, duration=self.duration, length=self.length, thumb=self.thumb, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L2192-L2204
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
VideoNoteMessage.to_array
def to_array(self): """ Serializes this VideoNoteMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VideoNoteMessage, self).to_array() if isinstance(self.video_note, InputFile): array['video_note'] = self.video_note.to_array() # type InputFile elif isinstance(self.video_note, str): array['video_note'] = u(self.video_note) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.duration is not None: array['duration'] = int(self.duration) # type int if self.length is not None: array['length'] = int(self.length) # type int if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
def to_array(self): """ Serializes this VideoNoteMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VideoNoteMessage, self).to_array() if isinstance(self.video_note, InputFile): array['video_note'] = self.video_note.to_array() # type InputFile elif isinstance(self.video_note, str): array['video_note'] = u(self.video_note) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.duration is not None: array['duration'] = int(self.duration) # type int if self.length is not None: array['length'] = int(self.length) # type int if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
Serializes this VideoNoteMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L2207-L2267
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
MediaGroupMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_media_group( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id media=self.media, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_media_group( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id media=self.media, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L2437-L2449
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
MediaGroupMessage.to_array
def to_array(self): """ Serializes this MediaGroupMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(MediaGroupMessage, self).to_array() if isinstance(self.media, InputMediaPhoto): array['media'] = self._as_array(self.media) # type list of InputMediaPhoto | list of InputMediaVideo elif isinstance(self.media, InputMediaVideo): array['media'] = self._as_array(self.media) # type list of InputMediaPhoto | list of InputMediaVideo else: raise TypeError('Unknown type, must be one of InputMediaPhoto, InputMediaVideo.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool return array
python
def to_array(self): """ Serializes this MediaGroupMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(MediaGroupMessage, self).to_array() if isinstance(self.media, InputMediaPhoto): array['media'] = self._as_array(self.media) # type list of InputMediaPhoto | list of InputMediaVideo elif isinstance(self.media, InputMediaVideo): array['media'] = self._as_array(self.media) # type list of InputMediaPhoto | list of InputMediaVideo else: raise TypeError('Unknown type, must be one of InputMediaPhoto, InputMediaVideo.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool return array
Serializes this MediaGroupMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L2452-L2486
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
MediaGroupMessage.from_array
def from_array(array): """ Deserialize a new MediaGroupMessage from a given dictionary. :return: new MediaGroupMessage instance. :rtype: MediaGroupMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.input_media import InputMediaPhoto from pytgbot.api_types.sendable.input_media import InputMediaVideo data = {} if isinstance(array.get('media'), InputMediaPhoto): data['media'] = InputMediaPhoto.from_array_list(array.get('media'), list_level=1) elif isinstance(array.get('media'), InputMediaVideo): data['media'] = InputMediaVideo.from_array_list(array.get('media'), list_level=1) else: raise TypeError('Unknown type, must be one of InputMediaPhoto, InputMediaVideo.') # end if if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None return MediaGroupMessage(**data)
python
def from_array(array): """ Deserialize a new MediaGroupMessage from a given dictionary. :return: new MediaGroupMessage instance. :rtype: MediaGroupMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.input_media import InputMediaPhoto from pytgbot.api_types.sendable.input_media import InputMediaVideo data = {} if isinstance(array.get('media'), InputMediaPhoto): data['media'] = InputMediaPhoto.from_array_list(array.get('media'), list_level=1) elif isinstance(array.get('media'), InputMediaVideo): data['media'] = InputMediaVideo.from_array_list(array.get('media'), list_level=1) else: raise TypeError('Unknown type, must be one of InputMediaPhoto, InputMediaVideo.') # end if if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None return MediaGroupMessage(**data)
Deserialize a new MediaGroupMessage from a given dictionary. :return: new MediaGroupMessage instance. :rtype: MediaGroupMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L2490-L2534
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
LocationMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_location( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id latitude=self.latitude, longitude=self.longitude, chat_id=self.receiver, reply_to_message_id=self.reply_id, live_period=self.live_period, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_location( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id latitude=self.latitude, longitude=self.longitude, chat_id=self.receiver, reply_to_message_id=self.reply_id, live_period=self.live_period, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L2658-L2670
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
LocationMessage.to_array
def to_array(self): """ Serializes this LocationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(LocationMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.live_period is not None: array['live_period'] = int(self.live_period) # type int if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
def to_array(self): """ Serializes this LocationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(LocationMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.live_period is not None: array['live_period'] = int(self.live_period) # type int if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
Serializes this LocationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L2673-L2716
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
VenueMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_venue( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id latitude=self.latitude, longitude=self.longitude, title=self.title, address=self.address, chat_id=self.receiver, reply_to_message_id=self.reply_id, foursquare_id=self.foursquare_id, foursquare_type=self.foursquare_type, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_venue( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id latitude=self.latitude, longitude=self.longitude, title=self.title, address=self.address, chat_id=self.receiver, reply_to_message_id=self.reply_id, foursquare_id=self.foursquare_id, foursquare_type=self.foursquare_type, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L2926-L2938
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
VenueMessage.to_array
def to_array(self): """ Serializes this VenueMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VenueMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str array['address'] = u(self.address) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.foursquare_id is not None: array['foursquare_id'] = u(self.foursquare_id) # py2: type unicode, py3: type str if self.foursquare_type is not None: array['foursquare_type'] = u(self.foursquare_type) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
def to_array(self): """ Serializes this VenueMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VenueMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str array['address'] = u(self.address) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.foursquare_id is not None: array['foursquare_id'] = u(self.foursquare_id) # py2: type unicode, py3: type str if self.foursquare_type is not None: array['foursquare_type'] = u(self.foursquare_type) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
Serializes this VenueMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L2941-L2992
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
ContactMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_contact( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id phone_number=self.phone_number, first_name=self.first_name, chat_id=self.receiver, reply_to_message_id=self.reply_id, last_name=self.last_name, vcard=self.vcard, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_contact( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id phone_number=self.phone_number, first_name=self.first_name, chat_id=self.receiver, reply_to_message_id=self.reply_id, last_name=self.last_name, vcard=self.vcard, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L3187-L3199
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
ContactMessage.to_array
def to_array(self): """ Serializes this ContactMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ContactMessage, self).to_array() array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.vcard is not None: array['vcard'] = u(self.vcard) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
def to_array(self): """ Serializes this ContactMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ContactMessage, self).to_array() array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.vcard is not None: array['vcard'] = u(self.vcard) # py2: type unicode, py3: type str if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
Serializes this ContactMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L3202-L3251
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
ChatActionMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_chat_action( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id action=self.action, chat_id=self.receiver )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_chat_action( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id action=self.action, chat_id=self.receiver )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L3393-L3405
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
ChatActionMessage.to_array
def to_array(self): """ Serializes this ChatActionMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ChatActionMessage, self).to_array() array['action'] = u(self.action) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if return array
python
def to_array(self): """ Serializes this ChatActionMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ChatActionMessage, self).to_array() array['action'] = u(self.action) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if return array
Serializes this ChatActionMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L3408-L3427
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
ChatActionMessage.from_array
def from_array(array): """ Deserialize a new ChatActionMessage from a given dictionary. :return: new ChatActionMessage instance. :rtype: ChatActionMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['action'] = u(array.get('action')) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if return ChatActionMessage(**data)
python
def from_array(array): """ Deserialize a new ChatActionMessage from a given dictionary. :return: new ChatActionMessage instance. :rtype: ChatActionMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['action'] = u(array.get('action')) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if return ChatActionMessage(**data)
Deserialize a new ChatActionMessage from a given dictionary. :return: new ChatActionMessage instance. :rtype: ChatActionMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L3431-L3456
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
StickerMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_sticker( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id sticker=self.sticker, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_sticker( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id sticker=self.sticker, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L3563-L3575
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
StickerMessage.to_array
def to_array(self): """ Serializes this StickerMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(StickerMessage, self).to_array() if isinstance(self.sticker, InputFile): array['sticker'] = self.sticker.to_array() # type InputFile elif isinstance(self.sticker, str): array['sticker'] = u(self.sticker) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
python
def to_array(self): """ Serializes this StickerMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(StickerMessage, self).to_array() if isinstance(self.sticker, InputFile): array['sticker'] = self.sticker.to_array() # type InputFile elif isinstance(self.sticker, str): array['sticker'] = u(self.sticker) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: if isinstance(self.reply_markup, InlineKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardMarkup): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardMarkup elif isinstance(self.reply_markup, ReplyKeyboardRemove): array['reply_markup'] = self.reply_markup.to_array() # type ReplyKeyboardRemove elif isinstance(self.reply_markup, ForceReply): array['reply_markup'] = self.reply_markup.to_array() # type ForceReply else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply.') # end if return array
Serializes this StickerMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L3578-L3625
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
StickerMessage.from_array
def from_array(array): """ Deserialize a new StickerMessage from a given dictionary. :return: new StickerMessage instance. :rtype: StickerMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.files import InputFile from pytgbot.api_types.sendable.reply_markup import ForceReply from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardRemove data = {} if isinstance(array.get('sticker'), InputFile): data['sticker'] = InputFile.from_array(array.get('sticker')) elif isinstance(array.get('sticker'), str): data['sticker'] = u(array.get('sticker')) else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None if array.get('reply_markup') is None: data['reply_markup'] = None elif isinstance(array.get('reply_markup'), InlineKeyboardMarkup): data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) elif isinstance(array.get('reply_markup'), ReplyKeyboardMarkup): data['reply_markup'] = ReplyKeyboardMarkup.from_array(array.get('reply_markup')) elif isinstance(array.get('reply_markup'), ReplyKeyboardRemove): data['reply_markup'] = ReplyKeyboardRemove.from_array(array.get('reply_markup')) elif isinstance(array.get('reply_markup'), ForceReply): data['reply_markup'] = ForceReply.from_array(array.get('reply_markup')) else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply or None.') # end if return StickerMessage(**data)
python
def from_array(array): """ Deserialize a new StickerMessage from a given dictionary. :return: new StickerMessage instance. :rtype: StickerMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.files import InputFile from pytgbot.api_types.sendable.reply_markup import ForceReply from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardRemove data = {} if isinstance(array.get('sticker'), InputFile): data['sticker'] = InputFile.from_array(array.get('sticker')) elif isinstance(array.get('sticker'), str): data['sticker'] = u(array.get('sticker')) else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None if array.get('reply_markup') is None: data['reply_markup'] = None elif isinstance(array.get('reply_markup'), InlineKeyboardMarkup): data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) elif isinstance(array.get('reply_markup'), ReplyKeyboardMarkup): data['reply_markup'] = ReplyKeyboardMarkup.from_array(array.get('reply_markup')) elif isinstance(array.get('reply_markup'), ReplyKeyboardRemove): data['reply_markup'] = ReplyKeyboardRemove.from_array(array.get('reply_markup')) elif isinstance(array.get('reply_markup'), ForceReply): data['reply_markup'] = ForceReply.from_array(array.get('reply_markup')) else: raise TypeError('Unknown type, must be one of InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply or None.') # end if return StickerMessage(**data)
Deserialize a new StickerMessage from a given dictionary. :return: new StickerMessage instance. :rtype: StickerMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L3629-L3689
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
InvoiceMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_invoice( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id title=self.title, description=self.description, payload=self.payload, provider_token=self.provider_token, start_parameter=self.start_parameter, currency=self.currency, prices=self.prices, chat_id=self.receiver, reply_to_message_id=self.reply_id, provider_data=self.provider_data, photo_url=self.photo_url, photo_size=self.photo_size, photo_width=self.photo_width, photo_height=self.photo_height, need_name=self.need_name, need_phone_number=self.need_phone_number, need_email=self.need_email, need_shipping_address=self.need_shipping_address, send_phone_number_to_provider=self.send_phone_number_to_provider, send_email_to_provider=self.send_email_to_provider, is_flexible=self.is_flexible, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_invoice( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id title=self.title, description=self.description, payload=self.payload, provider_token=self.provider_token, start_parameter=self.start_parameter, currency=self.currency, prices=self.prices, chat_id=self.receiver, reply_to_message_id=self.reply_id, provider_data=self.provider_data, photo_url=self.photo_url, photo_size=self.photo_size, photo_width=self.photo_width, photo_height=self.photo_height, need_name=self.need_name, need_phone_number=self.need_phone_number, need_email=self.need_email, need_shipping_address=self.need_shipping_address, send_phone_number_to_provider=self.send_phone_number_to_provider, send_email_to_provider=self.send_email_to_provider, is_flexible=self.is_flexible, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L3955-L3967
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
InvoiceMessage.to_array
def to_array(self): """ Serializes this InvoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InvoiceMessage, self).to_array() array['title'] = u(self.title) # py2: type unicode, py3: type str array['description'] = u(self.description) # py2: type unicode, py3: type str array['payload'] = u(self.payload) # py2: type unicode, py3: type str array['provider_token'] = u(self.provider_token) # py2: type unicode, py3: type str array['start_parameter'] = u(self.start_parameter) # py2: type unicode, py3: type str array['currency'] = u(self.currency) # py2: type unicode, py3: type str array['prices'] = self._as_array(self.prices) # type list of LabeledPrice if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.provider_data is not None: array['provider_data'] = u(self.provider_data) # py2: type unicode, py3: type str if self.photo_url is not None: array['photo_url'] = u(self.photo_url) # py2: type unicode, py3: type str if self.photo_size is not None: array['photo_size'] = int(self.photo_size) # type int if self.photo_width is not None: array['photo_width'] = int(self.photo_width) # type int if self.photo_height is not None: array['photo_height'] = int(self.photo_height) # type int if self.need_name is not None: array['need_name'] = bool(self.need_name) # type bool if self.need_phone_number is not None: array['need_phone_number'] = bool(self.need_phone_number) # type bool if self.need_email is not None: array['need_email'] = bool(self.need_email) # type bool if self.need_shipping_address is not None: array['need_shipping_address'] = bool(self.need_shipping_address) # type bool if self.send_phone_number_to_provider is not None: array['send_phone_number_to_provider'] = bool(self.send_phone_number_to_provider) # type bool if self.send_email_to_provider is not None: array['send_email_to_provider'] = bool(self.send_email_to_provider) # type bool if self.is_flexible is not None: array['is_flexible'] = bool(self.is_flexible) # type bool if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup return array
python
def to_array(self): """ Serializes this InvoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InvoiceMessage, self).to_array() array['title'] = u(self.title) # py2: type unicode, py3: type str array['description'] = u(self.description) # py2: type unicode, py3: type str array['payload'] = u(self.payload) # py2: type unicode, py3: type str array['provider_token'] = u(self.provider_token) # py2: type unicode, py3: type str array['start_parameter'] = u(self.start_parameter) # py2: type unicode, py3: type str array['currency'] = u(self.currency) # py2: type unicode, py3: type str array['prices'] = self._as_array(self.prices) # type list of LabeledPrice if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.provider_data is not None: array['provider_data'] = u(self.provider_data) # py2: type unicode, py3: type str if self.photo_url is not None: array['photo_url'] = u(self.photo_url) # py2: type unicode, py3: type str if self.photo_size is not None: array['photo_size'] = int(self.photo_size) # type int if self.photo_width is not None: array['photo_width'] = int(self.photo_width) # type int if self.photo_height is not None: array['photo_height'] = int(self.photo_height) # type int if self.need_name is not None: array['need_name'] = bool(self.need_name) # type bool if self.need_phone_number is not None: array['need_phone_number'] = bool(self.need_phone_number) # type bool if self.need_email is not None: array['need_email'] = bool(self.need_email) # type bool if self.need_shipping_address is not None: array['need_shipping_address'] = bool(self.need_shipping_address) # type bool if self.send_phone_number_to_provider is not None: array['send_phone_number_to_provider'] = bool(self.send_phone_number_to_provider) # type bool if self.send_email_to_provider is not None: array['send_email_to_provider'] = bool(self.send_email_to_provider) # type bool if self.is_flexible is not None: array['is_flexible'] = bool(self.is_flexible) # type bool if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup return array
Serializes this InvoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L3970-L4039
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
InvoiceMessage.from_array
def from_array(array): """ Deserialize a new InvoiceMessage from a given dictionary. :return: new InvoiceMessage instance. :rtype: InvoiceMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.payments import LabeledPrice from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup data = {} data['title'] = u(array.get('title')) data['description'] = u(array.get('description')) data['payload'] = u(array.get('payload')) data['provider_token'] = u(array.get('provider_token')) data['start_parameter'] = u(array.get('start_parameter')) data['currency'] = u(array.get('currency')) data['prices'] = LabeledPrice.from_array_list(array.get('prices'), list_level=1) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['provider_data'] = u(array.get('provider_data')) if array.get('provider_data') is not None else None data['photo_url'] = u(array.get('photo_url')) if array.get('photo_url') is not None else None data['photo_size'] = int(array.get('photo_size')) if array.get('photo_size') is not None else None data['photo_width'] = int(array.get('photo_width')) if array.get('photo_width') is not None else None data['photo_height'] = int(array.get('photo_height')) if array.get('photo_height') is not None else None data['need_name'] = bool(array.get('need_name')) if array.get('need_name') is not None else None data['need_phone_number'] = bool(array.get('need_phone_number')) if array.get('need_phone_number') is not None else None data['need_email'] = bool(array.get('need_email')) if array.get('need_email') is not None else None data['need_shipping_address'] = bool(array.get('need_shipping_address')) if array.get('need_shipping_address') is not None else None data['send_phone_number_to_provider'] = bool(array.get('send_phone_number_to_provider')) if array.get('send_phone_number_to_provider') is not None else None data['send_email_to_provider'] = bool(array.get('send_email_to_provider')) if array.get('send_email_to_provider') is not None else None data['is_flexible'] = bool(array.get('is_flexible')) if array.get('is_flexible') is not None else None data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None return InvoiceMessage(**data)
python
def from_array(array): """ Deserialize a new InvoiceMessage from a given dictionary. :return: new InvoiceMessage instance. :rtype: InvoiceMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.payments import LabeledPrice from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup data = {} data['title'] = u(array.get('title')) data['description'] = u(array.get('description')) data['payload'] = u(array.get('payload')) data['provider_token'] = u(array.get('provider_token')) data['start_parameter'] = u(array.get('start_parameter')) data['currency'] = u(array.get('currency')) data['prices'] = LabeledPrice.from_array_list(array.get('prices'), list_level=1) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['provider_data'] = u(array.get('provider_data')) if array.get('provider_data') is not None else None data['photo_url'] = u(array.get('photo_url')) if array.get('photo_url') is not None else None data['photo_size'] = int(array.get('photo_size')) if array.get('photo_size') is not None else None data['photo_width'] = int(array.get('photo_width')) if array.get('photo_width') is not None else None data['photo_height'] = int(array.get('photo_height')) if array.get('photo_height') is not None else None data['need_name'] = bool(array.get('need_name')) if array.get('need_name') is not None else None data['need_phone_number'] = bool(array.get('need_phone_number')) if array.get('need_phone_number') is not None else None data['need_email'] = bool(array.get('need_email')) if array.get('need_email') is not None else None data['need_shipping_address'] = bool(array.get('need_shipping_address')) if array.get('need_shipping_address') is not None else None data['send_phone_number_to_provider'] = bool(array.get('send_phone_number_to_provider')) if array.get('send_phone_number_to_provider') is not None else None data['send_email_to_provider'] = bool(array.get('send_email_to_provider')) if array.get('send_email_to_provider') is not None else None data['is_flexible'] = bool(array.get('is_flexible')) if array.get('is_flexible') is not None else None data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None return InvoiceMessage(**data)
Deserialize a new InvoiceMessage from a given dictionary. :return: new InvoiceMessage instance. :rtype: InvoiceMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L4043-L4100
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
GameMessage.send
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_game( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id game_short_name=self.game_short_name, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
python
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_game( # receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id game_short_name=self.game_short_name, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification, reply_markup=self.reply_markup )
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L4203-L4215
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
GameMessage.to_array
def to_array(self): """ Serializes this GameMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(GameMessage, self).to_array() array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup return array
python
def to_array(self): """ Serializes this GameMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(GameMessage, self).to_array() array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup return array
Serializes this GameMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L4218-L4249
luckydonald/pytgbot
code_generation/output/teleflask_messages.py
GameMessage.from_array
def from_array(array): """ Deserialize a new GameMessage from a given dictionary. :return: new GameMessage instance. :rtype: GameMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup data = {} data['game_short_name'] = u(array.get('game_short_name')) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None return GameMessage(**data)
python
def from_array(array): """ Deserialize a new GameMessage from a given dictionary. :return: new GameMessage instance. :rtype: GameMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup data = {} data['game_short_name'] = u(array.get('game_short_name')) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id')) elif isinstance(array.get('reply_to_message_id'), int): data['reply_id'] = int(array.get('reply_to_message_id')) else: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.') # end if data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None return GameMessage(**data)
Deserialize a new GameMessage from a given dictionary. :return: new GameMessage instance. :rtype: GameMessage
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L4253-L4291
delph-in/pydelphin
delphin/mrs/query.py
select_nodeids
def select_nodeids(xmrs, iv=None, label=None, pred=None): """ Return the list of matching nodeids in *xmrs*. Nodeids in *xmrs* match if their corresponding :class:`~delphin.mrs.components.ElementaryPredication` object matches its `intrinsic_variable` to *iv*, `label` to *label*, and `pred` to *pred*. The *iv*, *label*, and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query iv (str, optional): intrinsic variable to match label (str, optional): label to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching nodeids """ def datamatch(nid): ep = xmrs.ep(nid) return ((iv is None or ep.iv == iv) and (pred is None or ep.pred == pred) and (label is None or ep.label == label)) return list(filter(datamatch, xmrs.nodeids()))
python
def select_nodeids(xmrs, iv=None, label=None, pred=None): """ Return the list of matching nodeids in *xmrs*. Nodeids in *xmrs* match if their corresponding :class:`~delphin.mrs.components.ElementaryPredication` object matches its `intrinsic_variable` to *iv*, `label` to *label*, and `pred` to *pred*. The *iv*, *label*, and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query iv (str, optional): intrinsic variable to match label (str, optional): label to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching nodeids """ def datamatch(nid): ep = xmrs.ep(nid) return ((iv is None or ep.iv == iv) and (pred is None or ep.pred == pred) and (label is None or ep.label == label)) return list(filter(datamatch, xmrs.nodeids()))
Return the list of matching nodeids in *xmrs*. Nodeids in *xmrs* match if their corresponding :class:`~delphin.mrs.components.ElementaryPredication` object matches its `intrinsic_variable` to *iv*, `label` to *label*, and `pred` to *pred*. The *iv*, *label*, and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query iv (str, optional): intrinsic variable to match label (str, optional): label to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching nodeids
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L12-L37
delph-in/pydelphin
delphin/mrs/query.py
select_nodes
def select_nodes(xmrs, nodeid=None, pred=None): """ Return the list of matching nodes in *xmrs*. DMRS :class:`nodes <delphin.mrs.components.node>` for *xmrs* match if their `nodeid` matches *nodeid* and `pred` matches *pred*. The *nodeid* and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): DMRS nodeid to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching nodes """ nodematch = lambda n: ((nodeid is None or n.nodeid == nodeid) and (pred is None or n.pred == pred)) return list(filter(nodematch, nodes(xmrs)))
python
def select_nodes(xmrs, nodeid=None, pred=None): """ Return the list of matching nodes in *xmrs*. DMRS :class:`nodes <delphin.mrs.components.node>` for *xmrs* match if their `nodeid` matches *nodeid* and `pred` matches *pred*. The *nodeid* and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): DMRS nodeid to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching nodes """ nodematch = lambda n: ((nodeid is None or n.nodeid == nodeid) and (pred is None or n.pred == pred)) return list(filter(nodematch, nodes(xmrs)))
Return the list of matching nodes in *xmrs*. DMRS :class:`nodes <delphin.mrs.components.node>` for *xmrs* match if their `nodeid` matches *nodeid* and `pred` matches *pred*. The *nodeid* and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): DMRS nodeid to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching nodes
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L40-L59
delph-in/pydelphin
delphin/mrs/query.py
select_eps
def select_eps(xmrs, nodeid=None, iv=None, label=None, pred=None): """ Return the list of matching elementary predications in *xmrs*. :class:`~delphin.mrs.components.ElementaryPredication` objects for *xmrs* match if their `nodeid` matches *nodeid*, `intrinsic_variable` matches *iv*, `label` matches *label*, and `pred` to *pred*. The *nodeid*, *iv*, *label*, and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): nodeid to match iv (str, optional): intrinsic variable to match label (str, optional): label to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching elementary predications """ epmatch = lambda n: ((nodeid is None or n.nodeid == nodeid) and (iv is None or n.iv == iv) and (label is None or n.label == label) and (pred is None or n.pred == pred)) return list(filter(epmatch, xmrs.eps()))
python
def select_eps(xmrs, nodeid=None, iv=None, label=None, pred=None): """ Return the list of matching elementary predications in *xmrs*. :class:`~delphin.mrs.components.ElementaryPredication` objects for *xmrs* match if their `nodeid` matches *nodeid*, `intrinsic_variable` matches *iv*, `label` matches *label*, and `pred` to *pred*. The *nodeid*, *iv*, *label*, and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): nodeid to match iv (str, optional): intrinsic variable to match label (str, optional): label to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching elementary predications """ epmatch = lambda n: ((nodeid is None or n.nodeid == nodeid) and (iv is None or n.iv == iv) and (label is None or n.label == label) and (pred is None or n.pred == pred)) return list(filter(epmatch, xmrs.eps()))
Return the list of matching elementary predications in *xmrs*. :class:`~delphin.mrs.components.ElementaryPredication` objects for *xmrs* match if their `nodeid` matches *nodeid*, `intrinsic_variable` matches *iv*, `label` matches *label*, and `pred` to *pred*. The *nodeid*, *iv*, *label*, and *pred* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): nodeid to match iv (str, optional): intrinsic variable to match label (str, optional): label to match pred (str, :class:`~delphin.mrs.components.Pred`, optional): predicate to match Returns: list: matching elementary predications
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L62-L87
delph-in/pydelphin
delphin/mrs/query.py
select_args
def select_args(xmrs, nodeid=None, rargname=None, value=None): """ Return the list of matching (nodeid, role, value) triples in *xmrs*. Predication arguments in *xmrs* match if the `nodeid` of the :class:`~delphin.mrs.components.ElementaryPredication` they are arguments of match *nodeid*, their role matches *rargname*, and their value matches *value*. The *nodeid*, *rargname*, and *value* filters are ignored if they are `None`. Note: The *value* filter matches the variable, handle, or constant that is the overt value for the argument. If you want to find arguments that target a particular nodeid, look into :meth:`Xmrs.incoming_args() <delphin.mrs.xmrs.Xmrs.incoming_args>`. If you want to match a target value to its resolved object, see :func:`find_argument_target`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): nodeid to match rargname (str, optional): role name to match value (str, optional): argument value to match Returns: list: matching arguments as (nodeid, role, value) triples """ argmatch = lambda a: ((nodeid is None or a[0] == nodeid) and (rargname is None or a[1].upper() == rargname.upper()) and (value is None or a[2] == value)) all_args = ( (nid, role, val) for nid in xmrs.nodeids() for role, val in sorted( xmrs.args(nid).items(), key=lambda i: rargname_sortkey(i[0]) ) ) return list(filter(argmatch, all_args))
python
def select_args(xmrs, nodeid=None, rargname=None, value=None): """ Return the list of matching (nodeid, role, value) triples in *xmrs*. Predication arguments in *xmrs* match if the `nodeid` of the :class:`~delphin.mrs.components.ElementaryPredication` they are arguments of match *nodeid*, their role matches *rargname*, and their value matches *value*. The *nodeid*, *rargname*, and *value* filters are ignored if they are `None`. Note: The *value* filter matches the variable, handle, or constant that is the overt value for the argument. If you want to find arguments that target a particular nodeid, look into :meth:`Xmrs.incoming_args() <delphin.mrs.xmrs.Xmrs.incoming_args>`. If you want to match a target value to its resolved object, see :func:`find_argument_target`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): nodeid to match rargname (str, optional): role name to match value (str, optional): argument value to match Returns: list: matching arguments as (nodeid, role, value) triples """ argmatch = lambda a: ((nodeid is None or a[0] == nodeid) and (rargname is None or a[1].upper() == rargname.upper()) and (value is None or a[2] == value)) all_args = ( (nid, role, val) for nid in xmrs.nodeids() for role, val in sorted( xmrs.args(nid).items(), key=lambda i: rargname_sortkey(i[0]) ) ) return list(filter(argmatch, all_args))
Return the list of matching (nodeid, role, value) triples in *xmrs*. Predication arguments in *xmrs* match if the `nodeid` of the :class:`~delphin.mrs.components.ElementaryPredication` they are arguments of match *nodeid*, their role matches *rargname*, and their value matches *value*. The *nodeid*, *rargname*, and *value* filters are ignored if they are `None`. Note: The *value* filter matches the variable, handle, or constant that is the overt value for the argument. If you want to find arguments that target a particular nodeid, look into :meth:`Xmrs.incoming_args() <delphin.mrs.xmrs.Xmrs.incoming_args>`. If you want to match a target value to its resolved object, see :func:`find_argument_target`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query nodeid (optional): nodeid to match rargname (str, optional): role name to match value (str, optional): argument value to match Returns: list: matching arguments as (nodeid, role, value) triples
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L90-L128
delph-in/pydelphin
delphin/mrs/query.py
select_links
def select_links(xmrs, start=None, end=None, rargname=None, post=None): """ Return the list of matching links for *xmrs*. :class:`~delphin.mrs.components.Link` objects for *xmrs* match if their `start` matches *start*, `end` matches *end*, `rargname` matches *rargname*, and `post` matches *post*. The *start*, *end*, *rargname*, and *post* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query start (optional): link start nodeid to match end (optional): link end nodeid to match rargname (str, optional): role name to match post (str, optional): Link post-slash label to match Returns: list: matching links """ linkmatch = lambda l: ( (start is None or l.start == start) and (end is None or l.end == end) and (rargname is None or l.rargname == rargname) and (post is None or l.post == post)) return list(filter(linkmatch, links(xmrs)))
python
def select_links(xmrs, start=None, end=None, rargname=None, post=None): """ Return the list of matching links for *xmrs*. :class:`~delphin.mrs.components.Link` objects for *xmrs* match if their `start` matches *start*, `end` matches *end*, `rargname` matches *rargname*, and `post` matches *post*. The *start*, *end*, *rargname*, and *post* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query start (optional): link start nodeid to match end (optional): link end nodeid to match rargname (str, optional): role name to match post (str, optional): Link post-slash label to match Returns: list: matching links """ linkmatch = lambda l: ( (start is None or l.start == start) and (end is None or l.end == end) and (rargname is None or l.rargname == rargname) and (post is None or l.post == post)) return list(filter(linkmatch, links(xmrs)))
Return the list of matching links for *xmrs*. :class:`~delphin.mrs.components.Link` objects for *xmrs* match if their `start` matches *start*, `end` matches *end*, `rargname` matches *rargname*, and `post` matches *post*. The *start*, *end*, *rargname*, and *post* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query start (optional): link start nodeid to match end (optional): link end nodeid to match rargname (str, optional): role name to match post (str, optional): Link post-slash label to match Returns: list: matching links
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L131-L155
delph-in/pydelphin
delphin/mrs/query.py
select_hcons
def select_hcons(xmrs, hi=None, relation=None, lo=None): """ Return the list of matching HCONS for *xmrs*. :class:`~delphin.mrs.components.HandleConstraint` objects for *xmrs* match if their `hi` matches *hi*, `relation` matches *relation*, and `lo` matches *lo*. The *hi*, *relation*, and *lo* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query hi (str, optional): hi handle (hole) to match relation (str, optional): handle constraint relation to match lo (str, optional): lo handle (label) to match Returns: list: matching HCONS """ hcmatch = lambda hc: ( (hi is None or hc.hi == hi) and (relation is None or hc.relation == relation) and (lo is None or hc.lo == lo)) return list(filter(hcmatch, xmrs.hcons()))
python
def select_hcons(xmrs, hi=None, relation=None, lo=None): """ Return the list of matching HCONS for *xmrs*. :class:`~delphin.mrs.components.HandleConstraint` objects for *xmrs* match if their `hi` matches *hi*, `relation` matches *relation*, and `lo` matches *lo*. The *hi*, *relation*, and *lo* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query hi (str, optional): hi handle (hole) to match relation (str, optional): handle constraint relation to match lo (str, optional): lo handle (label) to match Returns: list: matching HCONS """ hcmatch = lambda hc: ( (hi is None or hc.hi == hi) and (relation is None or hc.relation == relation) and (lo is None or hc.lo == lo)) return list(filter(hcmatch, xmrs.hcons()))
Return the list of matching HCONS for *xmrs*. :class:`~delphin.mrs.components.HandleConstraint` objects for *xmrs* match if their `hi` matches *hi*, `relation` matches *relation*, and `lo` matches *lo*. The *hi*, *relation*, and *lo* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query hi (str, optional): hi handle (hole) to match relation (str, optional): handle constraint relation to match lo (str, optional): lo handle (label) to match Returns: list: matching HCONS
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L158-L180
delph-in/pydelphin
delphin/mrs/query.py
select_icons
def select_icons(xmrs, left=None, relation=None, right=None): """ Return the list of matching ICONS for *xmrs*. :class:`~delphin.mrs.components.IndividualConstraint` objects for *xmrs* match if their `left` matches *left*, `relation` matches *relation*, and `right` matches *right*. The *left*, *relation*, and *right* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query left (str, optional): left variable to match relation (str, optional): individual constraint relation to match right (str, optional): right variable to match Returns: list: matching ICONS """ icmatch = lambda ic: ( (left is None or ic.left == left) and (relation is None or ic.relation == relation) and (right is None or ic.right == right)) return list(filter(icmatch, xmrs.icons()))
python
def select_icons(xmrs, left=None, relation=None, right=None): """ Return the list of matching ICONS for *xmrs*. :class:`~delphin.mrs.components.IndividualConstraint` objects for *xmrs* match if their `left` matches *left*, `relation` matches *relation*, and `right` matches *right*. The *left*, *relation*, and *right* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query left (str, optional): left variable to match relation (str, optional): individual constraint relation to match right (str, optional): right variable to match Returns: list: matching ICONS """ icmatch = lambda ic: ( (left is None or ic.left == left) and (relation is None or ic.relation == relation) and (right is None or ic.right == right)) return list(filter(icmatch, xmrs.icons()))
Return the list of matching ICONS for *xmrs*. :class:`~delphin.mrs.components.IndividualConstraint` objects for *xmrs* match if their `left` matches *left*, `relation` matches *relation*, and `right` matches *right*. The *left*, *relation*, and *right* filters are ignored if they are `None`. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to query left (str, optional): left variable to match relation (str, optional): individual constraint relation to match right (str, optional): right variable to match Returns: list: matching ICONS
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L183-L205
delph-in/pydelphin
delphin/mrs/query.py
find_argument_target
def find_argument_target(xmrs, nodeid, rargname): """ Return the target of an argument (rather than just the variable). Note: If the argument value is an intrinsic variable whose target is an EP that has a quantifier, the non-quantifier EP's nodeid will be returned. With this nodeid, one can then use :meth:`Xmrs.nodeid() <delphin.mrs.xmrs.Xmrs.nodeid>` to get its quantifier's nodeid. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to use nodeid: nodeid of the argument. rargname: role name of the argument. Returns: The object that is the target of the argument. Possible values include: ================== ===== ============================= Argument value e.g. Target ------------------ ----- ----------------------------- intrinsic variable x4 nodeid; of the EP with the IV hole variable h0 nodeid; HCONS's labelset head label h1 nodeid; label's labelset head unbound variable i3 the variable itself constant "IBM" the constant itself ================== ===== ============================= """ tgt = xmrs.args(nodeid)[rargname] if tgt in xmrs.variables(): try: return xmrs.nodeid(tgt) except KeyError: pass try: tgt = xmrs.hcon(tgt).lo return next(iter(xmrs.labelset_heads(tgt)), None) except KeyError: pass try: return next(iter(xmrs.labelset_heads(tgt))) except (KeyError, StopIteration): pass return tgt
python
def find_argument_target(xmrs, nodeid, rargname): """ Return the target of an argument (rather than just the variable). Note: If the argument value is an intrinsic variable whose target is an EP that has a quantifier, the non-quantifier EP's nodeid will be returned. With this nodeid, one can then use :meth:`Xmrs.nodeid() <delphin.mrs.xmrs.Xmrs.nodeid>` to get its quantifier's nodeid. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to use nodeid: nodeid of the argument. rargname: role name of the argument. Returns: The object that is the target of the argument. Possible values include: ================== ===== ============================= Argument value e.g. Target ------------------ ----- ----------------------------- intrinsic variable x4 nodeid; of the EP with the IV hole variable h0 nodeid; HCONS's labelset head label h1 nodeid; label's labelset head unbound variable i3 the variable itself constant "IBM" the constant itself ================== ===== ============================= """ tgt = xmrs.args(nodeid)[rargname] if tgt in xmrs.variables(): try: return xmrs.nodeid(tgt) except KeyError: pass try: tgt = xmrs.hcon(tgt).lo return next(iter(xmrs.labelset_heads(tgt)), None) except KeyError: pass try: return next(iter(xmrs.labelset_heads(tgt))) except (KeyError, StopIteration): pass return tgt
Return the target of an argument (rather than just the variable). Note: If the argument value is an intrinsic variable whose target is an EP that has a quantifier, the non-quantifier EP's nodeid will be returned. With this nodeid, one can then use :meth:`Xmrs.nodeid() <delphin.mrs.xmrs.Xmrs.nodeid>` to get its quantifier's nodeid. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to use nodeid: nodeid of the argument. rargname: role name of the argument. Returns: The object that is the target of the argument. Possible values include: ================== ===== ============================= Argument value e.g. Target ------------------ ----- ----------------------------- intrinsic variable x4 nodeid; of the EP with the IV hole variable h0 nodeid; HCONS's labelset head label h1 nodeid; label's labelset head unbound variable i3 the variable itself constant "IBM" the constant itself ================== ===== =============================
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L208-L254
delph-in/pydelphin
delphin/mrs/query.py
find_subgraphs_by_preds
def find_subgraphs_by_preds(xmrs, preds, connected=None): """ Yield subgraphs matching a list of predicates. Predicates may match multiple EPs/nodes in the *xmrs*, meaning that more than one subgraph is possible. Also, predicates in *preds* match in number, so if a predicate appears twice in *preds*, there will be two matching EPs/nodes in each subgraph. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to use preds: iterable of predicates to include in subgraphs connected (bool, optional): if `True`, all yielded subgraphs must be connected, as determined by :meth:`Xmrs.is_connected() <delphin.mrs.xmrs.Xmrs.is_connected>`. Yields: A :class:`~delphin.mrs.xmrs.Xmrs` object for each subgraphs found. """ preds = list(preds) count = len(preds) # find all lists of nodeids such that the lists have no repeated nids; # keep them as a list (fixme: why not just get sets?) nidsets = set( tuple(sorted(ns)) for ns in filter( lambda ns: len(set(ns)) == count, product(*[select_nodeids(xmrs, pred=p) for p in preds]) ) ) for nidset in nidsets: sg = xmrs.subgraph(nidset) if connected is None or sg.is_connected() == connected: yield sg
python
def find_subgraphs_by_preds(xmrs, preds, connected=None): """ Yield subgraphs matching a list of predicates. Predicates may match multiple EPs/nodes in the *xmrs*, meaning that more than one subgraph is possible. Also, predicates in *preds* match in number, so if a predicate appears twice in *preds*, there will be two matching EPs/nodes in each subgraph. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to use preds: iterable of predicates to include in subgraphs connected (bool, optional): if `True`, all yielded subgraphs must be connected, as determined by :meth:`Xmrs.is_connected() <delphin.mrs.xmrs.Xmrs.is_connected>`. Yields: A :class:`~delphin.mrs.xmrs.Xmrs` object for each subgraphs found. """ preds = list(preds) count = len(preds) # find all lists of nodeids such that the lists have no repeated nids; # keep them as a list (fixme: why not just get sets?) nidsets = set( tuple(sorted(ns)) for ns in filter( lambda ns: len(set(ns)) == count, product(*[select_nodeids(xmrs, pred=p) for p in preds]) ) ) for nidset in nidsets: sg = xmrs.subgraph(nidset) if connected is None or sg.is_connected() == connected: yield sg
Yield subgraphs matching a list of predicates. Predicates may match multiple EPs/nodes in the *xmrs*, meaning that more than one subgraph is possible. Also, predicates in *preds* match in number, so if a predicate appears twice in *preds*, there will be two matching EPs/nodes in each subgraph. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to use preds: iterable of predicates to include in subgraphs connected (bool, optional): if `True`, all yielded subgraphs must be connected, as determined by :meth:`Xmrs.is_connected() <delphin.mrs.xmrs.Xmrs.is_connected>`. Yields: A :class:`~delphin.mrs.xmrs.Xmrs` object for each subgraphs found.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L257-L290
delph-in/pydelphin
delphin/mrs/query.py
intrinsic_variables
def intrinsic_variables(xmrs): """Return the list of all intrinsic variables in *xmrs*""" ivs = set( ep.intrinsic_variable for ep in xmrs.eps() if not ep.is_quantifier() and ep.intrinsic_variable is not None ) return sorted(ivs, key=var_id)
python
def intrinsic_variables(xmrs): """Return the list of all intrinsic variables in *xmrs*""" ivs = set( ep.intrinsic_variable for ep in xmrs.eps() if not ep.is_quantifier() and ep.intrinsic_variable is not None ) return sorted(ivs, key=var_id)
Return the list of all intrinsic variables in *xmrs*
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L297-L303
delph-in/pydelphin
delphin/mrs/query.py
bound_variables
def bound_variables(xmrs): """Return the list of all bound variables in *xmrs*""" bvs = set( ep.intrinsic_variable for ep in xmrs.eps() if ep.is_quantifier() and ep.intrinsic_variable is not None ) return sorted(bvs, key=var_id)
python
def bound_variables(xmrs): """Return the list of all bound variables in *xmrs*""" bvs = set( ep.intrinsic_variable for ep in xmrs.eps() if ep.is_quantifier() and ep.intrinsic_variable is not None ) return sorted(bvs, key=var_id)
Return the list of all bound variables in *xmrs*
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L305-L311
delph-in/pydelphin
delphin/mrs/query.py
in_labelset
def in_labelset(xmrs, nodeids, label=None): """ Test if all nodeids share a label. Args: nodeids: iterable of nodeids label (str, optional): the label that all nodeids must share Returns: bool: `True` if all nodeids share a label, otherwise `False` """ nodeids = set(nodeids) if label is None: label = xmrs.ep(next(iter(nodeids))).label return nodeids.issubset(xmrs._vars[label]['refs']['LBL'])
python
def in_labelset(xmrs, nodeids, label=None): """ Test if all nodeids share a label. Args: nodeids: iterable of nodeids label (str, optional): the label that all nodeids must share Returns: bool: `True` if all nodeids share a label, otherwise `False` """ nodeids = set(nodeids) if label is None: label = xmrs.ep(next(iter(nodeids))).label return nodeids.issubset(xmrs._vars[label]['refs']['LBL'])
Test if all nodeids share a label. Args: nodeids: iterable of nodeids label (str, optional): the label that all nodeids must share Returns: bool: `True` if all nodeids share a label, otherwise `False`
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L313-L326
luckydonald/pytgbot
pytgbot/api_types/sendable/files.py
InputFile.get_input_media_referenced_files
def get_input_media_referenced_files(self, var_name): """ Generates a tuple with the value for the json/url argument and a dictionary for the multipart file upload. Will return something which might be similar to `('attach://{var_name}', {var_name: ('foo.png', open('foo.png', 'rb'), 'image/png')})` or in the case of the :class:`InputFileUseFileID` class, just `('AwADBAADbXXXXXXXXXXXGBdhD2l6_XX', None)` :param var_name: name used to reference the file. :type var_name: str :return: tuple of (file_id, dict) :rtype: tuple """ # file to be uploaded string = 'attach://{name}'.format(name=var_name) return string, self.get_request_files(var_name)
python
def get_input_media_referenced_files(self, var_name): """ Generates a tuple with the value for the json/url argument and a dictionary for the multipart file upload. Will return something which might be similar to `('attach://{var_name}', {var_name: ('foo.png', open('foo.png', 'rb'), 'image/png')})` or in the case of the :class:`InputFileUseFileID` class, just `('AwADBAADbXXXXXXXXXXXGBdhD2l6_XX', None)` :param var_name: name used to reference the file. :type var_name: str :return: tuple of (file_id, dict) :rtype: tuple """ # file to be uploaded string = 'attach://{name}'.format(name=var_name) return string, self.get_request_files(var_name)
Generates a tuple with the value for the json/url argument and a dictionary for the multipart file upload. Will return something which might be similar to `('attach://{var_name}', {var_name: ('foo.png', open('foo.png', 'rb'), 'image/png')})` or in the case of the :class:`InputFileUseFileID` class, just `('AwADBAADbXXXXXXXXXXXGBdhD2l6_XX', None)` :param var_name: name used to reference the file. :type var_name: str :return: tuple of (file_id, dict) :rtype: tuple
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/files.py#L107-L124
luckydonald/pytgbot
pytgbot/api_types/sendable/files.py
InputFile.factory
def factory( cls, file_id=None, path=None, url=None, blob=None, mime=None, prefer_local_download=True, prefer_str=False, create_instance=True ): """ Creates a new InputFile subclass instance fitting the given parameters. :param prefer_local_download: If `True`, we download the file and send it to telegram. This is the default. If `False`, we send Telegram just the URL, and they'll try to download it. :type prefer_local_download: bool :param prefer_str: Return just the `str` instead of a `InputFileUseFileID` or `InputFileUseUrl` object. :type prefer_str: bool :param create_instance: If we should return a instance ready to use (default), or the building parts being a tuple of `(class, args_tuple, kwargs_dict)`. Setting this to `False` is probably only ever required for internal usage by the :class:`InputFile` constructor which uses this very factory. :type create_instance: bool :returns: if `create_instance=True` it returns a instance of some InputFile subclass or a string, if `create_instance=False` it returns a tuple of the needed class, args and kwargs needed to create a instance. :rtype: InputFile|InputFileFromBlob|InputFileFromDisk|InputFileFromURL|str|tuple """ if create_instance: clazz, args, kwargs = cls.factory( file_id=file_id, path=path, url=url, blob=blob, mime=mime, create_instance=False, ) return clazz(*args, **kwargs) if file_id: if prefer_str: assert_type_or_raise(file_id, str, parameter_name='file_id') return str, (file_id,), dict() # end if return InputFileUseFileID, (file_id,), dict() if blob: name = "file" suffix = ".blob" if path: name = os_path.basename(os_path.normpath(path)) # http://stackoverflow.com/a/3925147/3423324#last-part name, suffix = os_path.splitext(name) # http://stackoverflow.com/a/541394/3423324#extension elif url: # http://stackoverflow.com/a/18727481/3423324#how-to-extract-a-filename-from-a-url url = urlparse(url) name = os_path.basename(url.path) name, suffix = os_path.splitext(name) # end if if mime: import mimetypes suffix = mimetypes.guess_extension(mime) suffix = '.jpg' if suffix == '.jpe' else suffix # .jpe -> .jpg # end if if not suffix or not suffix.strip().lstrip("."): logger.debug("suffix was empty. Using '.blob'") suffix = ".blob" # end if name = "{filename}{suffix}".format(filename=name, suffix=suffix) return InputFileFromBlob, (blob,), dict(name=name, mime=mime) if path: return InputFileFromDisk, (path,), dict(mime=mime) if url: if prefer_local_download: return InputFileFromURL, (url,), dict(mime=mime) # end if # else -> so we wanna let telegram handle it if prefer_str: assert_type_or_raise(url, str, parameter_name='url') return str, (url,), dict() # end if return InputFileUseUrl, (url,), dict() # end if raise ValueError('Could not find a matching subclass. You might need to do it manually instead.')
python
def factory( cls, file_id=None, path=None, url=None, blob=None, mime=None, prefer_local_download=True, prefer_str=False, create_instance=True ): """ Creates a new InputFile subclass instance fitting the given parameters. :param prefer_local_download: If `True`, we download the file and send it to telegram. This is the default. If `False`, we send Telegram just the URL, and they'll try to download it. :type prefer_local_download: bool :param prefer_str: Return just the `str` instead of a `InputFileUseFileID` or `InputFileUseUrl` object. :type prefer_str: bool :param create_instance: If we should return a instance ready to use (default), or the building parts being a tuple of `(class, args_tuple, kwargs_dict)`. Setting this to `False` is probably only ever required for internal usage by the :class:`InputFile` constructor which uses this very factory. :type create_instance: bool :returns: if `create_instance=True` it returns a instance of some InputFile subclass or a string, if `create_instance=False` it returns a tuple of the needed class, args and kwargs needed to create a instance. :rtype: InputFile|InputFileFromBlob|InputFileFromDisk|InputFileFromURL|str|tuple """ if create_instance: clazz, args, kwargs = cls.factory( file_id=file_id, path=path, url=url, blob=blob, mime=mime, create_instance=False, ) return clazz(*args, **kwargs) if file_id: if prefer_str: assert_type_or_raise(file_id, str, parameter_name='file_id') return str, (file_id,), dict() # end if return InputFileUseFileID, (file_id,), dict() if blob: name = "file" suffix = ".blob" if path: name = os_path.basename(os_path.normpath(path)) # http://stackoverflow.com/a/3925147/3423324#last-part name, suffix = os_path.splitext(name) # http://stackoverflow.com/a/541394/3423324#extension elif url: # http://stackoverflow.com/a/18727481/3423324#how-to-extract-a-filename-from-a-url url = urlparse(url) name = os_path.basename(url.path) name, suffix = os_path.splitext(name) # end if if mime: import mimetypes suffix = mimetypes.guess_extension(mime) suffix = '.jpg' if suffix == '.jpe' else suffix # .jpe -> .jpg # end if if not suffix or not suffix.strip().lstrip("."): logger.debug("suffix was empty. Using '.blob'") suffix = ".blob" # end if name = "{filename}{suffix}".format(filename=name, suffix=suffix) return InputFileFromBlob, (blob,), dict(name=name, mime=mime) if path: return InputFileFromDisk, (path,), dict(mime=mime) if url: if prefer_local_download: return InputFileFromURL, (url,), dict(mime=mime) # end if # else -> so we wanna let telegram handle it if prefer_str: assert_type_or_raise(url, str, parameter_name='url') return str, (url,), dict() # end if return InputFileUseUrl, (url,), dict() # end if raise ValueError('Could not find a matching subclass. You might need to do it manually instead.')
Creates a new InputFile subclass instance fitting the given parameters. :param prefer_local_download: If `True`, we download the file and send it to telegram. This is the default. If `False`, we send Telegram just the URL, and they'll try to download it. :type prefer_local_download: bool :param prefer_str: Return just the `str` instead of a `InputFileUseFileID` or `InputFileUseUrl` object. :type prefer_str: bool :param create_instance: If we should return a instance ready to use (default), or the building parts being a tuple of `(class, args_tuple, kwargs_dict)`. Setting this to `False` is probably only ever required for internal usage by the :class:`InputFile` constructor which uses this very factory. :type create_instance: bool :returns: if `create_instance=True` it returns a instance of some InputFile subclass or a string, if `create_instance=False` it returns a tuple of the needed class, args and kwargs needed to create a instance. :rtype: InputFile|InputFileFromBlob|InputFileFromDisk|InputFileFromURL|str|tuple
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/files.py#L149-L228
luckydonald/pytgbot
pytgbot/api_types/receivable/passport.py
PassportData.to_array
def to_array(self): """ Serializes this PassportData to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(PassportData, self).to_array() array['data'] = self._as_array(self.data) # type list of EncryptedPassportElement array['credentials'] = self.credentials.to_array() # type EncryptedCredentials return array
python
def to_array(self): """ Serializes this PassportData to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(PassportData, self).to_array() array['data'] = self._as_array(self.data) # type list of EncryptedPassportElement array['credentials'] = self.credentials.to_array() # type EncryptedCredentials return array
Serializes this PassportData to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/passport.py#L63-L73
luckydonald/pytgbot
pytgbot/api_types/receivable/passport.py
PassportData.from_array
def from_array(array): """ Deserialize a new PassportData from a given dictionary. :return: new PassportData instance. :rtype: PassportData """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['data'] = EncryptedPassportElement.from_array_list(array.get('data'), list_level=1) data['credentials'] = EncryptedCredentials.from_array(array.get('credentials')) data['_raw'] = array return PassportData(**data)
python
def from_array(array): """ Deserialize a new PassportData from a given dictionary. :return: new PassportData instance. :rtype: PassportData """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['data'] = EncryptedPassportElement.from_array_list(array.get('data'), list_level=1) data['credentials'] = EncryptedCredentials.from_array(array.get('credentials')) data['_raw'] = array return PassportData(**data)
Deserialize a new PassportData from a given dictionary. :return: new PassportData instance. :rtype: PassportData
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/passport.py#L77-L94
luckydonald/pytgbot
pytgbot/api_types/receivable/passport.py
PassportFile.to_array
def to_array(self): """ Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(PassportFile, self).to_array() array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str array['file_size'] = int(self.file_size) # type int array['file_date'] = int(self.file_date) # type int return array
python
def to_array(self): """ Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(PassportFile, self).to_array() array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str array['file_size'] = int(self.file_size) # type int array['file_date'] = int(self.file_date) # type int return array
Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/passport.py#L186-L197
luckydonald/pytgbot
pytgbot/api_types/receivable/passport.py
EncryptedPassportElement.to_array
def to_array(self): """ Serializes this EncryptedPassportElement to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(EncryptedPassportElement, self).to_array() array['type'] = u(self.type) # py2: type unicode, py3: type str array['hash'] = u(self.hash) # py2: type unicode, py3: type str if self.data is not None: array['data'] = u(self.data) # py2: type unicode, py3: type str if self.phone_number is not None: array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str if self.email is not None: array['email'] = u(self.email) # py2: type unicode, py3: type str if self.files is not None: array['files'] = self._as_array(self.files) # type list of PassportFile if self.front_side is not None: array['front_side'] = self.front_side.to_array() # type PassportFile if self.reverse_side is not None: array['reverse_side'] = self.reverse_side.to_array() # type PassportFile if self.selfie is not None: array['selfie'] = self.selfie.to_array() # type PassportFile if self.translation is not None: array['translation'] = self._as_array(self.translation) # type list of PassportFile return array
python
def to_array(self): """ Serializes this EncryptedPassportElement to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(EncryptedPassportElement, self).to_array() array['type'] = u(self.type) # py2: type unicode, py3: type str array['hash'] = u(self.hash) # py2: type unicode, py3: type str if self.data is not None: array['data'] = u(self.data) # py2: type unicode, py3: type str if self.phone_number is not None: array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str if self.email is not None: array['email'] = u(self.email) # py2: type unicode, py3: type str if self.files is not None: array['files'] = self._as_array(self.files) # type list of PassportFile if self.front_side is not None: array['front_side'] = self.front_side.to_array() # type PassportFile if self.reverse_side is not None: array['reverse_side'] = self.reverse_side.to_array() # type PassportFile if self.selfie is not None: array['selfie'] = self.selfie.to_array() # type PassportFile if self.translation is not None: array['translation'] = self._as_array(self.translation) # type list of PassportFile return array
Serializes this EncryptedPassportElement to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/passport.py#L373-L401
luckydonald/pytgbot
pytgbot/api_types/receivable/passport.py
EncryptedPassportElement.from_array
def from_array(array): """ Deserialize a new EncryptedPassportElement from a given dictionary. :return: new EncryptedPassportElement instance. :rtype: EncryptedPassportElement """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['type'] = u(array.get('type')) data['hash'] = u(array.get('hash')) data['data'] = u(array.get('data')) if array.get('data') is not None else None data['phone_number'] = u(array.get('phone_number')) if array.get('phone_number') is not None else None data['email'] = u(array.get('email')) if array.get('email') is not None else None data['files'] = PassportFile.from_array_list(array.get('files'), list_level=1) if array.get('files') is not None else None data['front_side'] = PassportFile.from_array(array.get('front_side')) if array.get('front_side') is not None else None data['reverse_side'] = PassportFile.from_array(array.get('reverse_side')) if array.get('reverse_side') is not None else None data['selfie'] = PassportFile.from_array(array.get('selfie')) if array.get('selfie') is not None else None data['translation'] = PassportFile.from_array_list(array.get('translation'), list_level=1) if array.get('translation') is not None else None data['_raw'] = array return EncryptedPassportElement(**data)
python
def from_array(array): """ Deserialize a new EncryptedPassportElement from a given dictionary. :return: new EncryptedPassportElement instance. :rtype: EncryptedPassportElement """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['type'] = u(array.get('type')) data['hash'] = u(array.get('hash')) data['data'] = u(array.get('data')) if array.get('data') is not None else None data['phone_number'] = u(array.get('phone_number')) if array.get('phone_number') is not None else None data['email'] = u(array.get('email')) if array.get('email') is not None else None data['files'] = PassportFile.from_array_list(array.get('files'), list_level=1) if array.get('files') is not None else None data['front_side'] = PassportFile.from_array(array.get('front_side')) if array.get('front_side') is not None else None data['reverse_side'] = PassportFile.from_array(array.get('reverse_side')) if array.get('reverse_side') is not None else None data['selfie'] = PassportFile.from_array(array.get('selfie')) if array.get('selfie') is not None else None data['translation'] = PassportFile.from_array_list(array.get('translation'), list_level=1) if array.get('translation') is not None else None data['_raw'] = array return EncryptedPassportElement(**data)
Deserialize a new EncryptedPassportElement from a given dictionary. :return: new EncryptedPassportElement instance. :rtype: EncryptedPassportElement
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/passport.py#L405-L430
luckydonald/pytgbot
pytgbot/api_types/receivable/passport.py
EncryptedCredentials.to_array
def to_array(self): """ Serializes this EncryptedCredentials to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(EncryptedCredentials, self).to_array() array['data'] = u(self.data) # py2: type unicode, py3: type str array['hash'] = u(self.hash) # py2: type unicode, py3: type str array['secret'] = u(self.secret) # py2: type unicode, py3: type str return array
python
def to_array(self): """ Serializes this EncryptedCredentials to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(EncryptedCredentials, self).to_array() array['data'] = u(self.data) # py2: type unicode, py3: type str array['hash'] = u(self.hash) # py2: type unicode, py3: type str array['secret'] = u(self.secret) # py2: type unicode, py3: type str return array
Serializes this EncryptedCredentials to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/passport.py#L522-L533
luckydonald/pytgbot
pytgbot/api_types/receivable/passport.py
EncryptedCredentials.from_array
def from_array(array): """ Deserialize a new EncryptedCredentials from a given dictionary. :return: new EncryptedCredentials instance. :rtype: EncryptedCredentials """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['data'] = u(array.get('data')) data['hash'] = u(array.get('hash')) data['secret'] = u(array.get('secret')) data['_raw'] = array return EncryptedCredentials(**data)
python
def from_array(array): """ Deserialize a new EncryptedCredentials from a given dictionary. :return: new EncryptedCredentials instance. :rtype: EncryptedCredentials """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['data'] = u(array.get('data')) data['hash'] = u(array.get('hash')) data['secret'] = u(array.get('secret')) data['_raw'] = array return EncryptedCredentials(**data)
Deserialize a new EncryptedCredentials from a given dictionary. :return: new EncryptedCredentials instance. :rtype: EncryptedCredentials
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/passport.py#L537-L554
luckydonald/pytgbot
pytgbot/bot.py
Bot.get_updates
def get_updates(self, offset=None, limit=100, poll_timeout=0, allowed_updates=None, request_timeout=None, delta=timedelta(milliseconds=100), error_as_empty=False): """ Use this method to receive incoming updates using long polling. An Array of Update objects is returned. You can choose to set `error_as_empty` to `True` or `False`. If `error_as_empty` is set to `True`, it will log that exception as warning, and fake an empty result, intended for use in for loops. In case of such error (and only in such case) it contains an "exception" field. Ìt will look like this: `{"result": [], "exception": e}` This is useful if you want to use a for loop, but ignore Network related burps. If `error_as_empty` is set to `False` however, all `requests.RequestException` exceptions are normally raised. :keyword offset: (Optional) Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as :func:`get_updates` is called with an offset higher than its `update_id`. :type offset: int :param limit: Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100 :type limit: int :param poll_timeout: Timeout in seconds for long polling, e.g. how long we want to wait maximum. Defaults to 0, i.e. usual short polling. :type poll_timeout: int :param allowed_updates: List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used. Please note that this parameter doesn't affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. :type allowed_updates: list of str :param request_timeout: Timeout of the request. Not the long polling server side timeout. If not specified, it is set to `poll_timeout`+2. :type request_timeout: int :param delta: Wait minimal 'delta' seconds, between requests. Useful in a loop. :type delta: datetime. :param error_as_empty: If errors which subclasses `requests.RequestException` will be logged but not raised. Instead the returned DictObject will contain an "exception" field containing the exception occured, the "result" field will be an empty list `[]`. Defaults to `False`. :type error_as_empty: bool Returns: :return: An Array of Update objects is returned, or an empty array if there was an requests.RequestException and error_as_empty is set to True. :rtype: list of pytgbot.api_types.receivable.updates.Update """ from datetime import datetime assert(offset is None or isinstance(offset, int)) assert(limit is None or isinstance(limit, int)) assert(poll_timeout is None or isinstance(poll_timeout, int)) assert(allowed_updates is None or isinstance(allowed_updates, list)) if poll_timeout and not request_timeout is None: request_timeout = poll_timeout + 2 # end if if delta.total_seconds() > poll_timeout: now = datetime.now() if self._last_update - now < delta: wait = ((now - self._last_update) - delta).total_seconds() # can be 0.2 wait = 0 if wait < 0 else wait if wait != 0: logger.debug("Sleeping {i} seconds.".format(i=wait)) # end if sleep(wait) # end if # end if self._last_update = datetime.now() try: result = self.do( "getUpdates", offset=offset, limit=limit, timeout=poll_timeout, allowed_updates=allowed_updates, use_long_polling=poll_timeout != 0, request_timeout=request_timeout ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Update try: return Update.from_array_list(result, list_level=1) except TgApiParseException: logger.debug("Failed parsing as api_type Update", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result except (requests.RequestException, TgApiException) as e: if error_as_empty: logger.warn("Network related error happened in get_updates(), but will be ignored: " + str(e), exc_info=True) self._last_update = datetime.now() return DictObject(result=[], exception=e) else: raise
python
def get_updates(self, offset=None, limit=100, poll_timeout=0, allowed_updates=None, request_timeout=None, delta=timedelta(milliseconds=100), error_as_empty=False): """ Use this method to receive incoming updates using long polling. An Array of Update objects is returned. You can choose to set `error_as_empty` to `True` or `False`. If `error_as_empty` is set to `True`, it will log that exception as warning, and fake an empty result, intended for use in for loops. In case of such error (and only in such case) it contains an "exception" field. Ìt will look like this: `{"result": [], "exception": e}` This is useful if you want to use a for loop, but ignore Network related burps. If `error_as_empty` is set to `False` however, all `requests.RequestException` exceptions are normally raised. :keyword offset: (Optional) Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as :func:`get_updates` is called with an offset higher than its `update_id`. :type offset: int :param limit: Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100 :type limit: int :param poll_timeout: Timeout in seconds for long polling, e.g. how long we want to wait maximum. Defaults to 0, i.e. usual short polling. :type poll_timeout: int :param allowed_updates: List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used. Please note that this parameter doesn't affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. :type allowed_updates: list of str :param request_timeout: Timeout of the request. Not the long polling server side timeout. If not specified, it is set to `poll_timeout`+2. :type request_timeout: int :param delta: Wait minimal 'delta' seconds, between requests. Useful in a loop. :type delta: datetime. :param error_as_empty: If errors which subclasses `requests.RequestException` will be logged but not raised. Instead the returned DictObject will contain an "exception" field containing the exception occured, the "result" field will be an empty list `[]`. Defaults to `False`. :type error_as_empty: bool Returns: :return: An Array of Update objects is returned, or an empty array if there was an requests.RequestException and error_as_empty is set to True. :rtype: list of pytgbot.api_types.receivable.updates.Update """ from datetime import datetime assert(offset is None or isinstance(offset, int)) assert(limit is None or isinstance(limit, int)) assert(poll_timeout is None or isinstance(poll_timeout, int)) assert(allowed_updates is None or isinstance(allowed_updates, list)) if poll_timeout and not request_timeout is None: request_timeout = poll_timeout + 2 # end if if delta.total_seconds() > poll_timeout: now = datetime.now() if self._last_update - now < delta: wait = ((now - self._last_update) - delta).total_seconds() # can be 0.2 wait = 0 if wait < 0 else wait if wait != 0: logger.debug("Sleeping {i} seconds.".format(i=wait)) # end if sleep(wait) # end if # end if self._last_update = datetime.now() try: result = self.do( "getUpdates", offset=offset, limit=limit, timeout=poll_timeout, allowed_updates=allowed_updates, use_long_polling=poll_timeout != 0, request_timeout=request_timeout ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Update try: return Update.from_array_list(result, list_level=1) except TgApiParseException: logger.debug("Failed parsing as api_type Update", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result except (requests.RequestException, TgApiException) as e: if error_as_empty: logger.warn("Network related error happened in get_updates(), but will be ignored: " + str(e), exc_info=True) self._last_update = datetime.now() return DictObject(result=[], exception=e) else: raise
Use this method to receive incoming updates using long polling. An Array of Update objects is returned. You can choose to set `error_as_empty` to `True` or `False`. If `error_as_empty` is set to `True`, it will log that exception as warning, and fake an empty result, intended for use in for loops. In case of such error (and only in such case) it contains an "exception" field. Ìt will look like this: `{"result": [], "exception": e}` This is useful if you want to use a for loop, but ignore Network related burps. If `error_as_empty` is set to `False` however, all `requests.RequestException` exceptions are normally raised. :keyword offset: (Optional) Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as :func:`get_updates` is called with an offset higher than its `update_id`. :type offset: int :param limit: Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100 :type limit: int :param poll_timeout: Timeout in seconds for long polling, e.g. how long we want to wait maximum. Defaults to 0, i.e. usual short polling. :type poll_timeout: int :param allowed_updates: List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used. Please note that this parameter doesn't affect updates created before the call to the get_updates, so unwanted updates may be received for a short period of time. :type allowed_updates: list of str :param request_timeout: Timeout of the request. Not the long polling server side timeout. If not specified, it is set to `poll_timeout`+2. :type request_timeout: int :param delta: Wait minimal 'delta' seconds, between requests. Useful in a loop. :type delta: datetime. :param error_as_empty: If errors which subclasses `requests.RequestException` will be logged but not raised. Instead the returned DictObject will contain an "exception" field containing the exception occured, the "result" field will be an empty list `[]`. Defaults to `False`. :type error_as_empty: bool Returns: :return: An Array of Update objects is returned, or an empty array if there was an requests.RequestException and error_as_empty is set to True. :rtype: list of pytgbot.api_types.receivable.updates.Update
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/bot.py#L51-L152
luckydonald/pytgbot
pytgbot/bot.py
Bot.get_me
def get_me(self): """ A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a :class:`pytgbot.api_types.receivable.peer.User` object. https://core.telegram.org/bots/api#getme Returns: :return: Returns basic information about the bot in form of a User object :rtype: pytgbot.api_types.receivable.peer.User """ result = self.do("getMe") if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.peer import User try: return User.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type User", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
def get_me(self): """ A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a :class:`pytgbot.api_types.receivable.peer.User` object. https://core.telegram.org/bots/api#getme Returns: :return: Returns basic information about the bot in form of a User object :rtype: pytgbot.api_types.receivable.peer.User """ result = self.do("getMe") if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.peer import User try: return User.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type User", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a :class:`pytgbot.api_types.receivable.peer.User` object. https://core.telegram.org/bots/api#getme Returns: :return: Returns basic information about the bot in form of a User object :rtype: pytgbot.api_types.receivable.peer.User
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/bot.py#L296-L321
luckydonald/pytgbot
pytgbot/bot.py
Bot.forward_message
def forward_message(self, chat_id, from_chat_id, message_id, disable_notification=False): """ Use this method to forward messages of any kind. On success, the sent Message is returned. https://core.telegram.org/bots/api#forwardmessage Parameters: :param chat_id: Unique identifier for the target chat (chat id of user chat or group chat) or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param from_chat_id: Unique identifier for the chat where the original message was sent (id for chats or the channel's username in the format @channelusername) :type from_chat_id: int | str|unicode :param message_id: Message identifier in the chat specified in from_chat_id :type message_id: int Optional keyword parameters: :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: bool Returns: :return: On success, the sent Message is returned :rtype: pytgbot.api_types.receivable.updates.Message """ assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(from_chat_id, (int, unicode_type), parameter_name="from_chat_id") assert_type_or_raise(message_id, int, parameter_name="message_id") assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification") result = self.do( "forwardMessage", chat_id=chat_id, from_chat_id=from_chat_id, message_id=message_id, disable_notification=disable_notification ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
def forward_message(self, chat_id, from_chat_id, message_id, disable_notification=False): """ Use this method to forward messages of any kind. On success, the sent Message is returned. https://core.telegram.org/bots/api#forwardmessage Parameters: :param chat_id: Unique identifier for the target chat (chat id of user chat or group chat) or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param from_chat_id: Unique identifier for the chat where the original message was sent (id for chats or the channel's username in the format @channelusername) :type from_chat_id: int | str|unicode :param message_id: Message identifier in the chat specified in from_chat_id :type message_id: int Optional keyword parameters: :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: bool Returns: :return: On success, the sent Message is returned :rtype: pytgbot.api_types.receivable.updates.Message """ assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(from_chat_id, (int, unicode_type), parameter_name="from_chat_id") assert_type_or_raise(message_id, int, parameter_name="message_id") assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification") result = self.do( "forwardMessage", chat_id=chat_id, from_chat_id=from_chat_id, message_id=message_id, disable_notification=disable_notification ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
Use this method to forward messages of any kind. On success, the sent Message is returned. https://core.telegram.org/bots/api#forwardmessage Parameters: :param chat_id: Unique identifier for the target chat (chat id of user chat or group chat) or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param from_chat_id: Unique identifier for the chat where the original message was sent (id for chats or the channel's username in the format @channelusername) :type from_chat_id: int | str|unicode :param message_id: Message identifier in the chat specified in from_chat_id :type message_id: int Optional keyword parameters: :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: bool Returns: :return: On success, the sent Message is returned :rtype: pytgbot.api_types.receivable.updates.Message
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/bot.py#L404-L458
luckydonald/pytgbot
pytgbot/bot.py
Bot.send_media_group
def send_media_group(self, chat_id, media, disable_notification=None, reply_to_message_id=None): """ Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. https://core.telegram.org/bots/api#sendmediagroup Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param media: A array describing photos and videos to be sent, must include 2–10 items :type media: list of (pytgbot.api_types.sendable.input_media.InputMediaPhoto|pytgbot.api_types.sendable.input_media.InputMediaVideo) Optional keyword parameters: :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :type disable_notification: bool :param reply_to_message_id: If the messages are a reply, ID of the original message :type reply_to_message_id: int Returns: :return: On success, an array of the sent Messages is returned :rtype: Messages """ assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") from .api_types.sendable.input_media import InputMediaPhoto, InputMediaVideo files = {} new_media = [] assert_type_or_raise(media, list, parameter_name="media") for i, medium in enumerate(media): assert_type_or_raise(medium, InputMediaPhoto, InputMediaVideo, parameter_name="media[{i}]".format(i=i)) assert isinstance(medium, (InputMediaPhoto, InputMediaVideo)) new_medium, file = medium.get_request_data('pytgbot{i}'.format(i=i), full_data=True) logger.debug('InputMedia {} found.'.format(new_medium)) new_media.append(new_medium) if file: files.update(file) # end if # end for new_media = json.dumps(new_media) assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification") assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id") result = self.do( "sendMediaGroup", chat_id=chat_id, media=new_media, files=files, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) # no valid parsing so far if not isinstance(result, list): raise TgApiParseException("Could not parse result als list.") # See debug log for details! # end if from .api_types.receivable.updates import Message return [Message.from_array(msg) for msg in result] # parse them all as Message. raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
def send_media_group(self, chat_id, media, disable_notification=None, reply_to_message_id=None): """ Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. https://core.telegram.org/bots/api#sendmediagroup Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param media: A array describing photos and videos to be sent, must include 2–10 items :type media: list of (pytgbot.api_types.sendable.input_media.InputMediaPhoto|pytgbot.api_types.sendable.input_media.InputMediaVideo) Optional keyword parameters: :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :type disable_notification: bool :param reply_to_message_id: If the messages are a reply, ID of the original message :type reply_to_message_id: int Returns: :return: On success, an array of the sent Messages is returned :rtype: Messages """ assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") from .api_types.sendable.input_media import InputMediaPhoto, InputMediaVideo files = {} new_media = [] assert_type_or_raise(media, list, parameter_name="media") for i, medium in enumerate(media): assert_type_or_raise(medium, InputMediaPhoto, InputMediaVideo, parameter_name="media[{i}]".format(i=i)) assert isinstance(medium, (InputMediaPhoto, InputMediaVideo)) new_medium, file = medium.get_request_data('pytgbot{i}'.format(i=i), full_data=True) logger.debug('InputMedia {} found.'.format(new_medium)) new_media.append(new_medium) if file: files.update(file) # end if # end for new_media = json.dumps(new_media) assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification") assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id") result = self.do( "sendMediaGroup", chat_id=chat_id, media=new_media, files=files, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) # no valid parsing so far if not isinstance(result, list): raise TgApiParseException("Could not parse result als list.") # See debug log for details! # end if from .api_types.receivable.updates import Message return [Message.from_array(msg) for msg in result] # parse them all as Message. raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. https://core.telegram.org/bots/api#sendmediagroup Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param media: A array describing photos and videos to be sent, must include 2–10 items :type media: list of (pytgbot.api_types.sendable.input_media.InputMediaPhoto|pytgbot.api_types.sendable.input_media.InputMediaVideo) Optional keyword parameters: :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :type disable_notification: bool :param reply_to_message_id: If the messages are a reply, ID of the original message :type reply_to_message_id: int Returns: :return: On success, an array of the sent Messages is returned :rtype: Messages
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/bot.py#L1149-L1213
luckydonald/pytgbot
pytgbot/bot.py
Bot.answer_inline_query
def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, switch_pm_text=None, switch_pm_parameter=None): """ Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed. https://core.telegram.org/bots/api#answerinlinequery Parameters: :param inline_query_id: Unique identifier for the answered query :type inline_query_id: str|unicode :param results: A JSON-serialized array of results for the inline query :type results: list of pytgbot.api_types.sendable.inline.InlineQueryResult Optional keyword parameters: :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. :type cache_time: int :param is_personal: Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query :type is_personal: bool :param next_offset: Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. :type next_offset: str|unicode :param switch_pm_text: If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter :type switch_pm_text: str|unicode :param switch_pm_parameter: Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only `A-Z`, `a-z`, `0-9`, `_` and `-` are allowed. Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a "Connect your YouTube account" button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. :type switch_pm_parameter: str|unicode Returns: :return: On success, True is returned :rtype: bool """ assert_type_or_raise(inline_query_id, int, unicode_type, parameter_name="inline_query_id") if isinstance(inline_query_id, int): inline_query_id = u(inline_query_id) # end if assert isinstance(inline_query_id, unicode_type) assert_type_or_raise(results, list, tuple, InlineQueryResult, parameter_name="results") if isinstance(results, InlineQueryResult): results = [results] assert(isinstance(results, (list, tuple))) # list of InlineQueryResult result_objects = [] for result in results: if not isinstance(result, InlineQueryResult): # checks all elements of results raise ValueError("Parameter results is not list of InlineQueryResult") # end if result_objects.append(result.to_array()) # end for results assert_type_or_raise(cache_time, None, int, parameter_name="cache_time") assert_type_or_raise(is_personal, None, bool, parameter_name="is_personal") assert_type_or_raise(next_offset, None, unicode_type, str, int, parameter_name="next_offset") if next_offset is not None: assert(isinstance(next_offset, (str, unicode_type, int))) next_offset = u(next_offset) # end if assert_type_or_raise(switch_pm_text, None, unicode_type, parameter_name="switch_pm_text") assert_type_or_raise(switch_pm_parameter, None, unicode_type, parameter_name="switch_pm_parameter") result = self.do( "answerInlineQuery", inline_query_id=inline_query_id, results=json.dumps(result_objects), cache_time=cache_time, is_personal=is_personal, next_offset=next_offset, switch_pm_text=switch_pm_text, switch_pm_parameter=switch_pm_parameter ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
def answer_inline_query(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, switch_pm_text=None, switch_pm_parameter=None): """ Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed. https://core.telegram.org/bots/api#answerinlinequery Parameters: :param inline_query_id: Unique identifier for the answered query :type inline_query_id: str|unicode :param results: A JSON-serialized array of results for the inline query :type results: list of pytgbot.api_types.sendable.inline.InlineQueryResult Optional keyword parameters: :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. :type cache_time: int :param is_personal: Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query :type is_personal: bool :param next_offset: Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. :type next_offset: str|unicode :param switch_pm_text: If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter :type switch_pm_text: str|unicode :param switch_pm_parameter: Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only `A-Z`, `a-z`, `0-9`, `_` and `-` are allowed. Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a "Connect your YouTube account" button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. :type switch_pm_parameter: str|unicode Returns: :return: On success, True is returned :rtype: bool """ assert_type_or_raise(inline_query_id, int, unicode_type, parameter_name="inline_query_id") if isinstance(inline_query_id, int): inline_query_id = u(inline_query_id) # end if assert isinstance(inline_query_id, unicode_type) assert_type_or_raise(results, list, tuple, InlineQueryResult, parameter_name="results") if isinstance(results, InlineQueryResult): results = [results] assert(isinstance(results, (list, tuple))) # list of InlineQueryResult result_objects = [] for result in results: if not isinstance(result, InlineQueryResult): # checks all elements of results raise ValueError("Parameter results is not list of InlineQueryResult") # end if result_objects.append(result.to_array()) # end for results assert_type_or_raise(cache_time, None, int, parameter_name="cache_time") assert_type_or_raise(is_personal, None, bool, parameter_name="is_personal") assert_type_or_raise(next_offset, None, unicode_type, str, int, parameter_name="next_offset") if next_offset is not None: assert(isinstance(next_offset, (str, unicode_type, int))) next_offset = u(next_offset) # end if assert_type_or_raise(switch_pm_text, None, unicode_type, parameter_name="switch_pm_text") assert_type_or_raise(switch_pm_parameter, None, unicode_type, parameter_name="switch_pm_parameter") result = self.do( "answerInlineQuery", inline_query_id=inline_query_id, results=json.dumps(result_objects), cache_time=cache_time, is_personal=is_personal, next_offset=next_offset, switch_pm_text=switch_pm_text, switch_pm_parameter=switch_pm_parameter ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed. https://core.telegram.org/bots/api#answerinlinequery Parameters: :param inline_query_id: Unique identifier for the answered query :type inline_query_id: str|unicode :param results: A JSON-serialized array of results for the inline query :type results: list of pytgbot.api_types.sendable.inline.InlineQueryResult Optional keyword parameters: :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. :type cache_time: int :param is_personal: Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query :type is_personal: bool :param next_offset: Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. :type next_offset: str|unicode :param switch_pm_text: If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter :type switch_pm_text: str|unicode :param switch_pm_parameter: Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only `A-Z`, `a-z`, `0-9`, `_` and `-` are allowed. Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a "Connect your YouTube account" button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. :type switch_pm_parameter: str|unicode Returns: :return: On success, True is returned :rtype: bool
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/bot.py#L3286-L3392
luckydonald/pytgbot
pytgbot/bot.py
Bot.set_game_score
def set_game_score(self, user_id, score, force=False, disable_edit_message=False, chat_id=None, message_id=None, inline_message_id=None): """ Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. https://core.telegram.org/bots/api#setgamescore Parameters: :param user_id: User identifier :type user_id: int :param score: New score, must be non-negative :type score: int Optional keyword parameters: :param force: Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters :type force: bool :param disable_edit_message: Pass True, if the game message should not be automatically edited to include the current scoreboard :type disable_edit_message: bool :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat (or username of the target channel in the format @channelusername) :type chat_id: int :param message_id: Required if inline_message_id is not specified. Identifier of the sent message :type message_id: int :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message :type inline_message_id: str|unicode Returns: :return: On success, if the message was sent by the bot, returns the edited Message, otherwise returns True :rtype: pytgbot.api_types.receivable.updates.Message | bool """ assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(score, int, parameter_name="score") assert_type_or_raise(force, None, bool, parameter_name="force") assert_type_or_raise(disable_edit_message, None, bool, parameter_name="disable_edit_message") assert_type_or_raise(chat_id, None, int, parameter_name="chat_id") assert_type_or_raise(message_id, None, int, parameter_name="message_id") assert_type_or_raise(inline_message_id, None, unicode_type, parameter_name="inline_message_id") result = self.do("setGameScore", user_id=user_id, score=score, force=force, disable_edit_message=disable_edit_message, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
python
def set_game_score(self, user_id, score, force=False, disable_edit_message=False, chat_id=None, message_id=None, inline_message_id=None): """ Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. https://core.telegram.org/bots/api#setgamescore Parameters: :param user_id: User identifier :type user_id: int :param score: New score, must be non-negative :type score: int Optional keyword parameters: :param force: Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters :type force: bool :param disable_edit_message: Pass True, if the game message should not be automatically edited to include the current scoreboard :type disable_edit_message: bool :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat (or username of the target channel in the format @channelusername) :type chat_id: int :param message_id: Required if inline_message_id is not specified. Identifier of the sent message :type message_id: int :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message :type inline_message_id: str|unicode Returns: :return: On success, if the message was sent by the bot, returns the edited Message, otherwise returns True :rtype: pytgbot.api_types.receivable.updates.Message | bool """ assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(score, int, parameter_name="score") assert_type_or_raise(force, None, bool, parameter_name="force") assert_type_or_raise(disable_edit_message, None, bool, parameter_name="disable_edit_message") assert_type_or_raise(chat_id, None, int, parameter_name="chat_id") assert_type_or_raise(message_id, None, int, parameter_name="message_id") assert_type_or_raise(inline_message_id, None, unicode_type, parameter_name="inline_message_id") result = self.do("setGameScore", user_id=user_id, score=score, force=force, disable_edit_message=disable_edit_message, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import Message try: return Message.from_array(result) except TgApiParseException: logger.debug("Failed parsing as api_type Message", exc_info=True) # end try try: return from_array_list(bool, result, list_level=0, is_builtin=True) except TgApiParseException: logger.debug("Failed parsing as primitive bool", exc_info=True) # end try # no valid parsing so far raise TgApiParseException("Could not parse result.") # See debug log for details! # end if return_python_objects return result
Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. https://core.telegram.org/bots/api#setgamescore Parameters: :param user_id: User identifier :type user_id: int :param score: New score, must be non-negative :type score: int Optional keyword parameters: :param force: Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters :type force: bool :param disable_edit_message: Pass True, if the game message should not be automatically edited to include the current scoreboard :type disable_edit_message: bool :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat (or username of the target channel in the format @channelusername) :type chat_id: int :param message_id: Required if inline_message_id is not specified. Identifier of the sent message :type message_id: int :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message :type inline_message_id: str|unicode Returns: :return: On success, if the message was sent by the bot, returns the edited Message, otherwise returns True :rtype: pytgbot.api_types.receivable.updates.Message | bool
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/bot.py#L3759-L3833
luckydonald/pytgbot
pytgbot/bot.py
Bot._postprocess_request
def _postprocess_request(self, r): """ This converts the response to either the response or a parsed :class:`pytgbot.api_types.receivable.Receivable`. :param r: the request response :type r: requests.Response :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type. :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable """ from DictObject import DictObject import requests assert isinstance(r, requests.Response) try: logger.debug(r.json()) res = DictObject.objectify(r.json()) except Exception as e: raise TgApiResponseException('Parsing answer as json failed.', r, e) # end if res["response"] = r # TODO: does this failes on json lists? Does TG does that? # TG should always return an dict, with at least a status or something. if self.return_python_objects: if res.ok is not True: raise TgApiServerException( error_code=res.error_code if "error_code" in res else None, response=res.response if "response" in res else None, description=res.description if "description" in res else None, request=r.request ) # end if not ok if "result" not in res: raise TgApiParseException('Key "result" is missing.') # end if no result return res.result # end if return_python_objects return res
python
def _postprocess_request(self, r): """ This converts the response to either the response or a parsed :class:`pytgbot.api_types.receivable.Receivable`. :param r: the request response :type r: requests.Response :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type. :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable """ from DictObject import DictObject import requests assert isinstance(r, requests.Response) try: logger.debug(r.json()) res = DictObject.objectify(r.json()) except Exception as e: raise TgApiResponseException('Parsing answer as json failed.', r, e) # end if res["response"] = r # TODO: does this failes on json lists? Does TG does that? # TG should always return an dict, with at least a status or something. if self.return_python_objects: if res.ok is not True: raise TgApiServerException( error_code=res.error_code if "error_code" in res else None, response=res.response if "response" in res else None, description=res.description if "description" in res else None, request=r.request ) # end if not ok if "result" not in res: raise TgApiParseException('Key "result" is missing.') # end if no result return res.result # end if return_python_objects return res
This converts the response to either the response or a parsed :class:`pytgbot.api_types.receivable.Receivable`. :param r: the request response :type r: requests.Response :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type. :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/bot.py#L3964-L4001
luckydonald/pytgbot
pytgbot/bot.py
Bot._do_fileupload
def _do_fileupload(self, file_param_name, value, _command=None, _file_is_optional=False, **kwargs): """ :param file_param_name: For what field the file should be uploaded. :type file_param_name: str :param value: File to send. You can either pass a file_id as String to resend a file file that is already on the Telegram servers, or upload a new file, specifying the file path as :class:`pytgbot.api_types.sendable.files.InputFile`. If `_file_is_optional` is set to `True`, it can also be set to `None`. :type value: pytgbot.api_types.sendable.files.InputFile | str | None :param _command: Overwrite the command to be send. Default is to convert `file_param_name` to camel case (`"voice_note"` -> `"sendVoiceNote"`) :type _command: str|None :param _file_is_optional: If the file (`value`) is allowed to be None. :type _file_is_optional: bool :param kwargs: will get json encoded. :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type. :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable :raises TgApiTypeError, TgApiParseException, TgApiServerException: Everything from :meth:`Bot.do`, and :class:`TgApiTypeError` """ from .api_types.sendable.files import InputFile from luckydonaldUtils.encoding import unicode_type from luckydonaldUtils.encoding import to_native as n if value is None and _file_is_optional: # Is None but set optional, so do nothing. pass elif isinstance(value, str): kwargs[file_param_name] = str(value) elif isinstance(value, unicode_type): kwargs[file_param_name] = n(value) elif isinstance(value, InputFile): files = value.get_request_files(file_param_name) if "files" in kwargs and kwargs["files"]: # already are some files there, merge them. assert isinstance(kwargs["files"], dict), \ 'The files should be of type dict, but are of type {}.'.format(type(kwargs["files"])) for key in files.keys(): assert key not in kwargs["files"], '{key} would be overwritten!' kwargs["files"][key] = files[key] # end for else: # no files so far kwargs["files"] = files # end if else: raise TgApiTypeError("Parameter {key} is not type (str, {text_type}, {input_file_type}), but type {type}".format( key=file_param_name, type=type(value), input_file_type=InputFile, text_type=unicode_type)) # end if if not _command: # command as camelCase # "voice_note" -> "sendVoiceNote" # https://stackoverflow.com/a/10984923/3423324 command = re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), "send_" + file_param_name) else: command = _command # end def return self.do(command, **kwargs)
python
def _do_fileupload(self, file_param_name, value, _command=None, _file_is_optional=False, **kwargs): """ :param file_param_name: For what field the file should be uploaded. :type file_param_name: str :param value: File to send. You can either pass a file_id as String to resend a file file that is already on the Telegram servers, or upload a new file, specifying the file path as :class:`pytgbot.api_types.sendable.files.InputFile`. If `_file_is_optional` is set to `True`, it can also be set to `None`. :type value: pytgbot.api_types.sendable.files.InputFile | str | None :param _command: Overwrite the command to be send. Default is to convert `file_param_name` to camel case (`"voice_note"` -> `"sendVoiceNote"`) :type _command: str|None :param _file_is_optional: If the file (`value`) is allowed to be None. :type _file_is_optional: bool :param kwargs: will get json encoded. :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type. :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable :raises TgApiTypeError, TgApiParseException, TgApiServerException: Everything from :meth:`Bot.do`, and :class:`TgApiTypeError` """ from .api_types.sendable.files import InputFile from luckydonaldUtils.encoding import unicode_type from luckydonaldUtils.encoding import to_native as n if value is None and _file_is_optional: # Is None but set optional, so do nothing. pass elif isinstance(value, str): kwargs[file_param_name] = str(value) elif isinstance(value, unicode_type): kwargs[file_param_name] = n(value) elif isinstance(value, InputFile): files = value.get_request_files(file_param_name) if "files" in kwargs and kwargs["files"]: # already are some files there, merge them. assert isinstance(kwargs["files"], dict), \ 'The files should be of type dict, but are of type {}.'.format(type(kwargs["files"])) for key in files.keys(): assert key not in kwargs["files"], '{key} would be overwritten!' kwargs["files"][key] = files[key] # end for else: # no files so far kwargs["files"] = files # end if else: raise TgApiTypeError("Parameter {key} is not type (str, {text_type}, {input_file_type}), but type {type}".format( key=file_param_name, type=type(value), input_file_type=InputFile, text_type=unicode_type)) # end if if not _command: # command as camelCase # "voice_note" -> "sendVoiceNote" # https://stackoverflow.com/a/10984923/3423324 command = re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), "send_" + file_param_name) else: command = _command # end def return self.do(command, **kwargs)
:param file_param_name: For what field the file should be uploaded. :type file_param_name: str :param value: File to send. You can either pass a file_id as String to resend a file file that is already on the Telegram servers, or upload a new file, specifying the file path as :class:`pytgbot.api_types.sendable.files.InputFile`. If `_file_is_optional` is set to `True`, it can also be set to `None`. :type value: pytgbot.api_types.sendable.files.InputFile | str | None :param _command: Overwrite the command to be send. Default is to convert `file_param_name` to camel case (`"voice_note"` -> `"sendVoiceNote"`) :type _command: str|None :param _file_is_optional: If the file (`value`) is allowed to be None. :type _file_is_optional: bool :param kwargs: will get json encoded. :return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type. :rtype: DictObject.DictObject | pytgbot.api_types.receivable.Receivable :raises TgApiTypeError, TgApiParseException, TgApiServerException: Everything from :meth:`Bot.do`, and :class:`TgApiTypeError`
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/bot.py#L4004-L4064
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/sendable/payments.py
LabeledPrice.to_array
def to_array(self): """ Serializes this LabeledPrice to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(LabeledPrice, self).to_array() array['label'] = u(self.label) # py2: type unicode, py3: type str array['amount'] = int(self.amount) # type int return array
python
def to_array(self): """ Serializes this LabeledPrice to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(LabeledPrice, self).to_array() array['label'] = u(self.label) # py2: type unicode, py3: type str array['amount'] = int(self.amount) # type int return array
Serializes this LabeledPrice to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/payments.py#L53-L64
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/sendable/payments.py
LabeledPrice.from_array
def from_array(array): """ Deserialize a new LabeledPrice from a given dictionary. :return: new LabeledPrice instance. :rtype: LabeledPrice """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['label'] = u(array.get('label')) data['amount'] = int(array.get('amount')) instance = LabeledPrice(**data) instance._raw = array return instance
python
def from_array(array): """ Deserialize a new LabeledPrice from a given dictionary. :return: new LabeledPrice instance. :rtype: LabeledPrice """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['label'] = u(array.get('label')) data['amount'] = int(array.get('amount')) instance = LabeledPrice(**data) instance._raw = array return instance
Deserialize a new LabeledPrice from a given dictionary. :return: new LabeledPrice instance. :rtype: LabeledPrice
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/payments.py#L68-L86
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/sendable/payments.py
ShippingOption.to_array
def to_array(self): """ Serializes this ShippingOption to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ShippingOption, self).to_array() array['id'] = u(self.id) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str array['prices'] = self._as_array(self.prices) # type list of LabeledPrice return array
python
def to_array(self): """ Serializes this ShippingOption to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ShippingOption, self).to_array() array['id'] = u(self.id) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str array['prices'] = self._as_array(self.prices) # type list of LabeledPrice return array
Serializes this ShippingOption to a dictionary. :return: dictionary representation of this object. :rtype: dict
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/payments.py#L171-L185
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/sendable/payments.py
ShippingOption.from_array
def from_array(array): """ Deserialize a new ShippingOption from a given dictionary. :return: new ShippingOption instance. :rtype: ShippingOption """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.payments import LabeledPrice data = {} data['id'] = u(array.get('id')) data['title'] = u(array.get('title')) data['prices'] = LabeledPrice.from_array_list(array.get('prices'), list_level=1) instance = ShippingOption(**data) instance._raw = array return instance
python
def from_array(array): """ Deserialize a new ShippingOption from a given dictionary. :return: new ShippingOption instance. :rtype: ShippingOption """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.payments import LabeledPrice data = {} data['id'] = u(array.get('id')) data['title'] = u(array.get('title')) data['prices'] = LabeledPrice.from_array_list(array.get('prices'), list_level=1) instance = ShippingOption(**data) instance._raw = array return instance
Deserialize a new ShippingOption from a given dictionary. :return: new ShippingOption instance. :rtype: ShippingOption
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/sendable/payments.py#L189-L210
delph-in/pydelphin
delphin/itsdb.py
_prepare_target
def _prepare_target(ts, tables, buffer_size): """Clear tables affected by the processing.""" for tablename in tables: table = ts[tablename] table[:] = [] if buffer_size is not None and table.is_attached(): table.write(append=False)
python
def _prepare_target(ts, tables, buffer_size): """Clear tables affected by the processing.""" for tablename in tables: table = ts[tablename] table[:] = [] if buffer_size is not None and table.is_attached(): table.write(append=False)
Clear tables affected by the processing.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1289-L1295
delph-in/pydelphin
delphin/itsdb.py
_prepare_source
def _prepare_source(selector, source): """Normalize source rows and selectors.""" tablename, fields = get_data_specifier(selector) if len(fields) != 1: raise ItsdbError( 'Selector must specify exactly one data column: {}' .format(selector) ) if isinstance(source, TestSuite): if not tablename: tablename = source.relations.find(fields[0])[0] source = source[tablename] cols = list(source.fields.keys()) + fields return source, cols
python
def _prepare_source(selector, source): """Normalize source rows and selectors.""" tablename, fields = get_data_specifier(selector) if len(fields) != 1: raise ItsdbError( 'Selector must specify exactly one data column: {}' .format(selector) ) if isinstance(source, TestSuite): if not tablename: tablename = source.relations.find(fields[0])[0] source = source[tablename] cols = list(source.fields.keys()) + fields return source, cols
Normalize source rows and selectors.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1298-L1311
delph-in/pydelphin
delphin/itsdb.py
_add_record
def _add_record(table, data, buffer_size): """ Prepare and append a Record into its Table; flush to disk if necessary. """ fields = table.fields # remove any keys that aren't relation fields for invalid_key in set(data).difference([f.name for f in fields]): del data[invalid_key] table.append(Record.from_dict(fields, data)) # write if requested and possible if buffer_size is not None and table.is_attached(): # for now there isn't a public method to get the number of new # records, so use private members if (len(table) - 1) - table._last_synced_index > buffer_size: table.commit()
python
def _add_record(table, data, buffer_size): """ Prepare and append a Record into its Table; flush to disk if necessary. """ fields = table.fields # remove any keys that aren't relation fields for invalid_key in set(data).difference([f.name for f in fields]): del data[invalid_key] table.append(Record.from_dict(fields, data)) # write if requested and possible if buffer_size is not None and table.is_attached(): # for now there isn't a public method to get the number of new # records, so use private members if (len(table) - 1) - table._last_synced_index > buffer_size: table.commit()
Prepare and append a Record into its Table; flush to disk if necessary.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1314-L1328
delph-in/pydelphin
delphin/itsdb.py
get_data_specifier
def get_data_specifier(string): """ Return a tuple (table, col) for some [incr tsdb()] data specifier. For example:: item -> ('item', None) item:i-input -> ('item', ['i-input']) item:i-input@i-wf -> ('item', ['i-input', 'i-wf']) :i-input -> (None, ['i-input']) (otherwise) -> (None, None) """ match = data_specifier_re.match(string) if match is None: return (None, None) table = match.group('table') if table is not None: table = table.strip() cols = _split_cols(match.group('cols')) return (table, cols)
python
def get_data_specifier(string): """ Return a tuple (table, col) for some [incr tsdb()] data specifier. For example:: item -> ('item', None) item:i-input -> ('item', ['i-input']) item:i-input@i-wf -> ('item', ['i-input', 'i-wf']) :i-input -> (None, ['i-input']) (otherwise) -> (None, None) """ match = data_specifier_re.match(string) if match is None: return (None, None) table = match.group('table') if table is not None: table = table.strip() cols = _split_cols(match.group('cols')) return (table, cols)
Return a tuple (table, col) for some [incr tsdb()] data specifier. For example:: item -> ('item', None) item:i-input -> ('item', ['i-input']) item:i-input@i-wf -> ('item', ['i-input', 'i-wf']) :i-input -> (None, ['i-input']) (otherwise) -> (None, None)
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1335-L1353
delph-in/pydelphin
delphin/itsdb.py
decode_row
def decode_row(line, fields=None): """ Decode a raw line from a profile into a list of column values. Decoding involves splitting the line by the field delimiter (`"@"` by default) and unescaping special characters. If *fields* is given, cast the values into the datatype given by their respective Field object. Args: line: a raw line from a [incr tsdb()] profile. fields: a list or Relation object of Fields for the row Returns: A list of column values. """ cols = line.rstrip('\n').split(_field_delimiter) cols = list(map(unescape, cols)) if fields is not None: if len(cols) != len(fields): raise ItsdbError( 'Wrong number of fields: {} != {}' .format(len(cols), len(fields)) ) for i in range(len(cols)): col = cols[i] if col: field = fields[i] col = _cast_to_datatype(col, field) cols[i] = col return cols
python
def decode_row(line, fields=None): """ Decode a raw line from a profile into a list of column values. Decoding involves splitting the line by the field delimiter (`"@"` by default) and unescaping special characters. If *fields* is given, cast the values into the datatype given by their respective Field object. Args: line: a raw line from a [incr tsdb()] profile. fields: a list or Relation object of Fields for the row Returns: A list of column values. """ cols = line.rstrip('\n').split(_field_delimiter) cols = list(map(unescape, cols)) if fields is not None: if len(cols) != len(fields): raise ItsdbError( 'Wrong number of fields: {} != {}' .format(len(cols), len(fields)) ) for i in range(len(cols)): col = cols[i] if col: field = fields[i] col = _cast_to_datatype(col, field) cols[i] = col return cols
Decode a raw line from a profile into a list of column values. Decoding involves splitting the line by the field delimiter (`"@"` by default) and unescaping special characters. If *fields* is given, cast the values into the datatype given by their respective Field object. Args: line: a raw line from a [incr tsdb()] profile. fields: a list or Relation object of Fields for the row Returns: A list of column values.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1362-L1391
delph-in/pydelphin
delphin/itsdb.py
encode_row
def encode_row(fields): """ Encode a list of column values into a [incr tsdb()] profile line. Encoding involves escaping special characters for each value, then joining the values into a single string with the field delimiter (`"@"` by default). It does not fill in default values (see make_row()). Args: fields: a list of column values Returns: A [incr tsdb()]-encoded string """ # NOTE: str(f) only works for Python3 unicode_fields = [unicode(f) for f in fields] escaped_fields = map(escape, unicode_fields) return _field_delimiter.join(escaped_fields)
python
def encode_row(fields): """ Encode a list of column values into a [incr tsdb()] profile line. Encoding involves escaping special characters for each value, then joining the values into a single string with the field delimiter (`"@"` by default). It does not fill in default values (see make_row()). Args: fields: a list of column values Returns: A [incr tsdb()]-encoded string """ # NOTE: str(f) only works for Python3 unicode_fields = [unicode(f) for f in fields] escaped_fields = map(escape, unicode_fields) return _field_delimiter.join(escaped_fields)
Encode a list of column values into a [incr tsdb()] profile line. Encoding involves escaping special characters for each value, then joining the values into a single string with the field delimiter (`"@"` by default). It does not fill in default values (see make_row()). Args: fields: a list of column values Returns: A [incr tsdb()]-encoded string
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1418-L1435
delph-in/pydelphin
delphin/itsdb.py
_table_filename
def _table_filename(tbl_filename): """ Determine if the table path should end in .gz or not and return it. A .gz path is preferred only if it exists and is newer than any regular text file path. Raises: :class:`delphin.exceptions.ItsdbError`: when neither the .gz nor text file exist. """ tbl_filename = str(tbl_filename) # convert any Path objects txfn = _normalize_table_path(tbl_filename) gzfn = txfn + '.gz' if os.path.exists(txfn): if (os.path.exists(gzfn) and os.stat(gzfn).st_mtime > os.stat(txfn).st_mtime): tbl_filename = gzfn else: tbl_filename = txfn elif os.path.exists(gzfn): tbl_filename = gzfn else: raise ItsdbError( 'Table does not exist at {}(.gz)' .format(tbl_filename) ) return tbl_filename
python
def _table_filename(tbl_filename): """ Determine if the table path should end in .gz or not and return it. A .gz path is preferred only if it exists and is newer than any regular text file path. Raises: :class:`delphin.exceptions.ItsdbError`: when neither the .gz nor text file exist. """ tbl_filename = str(tbl_filename) # convert any Path objects txfn = _normalize_table_path(tbl_filename) gzfn = txfn + '.gz' if os.path.exists(txfn): if (os.path.exists(gzfn) and os.stat(gzfn).st_mtime > os.stat(txfn).st_mtime): tbl_filename = gzfn else: tbl_filename = txfn elif os.path.exists(gzfn): tbl_filename = gzfn else: raise ItsdbError( 'Table does not exist at {}(.gz)' .format(tbl_filename) ) return tbl_filename
Determine if the table path should end in .gz or not and return it. A .gz path is preferred only if it exists and is newer than any regular text file path. Raises: :class:`delphin.exceptions.ItsdbError`: when neither the .gz nor text file exist.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1478-L1508
delph-in/pydelphin
delphin/itsdb.py
_open_table
def _open_table(tbl_filename, encoding): """ Transparently open the compressed or text table file. Can be used as a context manager in a 'with' statement. """ path = _table_filename(tbl_filename) if path.endswith('.gz'): # gzip.open() cannot use mode='rt' until Python2.7 support # is gone; until then use TextIOWrapper gzfile = GzipFile(path, mode='r') gzfile.read1 = gzfile.read # Python2 hack with TextIOWrapper(gzfile, encoding=encoding) as f: yield f else: with io.open(path, encoding=encoding) as f: yield f
python
def _open_table(tbl_filename, encoding): """ Transparently open the compressed or text table file. Can be used as a context manager in a 'with' statement. """ path = _table_filename(tbl_filename) if path.endswith('.gz'): # gzip.open() cannot use mode='rt' until Python2.7 support # is gone; until then use TextIOWrapper gzfile = GzipFile(path, mode='r') gzfile.read1 = gzfile.read # Python2 hack with TextIOWrapper(gzfile, encoding=encoding) as f: yield f else: with io.open(path, encoding=encoding) as f: yield f
Transparently open the compressed or text table file. Can be used as a context manager in a 'with' statement.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1512-L1528
delph-in/pydelphin
delphin/itsdb.py
make_row
def make_row(row, fields): """ Encode a mapping of column name to values into a [incr tsdb()] profile line. The *fields* parameter determines what columns are used, and default values are provided if a column is missing from the mapping. Args: row: a mapping of column names to values fields: an iterable of :class:`Field` objects Returns: A [incr tsdb()]-encoded string """ if not hasattr(row, 'get'): row = {f.name: col for f, col in zip(fields, row)} row_fields = [] for f in fields: val = row.get(f.name, None) if val is None: val = str(f.default_value()) row_fields.append(val) return encode_row(row_fields)
python
def make_row(row, fields): """ Encode a mapping of column name to values into a [incr tsdb()] profile line. The *fields* parameter determines what columns are used, and default values are provided if a column is missing from the mapping. Args: row: a mapping of column names to values fields: an iterable of :class:`Field` objects Returns: A [incr tsdb()]-encoded string """ if not hasattr(row, 'get'): row = {f.name: col for f, col in zip(fields, row)} row_fields = [] for f in fields: val = row.get(f.name, None) if val is None: val = str(f.default_value()) row_fields.append(val) return encode_row(row_fields)
Encode a mapping of column name to values into a [incr tsdb()] profile line. The *fields* parameter determines what columns are used, and default values are provided if a column is missing from the mapping. Args: row: a mapping of column names to values fields: an iterable of :class:`Field` objects Returns: A [incr tsdb()]-encoded string
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1578-L1600
delph-in/pydelphin
delphin/itsdb.py
select_rows
def select_rows(cols, rows, mode='list', cast=True): """ Yield data selected from rows. It is sometimes useful to select a subset of data from a profile. This function selects the data in *cols* from *rows* and yields it in a form specified by *mode*. Possible values of *mode* are: ================== ================= ========================== mode description example `['i-id', 'i-wf']` ================== ================= ========================== `'list'` (default) a list of values `[10, 1]` `'dict'` col to value map `{'i-id': 10,'i-wf': 1}` `'row'` [incr tsdb()] row `'10@1'` ================== ================= ========================== Args: cols: an iterable of column names to select data for rows: the rows to select column data from mode: the form yielded data should take cast: if `True`, cast column values to their datatype (requires *rows* to be :class:`Record` objects) Yields: Selected data in the form specified by *mode*. """ mode = mode.lower() if mode == 'list': modecast = lambda cols, data: data elif mode == 'dict': modecast = lambda cols, data: dict(zip(cols, data)) elif mode == 'row': modecast = lambda cols, data: encode_row(data) else: raise ItsdbError('Invalid mode for select operation: {}\n' ' Valid options include: list, dict, row' .format(mode)) for row in rows: try: data = [row.get(c, cast=cast) for c in cols] except TypeError: data = [row.get(c) for c in cols] yield modecast(cols, data)
python
def select_rows(cols, rows, mode='list', cast=True): """ Yield data selected from rows. It is sometimes useful to select a subset of data from a profile. This function selects the data in *cols* from *rows* and yields it in a form specified by *mode*. Possible values of *mode* are: ================== ================= ========================== mode description example `['i-id', 'i-wf']` ================== ================= ========================== `'list'` (default) a list of values `[10, 1]` `'dict'` col to value map `{'i-id': 10,'i-wf': 1}` `'row'` [incr tsdb()] row `'10@1'` ================== ================= ========================== Args: cols: an iterable of column names to select data for rows: the rows to select column data from mode: the form yielded data should take cast: if `True`, cast column values to their datatype (requires *rows* to be :class:`Record` objects) Yields: Selected data in the form specified by *mode*. """ mode = mode.lower() if mode == 'list': modecast = lambda cols, data: data elif mode == 'dict': modecast = lambda cols, data: dict(zip(cols, data)) elif mode == 'row': modecast = lambda cols, data: encode_row(data) else: raise ItsdbError('Invalid mode for select operation: {}\n' ' Valid options include: list, dict, row' .format(mode)) for row in rows: try: data = [row.get(c, cast=cast) for c in cols] except TypeError: data = [row.get(c) for c in cols] yield modecast(cols, data)
Yield data selected from rows. It is sometimes useful to select a subset of data from a profile. This function selects the data in *cols* from *rows* and yields it in a form specified by *mode*. Possible values of *mode* are: ================== ================= ========================== mode description example `['i-id', 'i-wf']` ================== ================= ========================== `'list'` (default) a list of values `[10, 1]` `'dict'` col to value map `{'i-id': 10,'i-wf': 1}` `'row'` [incr tsdb()] row `'10@1'` ================== ================= ========================== Args: cols: an iterable of column names to select data for rows: the rows to select column data from mode: the form yielded data should take cast: if `True`, cast column values to their datatype (requires *rows* to be :class:`Record` objects) Yields: Selected data in the form specified by *mode*.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1603-L1645
delph-in/pydelphin
delphin/itsdb.py
match_rows
def match_rows(rows1, rows2, key, sort_keys=True): """ Yield triples of `(value, left_rows, right_rows)` where `left_rows` and `right_rows` are lists of rows that share the same column value for *key*. This means that both *rows1* and *rows2* must have a column with the same name *key*. .. warning:: Both *rows1* and *rows2* will exist in memory for this operation, so it is not recommended for very large tables on low-memory systems. Args: rows1: a :class:`Table` or list of :class:`Record` objects rows2: a :class:`Table` or list of :class:`Record` objects key (str): the column name on which to match sort_keys (bool): if `True`, yield matching rows sorted by the matched key instead of the original order """ matched = OrderedDict() for i, rows in enumerate([rows1, rows2]): for row in rows: val = row[key] try: data = matched[val] except KeyError: matched[val] = ([], []) data = matched[val] data[i].append(row) vals = matched.keys() if sort_keys: vals = sorted(vals, key=safe_int) for val in vals: left, right = matched[val] yield (val, left, right)
python
def match_rows(rows1, rows2, key, sort_keys=True): """ Yield triples of `(value, left_rows, right_rows)` where `left_rows` and `right_rows` are lists of rows that share the same column value for *key*. This means that both *rows1* and *rows2* must have a column with the same name *key*. .. warning:: Both *rows1* and *rows2* will exist in memory for this operation, so it is not recommended for very large tables on low-memory systems. Args: rows1: a :class:`Table` or list of :class:`Record` objects rows2: a :class:`Table` or list of :class:`Record` objects key (str): the column name on which to match sort_keys (bool): if `True`, yield matching rows sorted by the matched key instead of the original order """ matched = OrderedDict() for i, rows in enumerate([rows1, rows2]): for row in rows: val = row[key] try: data = matched[val] except KeyError: matched[val] = ([], []) data = matched[val] data[i].append(row) vals = matched.keys() if sort_keys: vals = sorted(vals, key=safe_int) for val in vals: left, right = matched[val] yield (val, left, right)
Yield triples of `(value, left_rows, right_rows)` where `left_rows` and `right_rows` are lists of rows that share the same column value for *key*. This means that both *rows1* and *rows2* must have a column with the same name *key*. .. warning:: Both *rows1* and *rows2* will exist in memory for this operation, so it is not recommended for very large tables on low-memory systems. Args: rows1: a :class:`Table` or list of :class:`Record` objects rows2: a :class:`Table` or list of :class:`Record` objects key (str): the column name on which to match sort_keys (bool): if `True`, yield matching rows sorted by the matched key instead of the original order
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1648-L1683
delph-in/pydelphin
delphin/itsdb.py
join
def join(table1, table2, on=None, how='inner', name=None): """ Join two tables and return the resulting Table object. Fields in the resulting table have their names prefixed with their corresponding table name. For example, when joining `item` and `parse` tables, the `i-input` field of the `item` table will be named `item:i-input` in the resulting Table. Pivot fields (those in *on*) are only stored once without the prefix. Both inner and left joins are possible by setting the *how* parameter to `inner` and `left`, respectively. .. warning:: Both *table2* and the resulting joined table will exist in memory for this operation, so it is not recommended for very large tables on low-memory systems. Args: table1 (:class:`Table`): the left table to join table2 (:class:`Table`): the right table to join on (str): the shared key to use for joining; if `None`, find shared keys using the schemata of the tables how (str): the method used for joining (`"inner"` or `"left"`) name (str): the name assigned to the resulting table """ if how not in ('inner', 'left'): ItsdbError('Only \'inner\' and \'left\' join methods are allowed.') # validate and normalize the pivot on = _join_pivot(on, table1, table2) # the fields of the joined table fields = _RelationJoin(table1.fields, table2.fields, on=on) # get key mappings to the right side (useful for inner and left joins) get_key = lambda rec: tuple(rec.get(k) for k in on) key_indices = set(table2.fields.index(k) for k in on) right = defaultdict(list) for rec in table2: right[get_key(rec)].append([c for i, c in enumerate(rec) if i not in key_indices]) # build joined table rfill = [f.default_value() for f in table2.fields if f.name not in on] joined = [] for lrec in table1: k = get_key(lrec) if how == 'left' or k in right: joined.extend(lrec + rrec for rrec in right.get(k, [rfill])) return Table(fields, joined)
python
def join(table1, table2, on=None, how='inner', name=None): """ Join two tables and return the resulting Table object. Fields in the resulting table have their names prefixed with their corresponding table name. For example, when joining `item` and `parse` tables, the `i-input` field of the `item` table will be named `item:i-input` in the resulting Table. Pivot fields (those in *on*) are only stored once without the prefix. Both inner and left joins are possible by setting the *how* parameter to `inner` and `left`, respectively. .. warning:: Both *table2* and the resulting joined table will exist in memory for this operation, so it is not recommended for very large tables on low-memory systems. Args: table1 (:class:`Table`): the left table to join table2 (:class:`Table`): the right table to join on (str): the shared key to use for joining; if `None`, find shared keys using the schemata of the tables how (str): the method used for joining (`"inner"` or `"left"`) name (str): the name assigned to the resulting table """ if how not in ('inner', 'left'): ItsdbError('Only \'inner\' and \'left\' join methods are allowed.') # validate and normalize the pivot on = _join_pivot(on, table1, table2) # the fields of the joined table fields = _RelationJoin(table1.fields, table2.fields, on=on) # get key mappings to the right side (useful for inner and left joins) get_key = lambda rec: tuple(rec.get(k) for k in on) key_indices = set(table2.fields.index(k) for k in on) right = defaultdict(list) for rec in table2: right[get_key(rec)].append([c for i, c in enumerate(rec) if i not in key_indices]) # build joined table rfill = [f.default_value() for f in table2.fields if f.name not in on] joined = [] for lrec in table1: k = get_key(lrec) if how == 'left' or k in right: joined.extend(lrec + rrec for rrec in right.get(k, [rfill])) return Table(fields, joined)
Join two tables and return the resulting Table object. Fields in the resulting table have their names prefixed with their corresponding table name. For example, when joining `item` and `parse` tables, the `i-input` field of the `item` table will be named `item:i-input` in the resulting Table. Pivot fields (those in *on*) are only stored once without the prefix. Both inner and left joins are possible by setting the *how* parameter to `inner` and `left`, respectively. .. warning:: Both *table2* and the resulting joined table will exist in memory for this operation, so it is not recommended for very large tables on low-memory systems. Args: table1 (:class:`Table`): the left table to join table2 (:class:`Table`): the right table to join on (str): the shared key to use for joining; if `None`, find shared keys using the schemata of the tables how (str): the method used for joining (`"inner"` or `"left"`) name (str): the name assigned to the resulting table
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1686-L1734
delph-in/pydelphin
delphin/itsdb.py
default_value
def default_value(fieldname, datatype): """ Return the default value for a column. If the column name (e.g. *i-wf*) is defined to have an idiosyncratic value, that value is returned. Otherwise the default value for the column's datatype is returned. Args: fieldname: the column name (e.g. `i-wf`) datatype: the datatype of the column (e.g. `:integer`) Returns: The default value for the column. .. deprecated:: v0.7.0 """ if fieldname in tsdb_coded_attributes: return str(tsdb_coded_attributes[fieldname]) else: return _default_datatype_values.get(datatype, '')
python
def default_value(fieldname, datatype): """ Return the default value for a column. If the column name (e.g. *i-wf*) is defined to have an idiosyncratic value, that value is returned. Otherwise the default value for the column's datatype is returned. Args: fieldname: the column name (e.g. `i-wf`) datatype: the datatype of the column (e.g. `:integer`) Returns: The default value for the column. .. deprecated:: v0.7.0 """ if fieldname in tsdb_coded_attributes: return str(tsdb_coded_attributes[fieldname]) else: return _default_datatype_values.get(datatype, '')
Return the default value for a column. If the column name (e.g. *i-wf*) is defined to have an idiosyncratic value, that value is returned. Otherwise the default value for the column's datatype is returned. Args: fieldname: the column name (e.g. `i-wf`) datatype: the datatype of the column (e.g. `:integer`) Returns: The default value for the column. .. deprecated:: v0.7.0
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1772-L1791
delph-in/pydelphin
delphin/itsdb.py
make_skeleton
def make_skeleton(path, relations, item_rows, gzip=False): """ Instantiate a new profile skeleton (only the relations file and item file) from an existing relations file and a list of rows for the item table. For standard relations files, it is suggested to have, as a minimum, the `i-id` and `i-input` fields in the item rows. Args: path: the destination directory of the skeleton---must not already exist, as it will be created relations: the path to the relations file item_rows: the rows to use for the item file gzip: if `True`, the item file will be compressed Returns: An ItsdbProfile containing the skeleton data (but the profile data will already have been written to disk). Raises: :class:`delphin.exceptions.ItsdbError`: if the destination directory could not be created. .. deprecated:: v0.7.0 """ try: os.makedirs(path) except OSError: raise ItsdbError('Path already exists: {}.'.format(path)) import shutil shutil.copyfile(relations, os.path.join(path, _relations_filename)) prof = ItsdbProfile(path, index=False) prof.write_table('item', item_rows, gzip=gzip) return prof
python
def make_skeleton(path, relations, item_rows, gzip=False): """ Instantiate a new profile skeleton (only the relations file and item file) from an existing relations file and a list of rows for the item table. For standard relations files, it is suggested to have, as a minimum, the `i-id` and `i-input` fields in the item rows. Args: path: the destination directory of the skeleton---must not already exist, as it will be created relations: the path to the relations file item_rows: the rows to use for the item file gzip: if `True`, the item file will be compressed Returns: An ItsdbProfile containing the skeleton data (but the profile data will already have been written to disk). Raises: :class:`delphin.exceptions.ItsdbError`: if the destination directory could not be created. .. deprecated:: v0.7.0 """ try: os.makedirs(path) except OSError: raise ItsdbError('Path already exists: {}.'.format(path)) import shutil shutil.copyfile(relations, os.path.join(path, _relations_filename)) prof = ItsdbProfile(path, index=False) prof.write_table('item', item_rows, gzip=gzip) return prof
Instantiate a new profile skeleton (only the relations file and item file) from an existing relations file and a list of rows for the item table. For standard relations files, it is suggested to have, as a minimum, the `i-id` and `i-input` fields in the item rows. Args: path: the destination directory of the skeleton---must not already exist, as it will be created relations: the path to the relations file item_rows: the rows to use for the item file gzip: if `True`, the item file will be compressed Returns: An ItsdbProfile containing the skeleton data (but the profile data will already have been written to disk). Raises: :class:`delphin.exceptions.ItsdbError`: if the destination directory could not be created. .. deprecated:: v0.7.0
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1795-L1827
delph-in/pydelphin
delphin/itsdb.py
filter_rows
def filter_rows(filters, rows): """ Yield rows matching all applicable filters. Filter functions have binary arity (e.g. `filter(row, col)`) where the first parameter is the dictionary of row data, and the second parameter is the data at one particular column. Args: filters: a tuple of (cols, filter_func) where filter_func will be tested (filter_func(row, col)) for each col in cols where col exists in the row rows: an iterable of rows to filter Yields: Rows matching all applicable filters .. deprecated:: v0.7.0 """ for row in rows: if all(condition(row, row.get(col)) for (cols, condition) in filters for col in cols if col is None or col in row): yield row
python
def filter_rows(filters, rows): """ Yield rows matching all applicable filters. Filter functions have binary arity (e.g. `filter(row, col)`) where the first parameter is the dictionary of row data, and the second parameter is the data at one particular column. Args: filters: a tuple of (cols, filter_func) where filter_func will be tested (filter_func(row, col)) for each col in cols where col exists in the row rows: an iterable of rows to filter Yields: Rows matching all applicable filters .. deprecated:: v0.7.0 """ for row in rows: if all(condition(row, row.get(col)) for (cols, condition) in filters for col in cols if col is None or col in row): yield row
Yield rows matching all applicable filters. Filter functions have binary arity (e.g. `filter(row, col)`) where the first parameter is the dictionary of row data, and the second parameter is the data at one particular column. Args: filters: a tuple of (cols, filter_func) where filter_func will be tested (filter_func(row, col)) for each col in cols where col exists in the row rows: an iterable of rows to filter Yields: Rows matching all applicable filters .. deprecated:: v0.7.0
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1831-L1854
delph-in/pydelphin
delphin/itsdb.py
apply_rows
def apply_rows(applicators, rows): """ Yield rows after applying the applicator functions to them. Applicators are simple unary functions that return a value, and that value is stored in the yielded row. E.g. `row[col] = applicator(row[col])`. These are useful to, e.g., cast strings to numeric datatypes, to convert formats stored in a cell, extract features for machine learning, and so on. Args: applicators: a tuple of (cols, applicator) where the applicator will be applied to each col in cols rows: an iterable of rows for applicators to be called on Yields: Rows with specified column values replaced with the results of the applicators .. deprecated:: v0.7.0 """ for row in rows: for (cols, function) in applicators: for col in (cols or []): value = row.get(col, '') row[col] = function(row, value) yield row
python
def apply_rows(applicators, rows): """ Yield rows after applying the applicator functions to them. Applicators are simple unary functions that return a value, and that value is stored in the yielded row. E.g. `row[col] = applicator(row[col])`. These are useful to, e.g., cast strings to numeric datatypes, to convert formats stored in a cell, extract features for machine learning, and so on. Args: applicators: a tuple of (cols, applicator) where the applicator will be applied to each col in cols rows: an iterable of rows for applicators to be called on Yields: Rows with specified column values replaced with the results of the applicators .. deprecated:: v0.7.0 """ for row in rows: for (cols, function) in applicators: for col in (cols or []): value = row.get(col, '') row[col] = function(row, value) yield row
Yield rows after applying the applicator functions to them. Applicators are simple unary functions that return a value, and that value is stored in the yielded row. E.g. `row[col] = applicator(row[col])`. These are useful to, e.g., cast strings to numeric datatypes, to convert formats stored in a cell, extract features for machine learning, and so on. Args: applicators: a tuple of (cols, applicator) where the applicator will be applied to each col in cols rows: an iterable of rows for applicators to be called on Yields: Rows with specified column values replaced with the results of the applicators .. deprecated:: v0.7.0
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L1858-L1883
delph-in/pydelphin
delphin/itsdb.py
Field.default_value
def default_value(self): """Get the default value of the field.""" if self.name in tsdb_coded_attributes: return tsdb_coded_attributes[self.name] elif self.datatype == ':integer': return -1 else: return ''
python
def default_value(self): """Get the default value of the field.""" if self.name in tsdb_coded_attributes: return tsdb_coded_attributes[self.name] elif self.datatype == ':integer': return -1 else: return ''
Get the default value of the field.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L183-L190
delph-in/pydelphin
delphin/itsdb.py
Relation.keys
def keys(self): """Return the tuple of field names of key fields.""" keys = self._keys if keys is None: keys = tuple(self[i].name for i in self.key_indices) return keys
python
def keys(self): """Return the tuple of field names of key fields.""" keys = self._keys if keys is None: keys = tuple(self[i].name for i in self.key_indices) return keys
Return the tuple of field names of key fields.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L219-L224
delph-in/pydelphin
delphin/itsdb.py
Relations.from_file
def from_file(cls, source): """Instantiate Relations from a relations file.""" if hasattr(source, 'read'): relations = cls.from_string(source.read()) else: with open(source) as f: relations = cls.from_string(f.read()) return relations
python
def from_file(cls, source): """Instantiate Relations from a relations file.""" if hasattr(source, 'read'): relations = cls.from_string(source.read()) else: with open(source) as f: relations = cls.from_string(f.read()) return relations
Instantiate Relations from a relations file.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L324-L331
delph-in/pydelphin
delphin/itsdb.py
Relations.from_string
def from_string(cls, s): """Instantiate Relations from a relations string.""" tables = [] seen = set() current_table = None lines = list(reversed(s.splitlines())) # to pop() in right order while lines: line = lines.pop().strip() table_m = re.match(r'^(?P<table>\w.+):$', line) field_m = re.match(r'\s*(?P<name>\S+)' r'(\s+(?P<attrs>[^#]+))?' r'(\s*#\s*(?P<comment>.*)$)?', line) if table_m is not None: table_name = table_m.group('table') if table_name in seen: raise ItsdbError( 'Table {} already defined.'.format(table_name) ) current_table = (table_name, []) tables.append(current_table) seen.add(table_name) elif field_m is not None and current_table is not None: name = field_m.group('name') attrs = field_m.group('attrs').split() datatype = attrs.pop(0) key = ':key' in attrs partial = ':partial' in attrs comment = field_m.group('comment') current_table[1].append( Field(name, datatype, key, partial, comment) ) elif line != '': raise ItsdbError('Invalid line: ' + line) return cls(tables)
python
def from_string(cls, s): """Instantiate Relations from a relations string.""" tables = [] seen = set() current_table = None lines = list(reversed(s.splitlines())) # to pop() in right order while lines: line = lines.pop().strip() table_m = re.match(r'^(?P<table>\w.+):$', line) field_m = re.match(r'\s*(?P<name>\S+)' r'(\s+(?P<attrs>[^#]+))?' r'(\s*#\s*(?P<comment>.*)$)?', line) if table_m is not None: table_name = table_m.group('table') if table_name in seen: raise ItsdbError( 'Table {} already defined.'.format(table_name) ) current_table = (table_name, []) tables.append(current_table) seen.add(table_name) elif field_m is not None and current_table is not None: name = field_m.group('name') attrs = field_m.group('attrs').split() datatype = attrs.pop(0) key = ':key' in attrs partial = ':partial' in attrs comment = field_m.group('comment') current_table[1].append( Field(name, datatype, key, partial, comment) ) elif line != '': raise ItsdbError('Invalid line: ' + line) return cls(tables)
Instantiate Relations from a relations string.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L334-L368
delph-in/pydelphin
delphin/itsdb.py
Relations.find
def find(self, fieldname): """ Return the list of tables that define the field *fieldname*. """ tablename, _, column = fieldname.rpartition(':') if tablename and tablename in self._field_map[column]: return tablename else: return self._field_map[fieldname]
python
def find(self, fieldname): """ Return the list of tables that define the field *fieldname*. """ tablename, _, column = fieldname.rpartition(':') if tablename and tablename in self._field_map[column]: return tablename else: return self._field_map[fieldname]
Return the list of tables that define the field *fieldname*.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L395-L403
delph-in/pydelphin
delphin/itsdb.py
Relations.path
def path(self, source, target): """ Find the path of id fields connecting two tables. This is just a basic breadth-first-search. The relations file should be small enough to not be a problem. Returns: list: (table, fieldname) pairs describing the path from the source to target tables Raises: :class:`delphin.exceptions.ItsdbError`: when no path is found Example: >>> relations.path('item', 'result') [('parse', 'i-id'), ('result', 'parse-id')] >>> relations.path('parse', 'item') [('item', 'i-id')] >>> relations.path('item', 'item') [] """ visited = set(source.split('+')) # split on + for joins targets = set(target.split('+')) - visited # ensure sources and targets exists for tablename in visited.union(targets): self[tablename] # base case; nothing to do if len(targets) == 0: return [] paths = [[(tablename, None)] for tablename in visited] while True: newpaths = [] for path in paths: laststep, pivot = path[-1] if laststep in targets: return path[1:] else: for key in self[laststep].keys(): for step in set(self.find(key)) - visited: visited.add(step) newpaths.append(path + [(step, key)]) if newpaths: paths = newpaths else: break raise ItsdbError('no relation path found from {} to {}' .format(source, target))
python
def path(self, source, target): """ Find the path of id fields connecting two tables. This is just a basic breadth-first-search. The relations file should be small enough to not be a problem. Returns: list: (table, fieldname) pairs describing the path from the source to target tables Raises: :class:`delphin.exceptions.ItsdbError`: when no path is found Example: >>> relations.path('item', 'result') [('parse', 'i-id'), ('result', 'parse-id')] >>> relations.path('parse', 'item') [('item', 'i-id')] >>> relations.path('item', 'item') [] """ visited = set(source.split('+')) # split on + for joins targets = set(target.split('+')) - visited # ensure sources and targets exists for tablename in visited.union(targets): self[tablename] # base case; nothing to do if len(targets) == 0: return [] paths = [[(tablename, None)] for tablename in visited] while True: newpaths = [] for path in paths: laststep, pivot = path[-1] if laststep in targets: return path[1:] else: for key in self[laststep].keys(): for step in set(self.find(key)) - visited: visited.add(step) newpaths.append(path + [(step, key)]) if newpaths: paths = newpaths else: break raise ItsdbError('no relation path found from {} to {}' .format(source, target))
Find the path of id fields connecting two tables. This is just a basic breadth-first-search. The relations file should be small enough to not be a problem. Returns: list: (table, fieldname) pairs describing the path from the source to target tables Raises: :class:`delphin.exceptions.ItsdbError`: when no path is found Example: >>> relations.path('item', 'result') [('parse', 'i-id'), ('result', 'parse-id')] >>> relations.path('parse', 'item') [('item', 'i-id')] >>> relations.path('item', 'item') []
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L405-L452
delph-in/pydelphin
delphin/itsdb.py
Record._make
def _make(cls, fields, iterable, table, rowid): """ Create a Record bound to a :class:`Table`. This is a helper method for creating Records from rows of a Table that is attached to a file. It is not meant to be called directly. It specifies the row number and a weak reference to the Table object so that when the Record is modified it is kept in the Table's in-memory list (see Record.__setitem__()), otherwise the changes would not be retained the next time the record is requested from the Table. The use of a weak reference to the Table is to avoid a circular reference and thus allow it to be properly garbage collected. """ record = cls(fields, iterable) record._tableref = weakref.ref(table) record._rowid = rowid return record
python
def _make(cls, fields, iterable, table, rowid): """ Create a Record bound to a :class:`Table`. This is a helper method for creating Records from rows of a Table that is attached to a file. It is not meant to be called directly. It specifies the row number and a weak reference to the Table object so that when the Record is modified it is kept in the Table's in-memory list (see Record.__setitem__()), otherwise the changes would not be retained the next time the record is requested from the Table. The use of a weak reference to the Table is to avoid a circular reference and thus allow it to be properly garbage collected. """ record = cls(fields, iterable) record._tableref = weakref.ref(table) record._rowid = rowid return record
Create a Record bound to a :class:`Table`. This is a helper method for creating Records from rows of a Table that is attached to a file. It is not meant to be called directly. It specifies the row number and a weak reference to the Table object so that when the Record is modified it is kept in the Table's in-memory list (see Record.__setitem__()), otherwise the changes would not be retained the next time the record is requested from the Table. The use of a weak reference to the Table is to avoid a circular reference and thus allow it to be properly garbage collected.
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L497-L514
delph-in/pydelphin
delphin/itsdb.py
Record.from_dict
def from_dict(cls, fields, mapping): """ Create a Record from a dictionary of field mappings. The *fields* object is used to determine the column indices of fields in the mapping. Args: fields: the Relation schema for the table of this record mapping: a dictionary or other mapping from field names to column values Returns: a :class:`Record` object """ iterable = [None] * len(fields) for key, value in mapping.items(): try: index = fields.index(key) except KeyError: raise ItsdbError('Invalid field name(s): ' + key) iterable[index] = value return cls(fields, iterable)
python
def from_dict(cls, fields, mapping): """ Create a Record from a dictionary of field mappings. The *fields* object is used to determine the column indices of fields in the mapping. Args: fields: the Relation schema for the table of this record mapping: a dictionary or other mapping from field names to column values Returns: a :class:`Record` object """ iterable = [None] * len(fields) for key, value in mapping.items(): try: index = fields.index(key) except KeyError: raise ItsdbError('Invalid field name(s): ' + key) iterable[index] = value return cls(fields, iterable)
Create a Record from a dictionary of field mappings. The *fields* object is used to determine the column indices of fields in the mapping. Args: fields: the Relation schema for the table of this record mapping: a dictionary or other mapping from field names to column values Returns: a :class:`Record` object
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L517-L538
delph-in/pydelphin
delphin/itsdb.py
Record.get
def get(self, key, default=None, cast=True): """ Return the field data given by field name *key*. Args: key: the field name of the data to return default: the value to return if *key* is not in the row """ tablename, _, key = key.rpartition(':') if tablename and tablename not in self.fields.name.split('+'): raise ItsdbError('column requested from wrong table: {}' .format(tablename)) try: index = self.fields.index(key) value = list.__getitem__(self, index) except (KeyError, IndexError): value = default else: if cast: field = self.fields[index] value = _cast_to_datatype(value, field) return value
python
def get(self, key, default=None, cast=True): """ Return the field data given by field name *key*. Args: key: the field name of the data to return default: the value to return if *key* is not in the row """ tablename, _, key = key.rpartition(':') if tablename and tablename not in self.fields.name.split('+'): raise ItsdbError('column requested from wrong table: {}' .format(tablename)) try: index = self.fields.index(key) value = list.__getitem__(self, index) except (KeyError, IndexError): value = default else: if cast: field = self.fields[index] value = _cast_to_datatype(value, field) return value
Return the field data given by field name *key*. Args: key: the field name of the data to return default: the value to return if *key* is not in the row
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L581-L602