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
|
---|---|---|---|---|---|---|---|
Alir3z4/python-currencies | currencies/__init__.py | Currency.get_money_with_currency_format | def get_money_with_currency_format(self, amount):
"""
:type amount: int or float or str
Usage:
>>> currency = Currency('USD')
>>> currency.get_money_with_currency_format(13)
>>> '$13 USD'
>>> currency.get_money_with_currency_format(13.99)
>>> '$13.99 USD'
>>> currency.get_money_with_currency_format('13,2313,33')
>>> '$13,2313,33 USD'
:rtype: str
"""
return self.money_formats[
self.get_money_currency()
]['money_with_currency_format'].format(amount=amount) | python | def get_money_with_currency_format(self, amount):
"""
:type amount: int or float or str
Usage:
>>> currency = Currency('USD')
>>> currency.get_money_with_currency_format(13)
>>> '$13 USD'
>>> currency.get_money_with_currency_format(13.99)
>>> '$13.99 USD'
>>> currency.get_money_with_currency_format('13,2313,33')
>>> '$13,2313,33 USD'
:rtype: str
"""
return self.money_formats[
self.get_money_currency()
]['money_with_currency_format'].format(amount=amount) | :type amount: int or float or str
Usage:
>>> currency = Currency('USD')
>>> currency.get_money_with_currency_format(13)
>>> '$13 USD'
>>> currency.get_money_with_currency_format(13.99)
>>> '$13.99 USD'
>>> currency.get_money_with_currency_format('13,2313,33')
>>> '$13,2313,33 USD'
:rtype: str | https://github.com/Alir3z4/python-currencies/blob/f8790c4da5df405bd23c63c0d2b02a417424d835/currencies/__init__.py#L67-L84 |
napalm-automation-community/napalm-fortios | napalm_fortios/fortios.py | FortiOSDriver.get_config | def get_config(self, retrieve="all"):
"""get_config implementation for FortiOS."""
get_startup = retrieve == "all" or retrieve == "startup"
get_running = retrieve == "all" or retrieve == "running"
get_candidate = retrieve == "all" or retrieve == "candidate"
if retrieve == "all" or get_running:
result = self._execute_command_with_vdom('show')
text_result = '\n'.join(result)
return {
'startup': u"",
'running': py23_compat.text_type(text_result),
'candidate': u"",
}
elif get_startup or get_candidate:
return {
'startup': u"",
'running': u"",
'candidate': u"",
} | python | def get_config(self, retrieve="all"):
"""get_config implementation for FortiOS."""
get_startup = retrieve == "all" or retrieve == "startup"
get_running = retrieve == "all" or retrieve == "running"
get_candidate = retrieve == "all" or retrieve == "candidate"
if retrieve == "all" or get_running:
result = self._execute_command_with_vdom('show')
text_result = '\n'.join(result)
return {
'startup': u"",
'running': py23_compat.text_type(text_result),
'candidate': u"",
}
elif get_startup or get_candidate:
return {
'startup': u"",
'running': u"",
'candidate': u"",
} | get_config implementation for FortiOS. | https://github.com/napalm-automation-community/napalm-fortios/blob/7cb0723b079ab523211d98751e15bf148a9a69b2/napalm_fortios/fortios.py#L162-L183 |
JohnDoee/deluge-client | deluge_client/client.py | DelugeRPCClient.connect | def connect(self):
"""
Connects to the Deluge instance
"""
self._connect()
logger.debug('Connected to Deluge, detecting daemon version')
self._detect_deluge_version()
logger.debug('Daemon version {} detected, logging in'.format(self.deluge_version))
if self.deluge_version == 2:
result = self.call('daemon.login', self.username, self.password, client_version='deluge-client')
else:
result = self.call('daemon.login', self.username, self.password)
logger.debug('Logged in with value %r' % result)
self.connected = True | python | def connect(self):
"""
Connects to the Deluge instance
"""
self._connect()
logger.debug('Connected to Deluge, detecting daemon version')
self._detect_deluge_version()
logger.debug('Daemon version {} detected, logging in'.format(self.deluge_version))
if self.deluge_version == 2:
result = self.call('daemon.login', self.username, self.password, client_version='deluge-client')
else:
result = self.call('daemon.login', self.username, self.password)
logger.debug('Logged in with value %r' % result)
self.connected = True | Connects to the Deluge instance | https://github.com/JohnDoee/deluge-client/blob/388512661b0bb2410c78185695ce564703b0e2fe/deluge_client/client.py#L74-L87 |
JohnDoee/deluge-client | deluge_client/client.py | DelugeRPCClient.disconnect | def disconnect(self):
"""
Disconnect from deluge
"""
if self.connected:
self._socket.close()
self._socket = None
self.connected = False | python | def disconnect(self):
"""
Disconnect from deluge
"""
if self.connected:
self._socket.close()
self._socket = None
self.connected = False | Disconnect from deluge | https://github.com/JohnDoee/deluge-client/blob/388512661b0bb2410c78185695ce564703b0e2fe/deluge_client/client.py#L103-L110 |
JohnDoee/deluge-client | deluge_client/client.py | DelugeRPCClient.call | def call(self, method, *args, **kwargs):
"""
Calls an RPC function
"""
tried_reconnect = False
for _ in range(2):
try:
self._send_call(self.deluge_version, self.deluge_protocol_version, method, *args, **kwargs)
return self._receive_response(self.deluge_version, self.deluge_protocol_version)
except (socket.error, ConnectionLostException, CallTimeoutException):
if self.automatic_reconnect:
if tried_reconnect:
raise FailedToReconnectException()
else:
try:
self.reconnect()
except (socket.error, ConnectionLostException, CallTimeoutException):
raise FailedToReconnectException()
tried_reconnect = True
else:
raise | python | def call(self, method, *args, **kwargs):
"""
Calls an RPC function
"""
tried_reconnect = False
for _ in range(2):
try:
self._send_call(self.deluge_version, self.deluge_protocol_version, method, *args, **kwargs)
return self._receive_response(self.deluge_version, self.deluge_protocol_version)
except (socket.error, ConnectionLostException, CallTimeoutException):
if self.automatic_reconnect:
if tried_reconnect:
raise FailedToReconnectException()
else:
try:
self.reconnect()
except (socket.error, ConnectionLostException, CallTimeoutException):
raise FailedToReconnectException()
tried_reconnect = True
else:
raise | Calls an RPC function | https://github.com/JohnDoee/deluge-client/blob/388512661b0bb2410c78185695ce564703b0e2fe/deluge_client/client.py#L239-L260 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/stickers.py | StickerSet.to_array | def to_array(self):
"""
Serializes this StickerSet to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(StickerSet, self).to_array()
array['name'] = u(self.name) # py2: type unicode, py3: type str
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['contains_masks'] = bool(self.contains_masks) # type bool
array['stickers'] = self._as_array(self.stickers) # type list of Sticker
return array | python | def to_array(self):
"""
Serializes this StickerSet to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(StickerSet, self).to_array()
array['name'] = u(self.name) # py2: type unicode, py3: type str
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['contains_masks'] = bool(self.contains_masks) # type bool
array['stickers'] = self._as_array(self.stickers) # type list of Sticker
return array | Serializes this StickerSet to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/stickers.py#L81-L96 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/stickers.py | StickerSet.from_array | def from_array(array):
"""
Deserialize a new StickerSet from a given dictionary.
:return: new StickerSet instance.
:rtype: StickerSet
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.media import Sticker
data = {}
data['name'] = u(array.get('name'))
data['title'] = u(array.get('title'))
data['contains_masks'] = bool(array.get('contains_masks'))
data['stickers'] = Sticker.from_array_list(array.get('stickers'), list_level=1)
data['_raw'] = array
return StickerSet(**data) | python | def from_array(array):
"""
Deserialize a new StickerSet from a given dictionary.
:return: new StickerSet instance.
:rtype: StickerSet
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.media import Sticker
data = {}
data['name'] = u(array.get('name'))
data['title'] = u(array.get('title'))
data['contains_masks'] = bool(array.get('contains_masks'))
data['stickers'] = Sticker.from_array_list(array.get('stickers'), list_level=1)
data['_raw'] = array
return StickerSet(**data) | Deserialize a new StickerSet from a given dictionary.
:return: new StickerSet instance.
:rtype: StickerSet | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/stickers.py#L100-L120 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/stickers.py | MaskPosition.to_array | def to_array(self):
"""
Serializes this MaskPosition to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(MaskPosition, self).to_array()
array['point'] = u(self.point) # py2: type unicode, py3: type str
array['x_shift'] = float(self.x_shift) # type float
array['y_shift'] = float(self.y_shift) # type float
array['scale'] = float(self.scale) # type float
return array | python | def to_array(self):
"""
Serializes this MaskPosition to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(MaskPosition, self).to_array()
array['point'] = u(self.point) # py2: type unicode, py3: type str
array['x_shift'] = float(self.x_shift) # type float
array['y_shift'] = float(self.y_shift) # type float
array['scale'] = float(self.scale) # type float
return array | Serializes this MaskPosition to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/stickers.py#L220-L233 |
luckydonald/pytgbot | code_generation/output/pytgbot/api_types/receivable/stickers.py | MaskPosition.from_array | def from_array(array):
"""
Deserialize a new MaskPosition from a given dictionary.
:return: new MaskPosition instance.
:rtype: MaskPosition
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['point'] = u(array.get('point'))
data['x_shift'] = float(array.get('x_shift'))
data['y_shift'] = float(array.get('y_shift'))
data['scale'] = float(array.get('scale'))
data['_raw'] = array
return MaskPosition(**data) | python | def from_array(array):
"""
Deserialize a new MaskPosition from a given dictionary.
:return: new MaskPosition instance.
:rtype: MaskPosition
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['point'] = u(array.get('point'))
data['x_shift'] = float(array.get('x_shift'))
data['y_shift'] = float(array.get('y_shift'))
data['scale'] = float(array.get('scale'))
data['_raw'] = array
return MaskPosition(**data) | Deserialize a new MaskPosition from a given dictionary.
:return: new MaskPosition instance.
:rtype: MaskPosition | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/stickers.py#L237-L255 |
delph-in/pydelphin | delphin/interfaces/ace.py | compile | def compile(cfg_path, out_path, executable=None, env=None, log=None):
"""
Use ACE to compile a grammar.
Args:
cfg_path (str): the path to the ACE config file
out_path (str): the path where the compiled grammar will be
written
executable (str, optional): the path to the ACE binary; if
`None`, the `ace` command will be used
env (dict, optional): environment variables to pass to the ACE
subprocess
log (file, optional): if given, the file, opened for writing,
or stream to write ACE's stdout and stderr compile messages
"""
try:
check_call(
[(executable or 'ace'), '-g', cfg_path, '-G', out_path],
stdout=log, stderr=log, close_fds=True,
env=(env or os.environ)
)
except (CalledProcessError, OSError):
logging.error(
'Failed to compile grammar with ACE. See {}'
.format(log.name if log is not None else '<stderr>')
)
raise | python | def compile(cfg_path, out_path, executable=None, env=None, log=None):
"""
Use ACE to compile a grammar.
Args:
cfg_path (str): the path to the ACE config file
out_path (str): the path where the compiled grammar will be
written
executable (str, optional): the path to the ACE binary; if
`None`, the `ace` command will be used
env (dict, optional): environment variables to pass to the ACE
subprocess
log (file, optional): if given, the file, opened for writing,
or stream to write ACE's stdout and stderr compile messages
"""
try:
check_call(
[(executable or 'ace'), '-g', cfg_path, '-G', out_path],
stdout=log, stderr=log, close_fds=True,
env=(env or os.environ)
)
except (CalledProcessError, OSError):
logging.error(
'Failed to compile grammar with ACE. See {}'
.format(log.name if log is not None else '<stderr>')
)
raise | Use ACE to compile a grammar.
Args:
cfg_path (str): the path to the ACE config file
out_path (str): the path where the compiled grammar will be
written
executable (str, optional): the path to the ACE binary; if
`None`, the `ace` command will be used
env (dict, optional): environment variables to pass to the ACE
subprocess
log (file, optional): if given, the file, opened for writing,
or stream to write ACE's stdout and stderr compile messages | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/ace.py#L439-L465 |
delph-in/pydelphin | delphin/interfaces/ace.py | parse_from_iterable | def parse_from_iterable(grm, data, **kwargs):
"""
Parse each sentence in *data* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
data (iterable): the sentences to parse
**kwargs: additional keyword arguments to pass to the AceParser
Yields:
:class:`~delphin.interfaces.ParseResponse`
Example:
>>> sentences = ['Dogs bark.', 'It rained']
>>> responses = list(ace.parse_from_iterable('erg.dat', sentences))
NOTE: parsed 2 / 2 sentences, avg 723k, time 0.01026s
"""
with AceParser(grm, **kwargs) as parser:
for datum in data:
yield parser.interact(datum) | python | def parse_from_iterable(grm, data, **kwargs):
"""
Parse each sentence in *data* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
data (iterable): the sentences to parse
**kwargs: additional keyword arguments to pass to the AceParser
Yields:
:class:`~delphin.interfaces.ParseResponse`
Example:
>>> sentences = ['Dogs bark.', 'It rained']
>>> responses = list(ace.parse_from_iterable('erg.dat', sentences))
NOTE: parsed 2 / 2 sentences, avg 723k, time 0.01026s
"""
with AceParser(grm, **kwargs) as parser:
for datum in data:
yield parser.interact(datum) | Parse each sentence in *data* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
data (iterable): the sentences to parse
**kwargs: additional keyword arguments to pass to the AceParser
Yields:
:class:`~delphin.interfaces.ParseResponse`
Example:
>>> sentences = ['Dogs bark.', 'It rained']
>>> responses = list(ace.parse_from_iterable('erg.dat', sentences))
NOTE: parsed 2 / 2 sentences, avg 723k, time 0.01026s | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/ace.py#L468-L485 |
delph-in/pydelphin | delphin/interfaces/ace.py | transfer_from_iterable | def transfer_from_iterable(grm, data, **kwargs):
"""
Transfer from each MRS in *data* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
data (iterable): source MRSs as SimpleMRS strings
**kwargs: additional keyword arguments to pass to the
AceTransferer
Yields:
:class:`~delphin.interfaces.ParseResponse`
"""
with AceTransferer(grm, **kwargs) as transferer:
for datum in data:
yield transferer.interact(datum) | python | def transfer_from_iterable(grm, data, **kwargs):
"""
Transfer from each MRS in *data* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
data (iterable): source MRSs as SimpleMRS strings
**kwargs: additional keyword arguments to pass to the
AceTransferer
Yields:
:class:`~delphin.interfaces.ParseResponse`
"""
with AceTransferer(grm, **kwargs) as transferer:
for datum in data:
yield transferer.interact(datum) | Transfer from each MRS in *data* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
data (iterable): source MRSs as SimpleMRS strings
**kwargs: additional keyword arguments to pass to the
AceTransferer
Yields:
:class:`~delphin.interfaces.ParseResponse` | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/ace.py#L505-L519 |
delph-in/pydelphin | delphin/interfaces/ace.py | generate_from_iterable | def generate_from_iterable(grm, data, **kwargs):
"""
Generate from each MRS in *data* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
data (iterable): MRSs as SimpleMRS strings
**kwargs: additional keyword arguments to pass to the
AceGenerator
Yields:
:class:`~delphin.interfaces.ParseResponse`
"""
with AceGenerator(grm, **kwargs) as generator:
for datum in data:
yield generator.interact(datum) | python | def generate_from_iterable(grm, data, **kwargs):
"""
Generate from each MRS in *data* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
data (iterable): MRSs as SimpleMRS strings
**kwargs: additional keyword arguments to pass to the
AceGenerator
Yields:
:class:`~delphin.interfaces.ParseResponse`
"""
with AceGenerator(grm, **kwargs) as generator:
for datum in data:
yield generator.interact(datum) | Generate from each MRS in *data* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
data (iterable): MRSs as SimpleMRS strings
**kwargs: additional keyword arguments to pass to the
AceGenerator
Yields:
:class:`~delphin.interfaces.ParseResponse` | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/ace.py#L537-L551 |
delph-in/pydelphin | delphin/interfaces/ace.py | AceProcess.send | def send(self, datum):
"""
Send *datum* (e.g. a sentence or MRS) to ACE.
Warning:
Sending data without reading (e.g., via :meth:`receive`) can
fill the buffer and cause data to be lost. Use the
:meth:`interact` method for most data-processing tasks with
ACE.
"""
try:
self._p.stdin.write((datum.rstrip() + '\n'))
self._p.stdin.flush()
except (IOError, OSError): # ValueError if file was closed manually
logging.info(
'Attempted to write to a closed process; attempting to reopen'
)
self._open()
self._p.stdin.write((datum.rstrip() + '\n'))
self._p.stdin.flush() | python | def send(self, datum):
"""
Send *datum* (e.g. a sentence or MRS) to ACE.
Warning:
Sending data without reading (e.g., via :meth:`receive`) can
fill the buffer and cause data to be lost. Use the
:meth:`interact` method for most data-processing tasks with
ACE.
"""
try:
self._p.stdin.write((datum.rstrip() + '\n'))
self._p.stdin.flush()
except (IOError, OSError): # ValueError if file was closed manually
logging.info(
'Attempted to write to a closed process; attempting to reopen'
)
self._open()
self._p.stdin.write((datum.rstrip() + '\n'))
self._p.stdin.flush() | Send *datum* (e.g. a sentence or MRS) to ACE.
Warning:
Sending data without reading (e.g., via :meth:`receive`) can
fill the buffer and cause data to be lost. Use the
:meth:`interact` method for most data-processing tasks with
ACE. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/ace.py#L221-L240 |
delph-in/pydelphin | delphin/interfaces/ace.py | AceProcess.interact | def interact(self, datum):
"""
Send *datum* to ACE and return the response.
This is the recommended method for sending and receiving data
to/from an ACE process as it reduces the chances of
over-filling or reading past the end of the buffer. It also
performs a simple validation of the input to help ensure that
one complete item is processed at a time.
If input item identifiers need to be tracked throughout
processing, see :meth:`process_item`.
Args:
datum (str): the input sentence or MRS
Returns:
:class:`~delphin.interfaces.ParseResponse`
"""
validated = self._validate_input(datum)
if validated:
self.send(validated)
result = self.receive()
else:
result, lines = _make_response(
[('NOTE: PyDelphin could not validate the input and '
'refused to send it to ACE'),
'SKIP: {}'.format(datum)],
self.run_info)
result['input'] = datum
return result | python | def interact(self, datum):
"""
Send *datum* to ACE and return the response.
This is the recommended method for sending and receiving data
to/from an ACE process as it reduces the chances of
over-filling or reading past the end of the buffer. It also
performs a simple validation of the input to help ensure that
one complete item is processed at a time.
If input item identifiers need to be tracked throughout
processing, see :meth:`process_item`.
Args:
datum (str): the input sentence or MRS
Returns:
:class:`~delphin.interfaces.ParseResponse`
"""
validated = self._validate_input(datum)
if validated:
self.send(validated)
result = self.receive()
else:
result, lines = _make_response(
[('NOTE: PyDelphin could not validate the input and '
'refused to send it to ACE'),
'SKIP: {}'.format(datum)],
self.run_info)
result['input'] = datum
return result | Send *datum* to ACE and return the response.
This is the recommended method for sending and receiving data
to/from an ACE process as it reduces the chances of
over-filling or reading past the end of the buffer. It also
performs a simple validation of the input to help ensure that
one complete item is processed at a time.
If input item identifiers need to be tracked throughout
processing, see :meth:`process_item`.
Args:
datum (str): the input sentence or MRS
Returns:
:class:`~delphin.interfaces.ParseResponse` | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/ace.py#L264-L293 |
delph-in/pydelphin | delphin/interfaces/ace.py | AceProcess.process_item | def process_item(self, datum, keys=None):
"""
Send *datum* to ACE and return the response with context.
The *keys* parameter can be used to track item identifiers
through an ACE interaction. If the `task` member is set on
the AceProcess instance (or one of its subclasses), it is
kept in the response as well.
Args:
datum (str): the input sentence or MRS
keys (dict): a mapping of item identifier names and values
Returns:
:class:`~delphin.interfaces.ParseResponse`
"""
response = self.interact(datum)
if keys is not None:
response['keys'] = keys
if 'task' not in response and self.task is not None:
response['task'] = self.task
return response | python | def process_item(self, datum, keys=None):
"""
Send *datum* to ACE and return the response with context.
The *keys* parameter can be used to track item identifiers
through an ACE interaction. If the `task` member is set on
the AceProcess instance (or one of its subclasses), it is
kept in the response as well.
Args:
datum (str): the input sentence or MRS
keys (dict): a mapping of item identifier names and values
Returns:
:class:`~delphin.interfaces.ParseResponse`
"""
response = self.interact(datum)
if keys is not None:
response['keys'] = keys
if 'task' not in response and self.task is not None:
response['task'] = self.task
return response | Send *datum* to ACE and return the response with context.
The *keys* parameter can be used to track item identifiers
through an ACE interaction. If the `task` member is set on
the AceProcess instance (or one of its subclasses), it is
kept in the response as well.
Args:
datum (str): the input sentence or MRS
keys (dict): a mapping of item identifier names and values
Returns:
:class:`~delphin.interfaces.ParseResponse` | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/ace.py#L295-L314 |
delph-in/pydelphin | delphin/interfaces/ace.py | AceProcess.close | def close(self):
"""
Close the ACE process and return the process's exit code.
"""
self.run_info['end'] = datetime.now()
self._p.stdin.close()
for line in self._p.stdout:
if line.startswith('NOTE: tsdb run:'):
self._read_run_info(line)
else:
logging.debug('ACE cleanup: {}'.format(line.rstrip()))
retval = self._p.wait()
return retval | python | def close(self):
"""
Close the ACE process and return the process's exit code.
"""
self.run_info['end'] = datetime.now()
self._p.stdin.close()
for line in self._p.stdout:
if line.startswith('NOTE: tsdb run:'):
self._read_run_info(line)
else:
logging.debug('ACE cleanup: {}'.format(line.rstrip()))
retval = self._p.wait()
return retval | Close the ACE process and return the process's exit code. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/ace.py#L316-L328 |
delph-in/pydelphin | delphin/mrs/dmrx.py | load | def load(fh, single=False):
"""
Deserialize DMRX from a file (handle or filename)
Args:
fh (str, file): input filename or file object
single: if `True`, only return the first read Xmrs object
Returns:
a generator of Xmrs objects (unless the *single* option is
`True`)
"""
ms = deserialize(fh)
if single:
ms = next(ms)
return ms | python | def load(fh, single=False):
"""
Deserialize DMRX from a file (handle or filename)
Args:
fh (str, file): input filename or file object
single: if `True`, only return the first read Xmrs object
Returns:
a generator of Xmrs objects (unless the *single* option is
`True`)
"""
ms = deserialize(fh)
if single:
ms = next(ms)
return ms | Deserialize DMRX from a file (handle or filename)
Args:
fh (str, file): input filename or file object
single: if `True`, only return the first read Xmrs object
Returns:
a generator of Xmrs objects (unless the *single* option is
`True`) | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/dmrx.py#L24-L38 |
delph-in/pydelphin | delphin/mrs/dmrx.py | loads | def loads(s, single=False):
"""
Deserialize DMRX string representations
Args:
s (str): a DMRX string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of Xmrs objects (unless *single* is `True`)
"""
corpus = etree.fromstring(s)
if single:
ds = _deserialize_dmrs(next(iter(corpus)))
else:
ds = (_deserialize_dmrs(dmrs_elem) for dmrs_elem in corpus)
return ds | python | def loads(s, single=False):
"""
Deserialize DMRX string representations
Args:
s (str): a DMRX string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of Xmrs objects (unless *single* is `True`)
"""
corpus = etree.fromstring(s)
if single:
ds = _deserialize_dmrs(next(iter(corpus)))
else:
ds = (_deserialize_dmrs(dmrs_elem) for dmrs_elem in corpus)
return ds | Deserialize DMRX string representations
Args:
s (str): a DMRX string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of Xmrs objects (unless *single* is `True`) | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/dmrx.py#L41-L56 |
delph-in/pydelphin | delphin/interfaces/base.py | ParseResult.derivation | def derivation(self):
"""
Deserialize and return a Derivation object for UDF- or
JSON-formatted derivation data; otherwise return the original
string.
"""
drv = self.get('derivation')
if drv is not None:
if isinstance(drv, dict):
drv = Derivation.from_dict(drv)
elif isinstance(drv, stringtypes):
drv = Derivation.from_string(drv)
return drv | python | def derivation(self):
"""
Deserialize and return a Derivation object for UDF- or
JSON-formatted derivation data; otherwise return the original
string.
"""
drv = self.get('derivation')
if drv is not None:
if isinstance(drv, dict):
drv = Derivation.from_dict(drv)
elif isinstance(drv, stringtypes):
drv = Derivation.from_string(drv)
return drv | Deserialize and return a Derivation object for UDF- or
JSON-formatted derivation data; otherwise return the original
string. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/base.py#L64-L76 |
delph-in/pydelphin | delphin/interfaces/base.py | ParseResult.tree | def tree(self):
"""
Deserialize and return a labeled syntax tree. The tree data
may be a standalone datum, or embedded in the derivation.
"""
tree = self.get('tree')
if isinstance(tree, stringtypes):
tree = SExpr.parse(tree).data
elif tree is None:
drv = self.get('derivation')
if isinstance(drv, dict) and 'label' in drv:
def _extract_tree(d):
t = [d.get('label', '')]
if 'tokens' in d:
t.append([d.get('form', '')])
else:
for dtr in d.get('daughters', []):
t.append(_extract_tree(dtr))
return t
tree = _extract_tree(drv)
return tree | python | def tree(self):
"""
Deserialize and return a labeled syntax tree. The tree data
may be a standalone datum, or embedded in the derivation.
"""
tree = self.get('tree')
if isinstance(tree, stringtypes):
tree = SExpr.parse(tree).data
elif tree is None:
drv = self.get('derivation')
if isinstance(drv, dict) and 'label' in drv:
def _extract_tree(d):
t = [d.get('label', '')]
if 'tokens' in d:
t.append([d.get('form', '')])
else:
for dtr in d.get('daughters', []):
t.append(_extract_tree(dtr))
return t
tree = _extract_tree(drv)
return tree | Deserialize and return a labeled syntax tree. The tree data
may be a standalone datum, or embedded in the derivation. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/base.py#L78-L98 |
delph-in/pydelphin | delphin/interfaces/base.py | ParseResult.mrs | def mrs(self):
"""
Deserialize and return an Mrs object for simplemrs or
JSON-formatted MRS data; otherwise return the original string.
"""
mrs = self.get('mrs')
if mrs is not None:
if isinstance(mrs, dict):
mrs = Mrs.from_dict(mrs)
elif isinstance(mrs, stringtypes):
mrs = simplemrs.loads_one(mrs)
return mrs | python | def mrs(self):
"""
Deserialize and return an Mrs object for simplemrs or
JSON-formatted MRS data; otherwise return the original string.
"""
mrs = self.get('mrs')
if mrs is not None:
if isinstance(mrs, dict):
mrs = Mrs.from_dict(mrs)
elif isinstance(mrs, stringtypes):
mrs = simplemrs.loads_one(mrs)
return mrs | Deserialize and return an Mrs object for simplemrs or
JSON-formatted MRS data; otherwise return the original string. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/base.py#L100-L111 |
delph-in/pydelphin | delphin/interfaces/base.py | ParseResult.eds | def eds(self):
"""
Deserialize and return an Eds object for native- or
JSON-formatted EDS data; otherwise return the original string.
"""
_eds = self.get('eds')
if _eds is not None:
if isinstance(_eds, dict):
_eds = eds.Eds.from_dict(_eds)
elif isinstance(_eds, stringtypes):
_eds = eds.loads_one(_eds)
return _eds | python | def eds(self):
"""
Deserialize and return an Eds object for native- or
JSON-formatted EDS data; otherwise return the original string.
"""
_eds = self.get('eds')
if _eds is not None:
if isinstance(_eds, dict):
_eds = eds.Eds.from_dict(_eds)
elif isinstance(_eds, stringtypes):
_eds = eds.loads_one(_eds)
return _eds | Deserialize and return an Eds object for native- or
JSON-formatted EDS data; otherwise return the original string. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/base.py#L113-L124 |
delph-in/pydelphin | delphin/interfaces/base.py | ParseResult.dmrs | def dmrs(self):
"""
Deserialize and return a Dmrs object for JSON-formatted DMRS
data; otherwise return the original string.
"""
dmrs = self.get('dmrs')
if dmrs is not None:
if isinstance(dmrs, dict):
dmrs = Dmrs.from_dict(dmrs)
return dmrs | python | def dmrs(self):
"""
Deserialize and return a Dmrs object for JSON-formatted DMRS
data; otherwise return the original string.
"""
dmrs = self.get('dmrs')
if dmrs is not None:
if isinstance(dmrs, dict):
dmrs = Dmrs.from_dict(dmrs)
return dmrs | Deserialize and return a Dmrs object for JSON-formatted DMRS
data; otherwise return the original string. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/base.py#L126-L135 |
delph-in/pydelphin | delphin/interfaces/base.py | ParseResponse.tokens | def tokens(self, tokenset='internal'):
"""
Deserialize and return a YyTokenLattice object for the
initial or internal token set, if provided, from the YY
format or the JSON-formatted data; otherwise return the
original string.
Args:
tokenset (str): return `'initial'` or `'internal'` tokens
(default: `'internal'`)
Returns:
:class:`YyTokenLattice`
"""
toks = self.get('tokens', {}).get(tokenset)
if toks is not None:
if isinstance(toks, stringtypes):
toks = YyTokenLattice.from_string(toks)
elif isinstance(toks, Sequence):
toks = YyTokenLattice.from_list(toks)
return toks | python | def tokens(self, tokenset='internal'):
"""
Deserialize and return a YyTokenLattice object for the
initial or internal token set, if provided, from the YY
format or the JSON-formatted data; otherwise return the
original string.
Args:
tokenset (str): return `'initial'` or `'internal'` tokens
(default: `'internal'`)
Returns:
:class:`YyTokenLattice`
"""
toks = self.get('tokens', {}).get(tokenset)
if toks is not None:
if isinstance(toks, stringtypes):
toks = YyTokenLattice.from_string(toks)
elif isinstance(toks, Sequence):
toks = YyTokenLattice.from_list(toks)
return toks | Deserialize and return a YyTokenLattice object for the
initial or internal token set, if provided, from the YY
format or the JSON-formatted data; otherwise return the
original string.
Args:
tokenset (str): return `'initial'` or `'internal'` tokens
(default: `'internal'`)
Returns:
:class:`YyTokenLattice` | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/base.py#L155-L174 |
delph-in/pydelphin | delphin/interfaces/base.py | FieldMapper.map | def map(self, response):
"""
Process *response* and return a list of (table, rowdata) tuples.
"""
inserts = []
parse = {}
# custom remapping, cleanup, and filling in holes
parse['i-id'] = response.get('keys', {}).get('i-id', -1)
self._parse_id = max(self._parse_id + 1, parse['i-id'])
parse['parse-id'] = self._parse_id
parse['run-id'] = response.get('run', {}).get('run-id', -1)
if 'tokens' in response:
parse['p-input'] = response['tokens'].get('initial')
parse['p-tokens'] = response['tokens'].get('internal')
if 'ninputs' not in response:
toks = response.tokens('initial')
if toks is not None:
response['ninputs'] = len(toks.tokens)
if 'ntokens' not in response:
toks = response.tokens('internal')
if toks is not None:
response['ntokens'] = len(toks.tokens)
if 'readings' not in response and 'results' in response:
response['readings'] = len(response['results'])
# basic mapping
for key in self._parse_keys:
if key in response:
parse[key] = response[key]
inserts.append(('parse', parse))
for result in response.get('results', []):
d = {'parse-id': self._parse_id}
if 'flags' in result:
d['flags'] = SExpr.format(result['flags'])
for key in self._result_keys:
if key in result:
d[key] = result[key]
inserts.append(('result', d))
if 'run' in response:
run_id = response['run'].get('run-id', -1)
# check if last run was not closed properly
if run_id not in self._runs and self._last_run_id in self._runs:
last_run = self._runs[self._last_run_id]
if 'end' not in last_run:
last_run['end'] = datetime.now()
self._runs[run_id] = response['run']
self._last_run_id = run_id
return inserts | python | def map(self, response):
"""
Process *response* and return a list of (table, rowdata) tuples.
"""
inserts = []
parse = {}
# custom remapping, cleanup, and filling in holes
parse['i-id'] = response.get('keys', {}).get('i-id', -1)
self._parse_id = max(self._parse_id + 1, parse['i-id'])
parse['parse-id'] = self._parse_id
parse['run-id'] = response.get('run', {}).get('run-id', -1)
if 'tokens' in response:
parse['p-input'] = response['tokens'].get('initial')
parse['p-tokens'] = response['tokens'].get('internal')
if 'ninputs' not in response:
toks = response.tokens('initial')
if toks is not None:
response['ninputs'] = len(toks.tokens)
if 'ntokens' not in response:
toks = response.tokens('internal')
if toks is not None:
response['ntokens'] = len(toks.tokens)
if 'readings' not in response and 'results' in response:
response['readings'] = len(response['results'])
# basic mapping
for key in self._parse_keys:
if key in response:
parse[key] = response[key]
inserts.append(('parse', parse))
for result in response.get('results', []):
d = {'parse-id': self._parse_id}
if 'flags' in result:
d['flags'] = SExpr.format(result['flags'])
for key in self._result_keys:
if key in result:
d[key] = result[key]
inserts.append(('result', d))
if 'run' in response:
run_id = response['run'].get('run-id', -1)
# check if last run was not closed properly
if run_id not in self._runs and self._last_run_id in self._runs:
last_run = self._runs[self._last_run_id]
if 'end' not in last_run:
last_run['end'] = datetime.now()
self._runs[run_id] = response['run']
self._last_run_id = run_id
return inserts | Process *response* and return a list of (table, rowdata) tuples. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/base.py#L230-L280 |
delph-in/pydelphin | delphin/interfaces/base.py | FieldMapper.cleanup | def cleanup(self):
"""
Return aggregated (table, rowdata) tuples and clear the state.
"""
inserts = []
last_run = self._runs[self._last_run_id]
if 'end' not in last_run:
last_run['end'] = datetime.now()
for run_id in sorted(self._runs):
run = self._runs[run_id]
d = {'run-id': run.get('run-id', -1)}
for key in self._run_keys:
if key in run:
d[key] = run[key]
inserts.append(('run', d))
# reset for next task
self._parse_id = -1
self._runs = {}
self._last_run_id = -1
return inserts | python | def cleanup(self):
"""
Return aggregated (table, rowdata) tuples and clear the state.
"""
inserts = []
last_run = self._runs[self._last_run_id]
if 'end' not in last_run:
last_run['end'] = datetime.now()
for run_id in sorted(self._runs):
run = self._runs[run_id]
d = {'run-id': run.get('run-id', -1)}
for key in self._run_keys:
if key in run:
d[key] = run[key]
inserts.append(('run', d))
# reset for next task
self._parse_id = -1
self._runs = {}
self._last_run_id = -1
return inserts | Return aggregated (table, rowdata) tuples and clear the state. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/base.py#L282-L305 |
luckydonald/pytgbot | pytgbot/api_types/receivable/game.py | GameHighScore.to_array | def to_array(self):
"""
Serializes this GameHighScore to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(GameHighScore, self).to_array()
array['position'] = int(self.position) # type int
array['user'] = self.user.to_array() # type User
array['score'] = int(self.score) # type int
return array | python | def to_array(self):
"""
Serializes this GameHighScore to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(GameHighScore, self).to_array()
array['position'] = int(self.position) # type int
array['user'] = self.user.to_array() # type User
array['score'] = int(self.score) # type int
return array | Serializes this GameHighScore to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/game.py#L74-L85 |
luckydonald/pytgbot | pytgbot/api_types/receivable/game.py | GameHighScore.from_array | def from_array(array):
"""
Deserialize a new GameHighScore from a given dictionary.
:return: new GameHighScore instance.
:rtype: GameHighScore
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.peer import User
data = {}
data['position'] = int(array.get('position'))
data['user'] = User.from_array(array.get('user'))
data['score'] = int(array.get('score'))
data['_raw'] = array
return GameHighScore(**data) | python | def from_array(array):
"""
Deserialize a new GameHighScore from a given dictionary.
:return: new GameHighScore instance.
:rtype: GameHighScore
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.peer import User
data = {}
data['position'] = int(array.get('position'))
data['user'] = User.from_array(array.get('user'))
data['score'] = int(array.get('score'))
data['_raw'] = array
return GameHighScore(**data) | Deserialize a new GameHighScore from a given dictionary.
:return: new GameHighScore instance.
:rtype: GameHighScore | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/receivable/game.py#L89-L108 |
delph-in/pydelphin | delphin/extra/latex.py | dmrs_tikz_dependency | def dmrs_tikz_dependency(xs, **kwargs):
"""
Return a LaTeX document with each Xmrs in *xs* rendered as DMRSs.
DMRSs use the `tikz-dependency` package for visualization.
"""
def link_label(link):
return '{}/{}'.format(link.rargname or '', link.post)
def label_edge(link):
if link.post == H_POST and link.rargname == RSTR_ROLE:
return 'rstr'
elif link.post == EQ_POST:
return 'eq'
else:
return 'arg'
if isinstance(xs, Xmrs):
xs = [xs]
lines = """\\documentclass{standalone}
\\usepackage{tikz-dependency}
\\usepackage{relsize}
%%%
%%% style for dmrs graph
%%%
\\depstyle{dmrs}{edge unit distance=1.5ex,
label style={above, scale=.9, opacity=0, text opacity=1},
baseline={([yshift=-0.7\\baselineskip]current bounding box.north)}}
%%% set text opacity=0 to hide text, opacity = 0 to hide box
\\depstyle{root}{edge unit distance=3ex, label style={opacity=1}}
\\depstyle{arg}{edge above}
\\depstyle{rstr}{edge below, dotted, label style={text opacity=1}}
\\depstyle{eq}{edge below, label style={text opacity=1}}
\\depstyle{icons}{edge below, dashed}
\\providecommand{\\named}{}
\\renewcommand{\\named}{named}
%%% styles for predicates and roles (from mrs.sty)
\\providecommand{\\spred}{}
\\renewcommand{\\spred}[1]{\\mbox{\\textsf{#1}}}
\\providecommand{\\srl}{}
\\renewcommand{\\srl}[1]{\\mbox{\\textsf{\\smaller #1}}}
%%%
\\begin{document}""".split("\n")
for ix, x in enumerate(xs):
lines.append("%%%\n%%% {}\n%%%".format(ix+1))
lines.append("\\begin{dependency}[dmrs]")
ns = nodes(x)
### predicates
lines.append(" \\begin{deptext}[column sep=10pt]")
for i, n in enumerate(ns):
sep = "\\&" if (i < len(ns) - 1) else "\\\\"
pred = _latex_escape(n.pred.short_form())
pred = "\\named{}" if pred == 'named' else pred
if n.carg is not None:
print(n.carg.strip('"'))
pred += "\\smaller ({})".format(n.carg.strip('"'))
lines.append(" \\spred{{{}}} {} % node {}".format(
pred, sep, i+1))
lines.append(" \\end{deptext}")
nodeidx = {n.nodeid: i+1 for i, n in enumerate(ns)}
### links
for link in links(x):
if link.start == 0:
lines.append(
' \\deproot[root]{{{}}}{{{}}}'.format(
nodeidx[link.end],
'\\srl{TOP}' # _latex_escape('/' + link.post)
)
)
else:
lines.append(' \\depedge[{}]{{{}}}{{{}}}{{\\srl{{{}}}}}'.format(
label_edge(link),
nodeidx[link.start],
nodeidx[link.end],
_latex_escape(link_label(link))
))
### placeholder for icons
lines.append('% \\depedge[icons]{f}{t}{FOCUS}')
lines.append('\\end{dependency}\n')
lines.append('\\end{document}')
return '\n'.join(lines) | python | def dmrs_tikz_dependency(xs, **kwargs):
"""
Return a LaTeX document with each Xmrs in *xs* rendered as DMRSs.
DMRSs use the `tikz-dependency` package for visualization.
"""
def link_label(link):
return '{}/{}'.format(link.rargname or '', link.post)
def label_edge(link):
if link.post == H_POST and link.rargname == RSTR_ROLE:
return 'rstr'
elif link.post == EQ_POST:
return 'eq'
else:
return 'arg'
if isinstance(xs, Xmrs):
xs = [xs]
lines = """\\documentclass{standalone}
\\usepackage{tikz-dependency}
\\usepackage{relsize}
%%%
%%% style for dmrs graph
%%%
\\depstyle{dmrs}{edge unit distance=1.5ex,
label style={above, scale=.9, opacity=0, text opacity=1},
baseline={([yshift=-0.7\\baselineskip]current bounding box.north)}}
%%% set text opacity=0 to hide text, opacity = 0 to hide box
\\depstyle{root}{edge unit distance=3ex, label style={opacity=1}}
\\depstyle{arg}{edge above}
\\depstyle{rstr}{edge below, dotted, label style={text opacity=1}}
\\depstyle{eq}{edge below, label style={text opacity=1}}
\\depstyle{icons}{edge below, dashed}
\\providecommand{\\named}{}
\\renewcommand{\\named}{named}
%%% styles for predicates and roles (from mrs.sty)
\\providecommand{\\spred}{}
\\renewcommand{\\spred}[1]{\\mbox{\\textsf{#1}}}
\\providecommand{\\srl}{}
\\renewcommand{\\srl}[1]{\\mbox{\\textsf{\\smaller #1}}}
%%%
\\begin{document}""".split("\n")
for ix, x in enumerate(xs):
lines.append("%%%\n%%% {}\n%%%".format(ix+1))
lines.append("\\begin{dependency}[dmrs]")
ns = nodes(x)
### predicates
lines.append(" \\begin{deptext}[column sep=10pt]")
for i, n in enumerate(ns):
sep = "\\&" if (i < len(ns) - 1) else "\\\\"
pred = _latex_escape(n.pred.short_form())
pred = "\\named{}" if pred == 'named' else pred
if n.carg is not None:
print(n.carg.strip('"'))
pred += "\\smaller ({})".format(n.carg.strip('"'))
lines.append(" \\spred{{{}}} {} % node {}".format(
pred, sep, i+1))
lines.append(" \\end{deptext}")
nodeidx = {n.nodeid: i+1 for i, n in enumerate(ns)}
### links
for link in links(x):
if link.start == 0:
lines.append(
' \\deproot[root]{{{}}}{{{}}}'.format(
nodeidx[link.end],
'\\srl{TOP}' # _latex_escape('/' + link.post)
)
)
else:
lines.append(' \\depedge[{}]{{{}}}{{{}}}{{\\srl{{{}}}}}'.format(
label_edge(link),
nodeidx[link.start],
nodeidx[link.end],
_latex_escape(link_label(link))
))
### placeholder for icons
lines.append('% \\depedge[icons]{f}{t}{FOCUS}')
lines.append('\\end{dependency}\n')
lines.append('\\end{document}')
return '\n'.join(lines) | Return a LaTeX document with each Xmrs in *xs* rendered as DMRSs.
DMRSs use the `tikz-dependency` package for visualization. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/extra/latex.py#L41-L127 |
delph-in/pydelphin | delphin/lib/pegre.py | valuemap | def valuemap(f):
"""
Decorator to help PEG functions handle value conversions.
"""
@wraps(f)
def wrapper(*args, **kwargs):
if 'value' in kwargs:
val = kwargs['value']
del kwargs['value']
_f = f(*args, **kwargs)
def valued_f(*args, **kwargs):
result = _f(*args, **kwargs)
s, obj, span = result
if callable(val):
return PegreResult(s, val(obj), span)
else:
return PegreResult(s, val, span)
return valued_f
else:
return f(*args, **kwargs)
return wrapper | python | def valuemap(f):
"""
Decorator to help PEG functions handle value conversions.
"""
@wraps(f)
def wrapper(*args, **kwargs):
if 'value' in kwargs:
val = kwargs['value']
del kwargs['value']
_f = f(*args, **kwargs)
def valued_f(*args, **kwargs):
result = _f(*args, **kwargs)
s, obj, span = result
if callable(val):
return PegreResult(s, val(obj), span)
else:
return PegreResult(s, val, span)
return valued_f
else:
return f(*args, **kwargs)
return wrapper | Decorator to help PEG functions handle value conversions. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L74-L94 |
delph-in/pydelphin | delphin/lib/pegre.py | literal | def literal(x):
"""
Create a PEG function to consume a literal.
"""
xlen = len(x)
msg = 'Expected: "{}"'.format(x)
def match_literal(s, grm=None, pos=0):
if s[:xlen] == x:
return PegreResult(s[xlen:], x, (pos, pos+xlen))
raise PegreError(msg, pos)
return match_literal | python | def literal(x):
"""
Create a PEG function to consume a literal.
"""
xlen = len(x)
msg = 'Expected: "{}"'.format(x)
def match_literal(s, grm=None, pos=0):
if s[:xlen] == x:
return PegreResult(s[xlen:], x, (pos, pos+xlen))
raise PegreError(msg, pos)
return match_literal | Create a PEG function to consume a literal. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L97-L107 |
delph-in/pydelphin | delphin/lib/pegre.py | regex | def regex(r):
"""
Create a PEG function to match a regular expression.
"""
if isinstance(r, stringtypes):
p = re.compile(r)
else:
p = r
msg = 'Expected to match: {}'.format(p.pattern)
def match_regex(s, grm=None, pos=0):
m = p.match(s)
if m is not None:
start, end = m.span()
data = m.groupdict() if p.groupindex else m.group()
return PegreResult(s[m.end():], data, (pos+start, pos+end))
raise PegreError(msg, pos)
return match_regex | python | def regex(r):
"""
Create a PEG function to match a regular expression.
"""
if isinstance(r, stringtypes):
p = re.compile(r)
else:
p = r
msg = 'Expected to match: {}'.format(p.pattern)
def match_regex(s, grm=None, pos=0):
m = p.match(s)
if m is not None:
start, end = m.span()
data = m.groupdict() if p.groupindex else m.group()
return PegreResult(s[m.end():], data, (pos+start, pos+end))
raise PegreError(msg, pos)
return match_regex | Create a PEG function to match a regular expression. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L110-L126 |
delph-in/pydelphin | delphin/lib/pegre.py | nonterminal | def nonterminal(n):
"""
Create a PEG function to match a nonterminal.
"""
def match_nonterminal(s, grm=None, pos=0):
if grm is None: grm = {}
expr = grm[n]
return expr(s, grm, pos)
return match_nonterminal | python | def nonterminal(n):
"""
Create a PEG function to match a nonterminal.
"""
def match_nonterminal(s, grm=None, pos=0):
if grm is None: grm = {}
expr = grm[n]
return expr(s, grm, pos)
return match_nonterminal | Create a PEG function to match a nonterminal. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L129-L137 |
delph-in/pydelphin | delphin/lib/pegre.py | and_next | def and_next(e):
"""
Create a PEG function for positive lookahead.
"""
def match_and_next(s, grm=None, pos=0):
try:
e(s, grm, pos)
except PegreError as ex:
raise PegreError('Positive lookahead failed', pos)
else:
return PegreResult(s, Ignore, (pos, pos))
return match_and_next | python | def and_next(e):
"""
Create a PEG function for positive lookahead.
"""
def match_and_next(s, grm=None, pos=0):
try:
e(s, grm, pos)
except PegreError as ex:
raise PegreError('Positive lookahead failed', pos)
else:
return PegreResult(s, Ignore, (pos, pos))
return match_and_next | Create a PEG function for positive lookahead. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L140-L151 |
delph-in/pydelphin | delphin/lib/pegre.py | not_next | def not_next(e):
"""
Create a PEG function for negative lookahead.
"""
def match_not_next(s, grm=None, pos=0):
try:
e(s, grm, pos)
except PegreError as ex:
return PegreResult(s, Ignore, (pos, pos))
else:
raise PegreError('Negative lookahead failed', pos)
return match_not_next | python | def not_next(e):
"""
Create a PEG function for negative lookahead.
"""
def match_not_next(s, grm=None, pos=0):
try:
e(s, grm, pos)
except PegreError as ex:
return PegreResult(s, Ignore, (pos, pos))
else:
raise PegreError('Negative lookahead failed', pos)
return match_not_next | Create a PEG function for negative lookahead. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L154-L165 |
delph-in/pydelphin | delphin/lib/pegre.py | sequence | def sequence(*es):
"""
Create a PEG function to match a sequence.
"""
def match_sequence(s, grm=None, pos=0):
data = []
start = pos
for e in es:
s, obj, span = e(s, grm, pos)
pos = span[1]
if obj is not Ignore:
data.append(obj)
return PegreResult(s, data, (start, pos))
return match_sequence | python | def sequence(*es):
"""
Create a PEG function to match a sequence.
"""
def match_sequence(s, grm=None, pos=0):
data = []
start = pos
for e in es:
s, obj, span = e(s, grm, pos)
pos = span[1]
if obj is not Ignore:
data.append(obj)
return PegreResult(s, data, (start, pos))
return match_sequence | Create a PEG function to match a sequence. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L168-L181 |
delph-in/pydelphin | delphin/lib/pegre.py | choice | def choice(*es):
"""
Create a PEG function to match an ordered choice.
"""
msg = 'Expected one of: {}'.format(', '.join(map(repr, es)))
def match_choice(s, grm=None, pos=0):
errs = []
for e in es:
try:
return e(s, grm, pos)
except PegreError as ex:
errs.append((ex.message, ex.position))
if errs:
raise PegreChoiceError(errs, pos)
return match_choice | python | def choice(*es):
"""
Create a PEG function to match an ordered choice.
"""
msg = 'Expected one of: {}'.format(', '.join(map(repr, es)))
def match_choice(s, grm=None, pos=0):
errs = []
for e in es:
try:
return e(s, grm, pos)
except PegreError as ex:
errs.append((ex.message, ex.position))
if errs:
raise PegreChoiceError(errs, pos)
return match_choice | Create a PEG function to match an ordered choice. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L184-L198 |
delph-in/pydelphin | delphin/lib/pegre.py | optional | def optional(e, default=Ignore):
"""
Create a PEG function to optionally match an expression.
"""
def match_optional(s, grm=None, pos=0):
try:
return e(s, grm, pos)
except PegreError:
return PegreResult(s, default, (pos, pos))
return match_optional | python | def optional(e, default=Ignore):
"""
Create a PEG function to optionally match an expression.
"""
def match_optional(s, grm=None, pos=0):
try:
return e(s, grm, pos)
except PegreError:
return PegreResult(s, default, (pos, pos))
return match_optional | Create a PEG function to optionally match an expression. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L201-L210 |
delph-in/pydelphin | delphin/lib/pegre.py | zero_or_more | def zero_or_more(e, delimiter=None):
"""
Create a PEG function to match zero or more expressions.
Args:
e: the expression to match
delimiter: an optional expression to match between the
primary *e* matches.
"""
if delimiter is None:
delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos))
def match_zero_or_more(s, grm=None, pos=0):
start = pos
try:
s, obj, span = e(s, grm, pos)
pos = span[1]
data = [] if obj is Ignore else [obj]
except PegreError:
return PegreResult(s, [], (pos, pos))
try:
while True:
s, obj, span = delimiter(s, grm, pos)
pos = span[1]
if obj is not Ignore:
data.append(obj)
s, obj, span = e(s, grm, pos)
pos = span[1]
if obj is not Ignore:
data.append(obj)
except PegreError:
pass
return PegreResult(s, data, (start, pos))
return match_zero_or_more | python | def zero_or_more(e, delimiter=None):
"""
Create a PEG function to match zero or more expressions.
Args:
e: the expression to match
delimiter: an optional expression to match between the
primary *e* matches.
"""
if delimiter is None:
delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos))
def match_zero_or_more(s, grm=None, pos=0):
start = pos
try:
s, obj, span = e(s, grm, pos)
pos = span[1]
data = [] if obj is Ignore else [obj]
except PegreError:
return PegreResult(s, [], (pos, pos))
try:
while True:
s, obj, span = delimiter(s, grm, pos)
pos = span[1]
if obj is not Ignore:
data.append(obj)
s, obj, span = e(s, grm, pos)
pos = span[1]
if obj is not Ignore:
data.append(obj)
except PegreError:
pass
return PegreResult(s, data, (start, pos))
return match_zero_or_more | Create a PEG function to match zero or more expressions.
Args:
e: the expression to match
delimiter: an optional expression to match between the
primary *e* matches. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L213-L245 |
delph-in/pydelphin | delphin/lib/pegre.py | one_or_more | def one_or_more(e, delimiter=None):
"""
Create a PEG function to match one or more expressions.
Args:
e: the expression to match
delimiter: an optional expression to match between the
primary *e* matches.
"""
if delimiter is None:
delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos))
msg = 'Expected one or more of: {}'.format(repr(e))
def match_one_or_more(s, grm=None, pos=0):
start = pos
s, obj, span = e(s, grm, pos)
pos = span[1]
data = [] if obj is Ignore else [obj]
try:
while True:
s, obj, span = delimiter(s, grm, pos)
pos = span[1]
if obj is not Ignore:
data.append(obj)
s, obj, span = e(s, grm, pos)
pos = span[1]
if obj is not Ignore:
data.append(obj)
except PegreError:
pass
return PegreResult(s, data, (start, pos))
return match_one_or_more | python | def one_or_more(e, delimiter=None):
"""
Create a PEG function to match one or more expressions.
Args:
e: the expression to match
delimiter: an optional expression to match between the
primary *e* matches.
"""
if delimiter is None:
delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos))
msg = 'Expected one or more of: {}'.format(repr(e))
def match_one_or_more(s, grm=None, pos=0):
start = pos
s, obj, span = e(s, grm, pos)
pos = span[1]
data = [] if obj is Ignore else [obj]
try:
while True:
s, obj, span = delimiter(s, grm, pos)
pos = span[1]
if obj is not Ignore:
data.append(obj)
s, obj, span = e(s, grm, pos)
pos = span[1]
if obj is not Ignore:
data.append(obj)
except PegreError:
pass
return PegreResult(s, data, (start, pos))
return match_one_or_more | Create a PEG function to match one or more expressions.
Args:
e: the expression to match
delimiter: an optional expression to match between the
primary *e* matches. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/lib/pegre.py#L248-L278 |
delph-in/pydelphin | delphin/mrs/path.py | merge | def merge(base, obj, location=None):
"""
merge is like XmrsPathNode.update() except it raises errors on
unequal non-None values.
"""
# pump object to it's location with dummy nodes
while location:
axis = location.pop()
obj = XmrsPathNode(None, None, links={axis: obj})
if base is None:
return obj
_merge(base, obj)
# if isinstance(base, XmrsPath):
# base.calculate_metrics()
return base | python | def merge(base, obj, location=None):
"""
merge is like XmrsPathNode.update() except it raises errors on
unequal non-None values.
"""
# pump object to it's location with dummy nodes
while location:
axis = location.pop()
obj = XmrsPathNode(None, None, links={axis: obj})
if base is None:
return obj
_merge(base, obj)
# if isinstance(base, XmrsPath):
# base.calculate_metrics()
return base | merge is like XmrsPathNode.update() except it raises errors on
unequal non-None values. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/path.py#L321-L335 |
delph-in/pydelphin | delphin/mrs/path.py | _prepare_axes | def _prepare_axes(node, sort_key):
"""
Sort axes and combine those that point to the same target and go
in the same direction.
"""
links = node.links
o_links = node._overlapping_links
overlap = {ax2 for ax in links for ax2 in o_links.get(ax, [])}
axes = []
for axis in sorted(links.keys(), key=sort_key):
if axis in overlap: continue
tgt = links[axis]
if axis in o_links:
s, e = axis[0], axis[-1]
axis = '%s%s%s' % (
s, '&'.join(a[1:-1] for a in [axis] + o_links[axis]), e
)
axes.append((axis, tgt))
return axes | python | def _prepare_axes(node, sort_key):
"""
Sort axes and combine those that point to the same target and go
in the same direction.
"""
links = node.links
o_links = node._overlapping_links
overlap = {ax2 for ax in links for ax2 in o_links.get(ax, [])}
axes = []
for axis in sorted(links.keys(), key=sort_key):
if axis in overlap: continue
tgt = links[axis]
if axis in o_links:
s, e = axis[0], axis[-1]
axis = '%s%s%s' % (
s, '&'.join(a[1:-1] for a in [axis] + o_links[axis]), e
)
axes.append((axis, tgt))
return axes | Sort axes and combine those that point to the same target and go
in the same direction. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/path.py#L432-L450 |
delph-in/pydelphin | delphin/tfs.py | FeatureStructure.get | def get(self, key, default=None):
"""
Return the value for *key* if it exists, otherwise *default*.
"""
try:
val = self[key]
except KeyError:
val = default
return val | python | def get(self, key, default=None):
"""
Return the value for *key* if it exists, otherwise *default*.
"""
try:
val = self[key]
except KeyError:
val = default
return val | Return the value for *key* if it exists, otherwise *default*. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tfs.py#L90-L98 |
delph-in/pydelphin | delphin/tfs.py | FeatureStructure.features | def features(self, expand=False):
"""
Return the list of tuples of feature paths and feature values.
Args:
expand (bool): if `True`, expand all feature paths
Example:
>>> fs = FeatureStructure([('A.B', 1), ('A.C', 2)])
>>> fs.features()
[('A', <FeatureStructure object at ...>)]
>>> fs.features(expand=True)
[('A.B', 1), ('A.C', 2)]
"""
fs = []
if self._avm is not None:
if len(self._feats) == len(self._avm):
feats = self._feats
else:
feats = list(self._avm)
for feat in feats:
val = self._avm[feat]
if isinstance(val, FeatureStructure):
if not expand and val._is_notable():
fs.append((feat, val))
else:
for subfeat, subval in val.features(expand=expand):
fs.append(('{}.{}'.format(feat, subfeat), subval))
else:
fs.append((feat, val))
return fs | python | def features(self, expand=False):
"""
Return the list of tuples of feature paths and feature values.
Args:
expand (bool): if `True`, expand all feature paths
Example:
>>> fs = FeatureStructure([('A.B', 1), ('A.C', 2)])
>>> fs.features()
[('A', <FeatureStructure object at ...>)]
>>> fs.features(expand=True)
[('A.B', 1), ('A.C', 2)]
"""
fs = []
if self._avm is not None:
if len(self._feats) == len(self._avm):
feats = self._feats
else:
feats = list(self._avm)
for feat in feats:
val = self._avm[feat]
if isinstance(val, FeatureStructure):
if not expand and val._is_notable():
fs.append((feat, val))
else:
for subfeat, subval in val.features(expand=expand):
fs.append(('{}.{}'.format(feat, subfeat), subval))
else:
fs.append((feat, val))
return fs | Return the list of tuples of feature paths and feature values.
Args:
expand (bool): if `True`, expand all feature paths
Example:
>>> fs = FeatureStructure([('A.B', 1), ('A.C', 2)])
>>> fs.features()
[('A', <FeatureStructure object at ...>)]
>>> fs.features(expand=True)
[('A.B', 1), ('A.C', 2)] | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tfs.py#L109-L138 |
delph-in/pydelphin | delphin/tfs.py | TypeHierarchy.ancestors | def ancestors(self, typename):
"""Return the ancestor types of *typename*."""
xs = []
for parent in self._hier[typename][0]:
xs.append(parent)
xs.extend(self.ancestors(parent))
return xs | python | def ancestors(self, typename):
"""Return the ancestor types of *typename*."""
xs = []
for parent in self._hier[typename][0]:
xs.append(parent)
xs.extend(self.ancestors(parent))
return xs | Return the ancestor types of *typename*. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tfs.py#L239-L245 |
delph-in/pydelphin | delphin/tfs.py | TypeHierarchy.descendants | def descendants(self, typename):
"""Return the descendant types of *typename*."""
xs = []
for child in self._hier[typename][1]:
xs.append(child)
xs.extend(self.descendants(child))
return xs | python | def descendants(self, typename):
"""Return the descendant types of *typename*."""
xs = []
for child in self._hier[typename][1]:
xs.append(child)
xs.extend(self.descendants(child))
return xs | Return the descendant types of *typename*. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tfs.py#L247-L253 |
delph-in/pydelphin | delphin/tfs.py | TypeHierarchy.subsumes | def subsumes(self, a, b):
"""Return `True` if type *a* subsumes type *b*."""
return a == b or b in self.descendants(a) | python | def subsumes(self, a, b):
"""Return `True` if type *a* subsumes type *b*."""
return a == b or b in self.descendants(a) | Return `True` if type *a* subsumes type *b*. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tfs.py#L255-L257 |
delph-in/pydelphin | delphin/tfs.py | TypeHierarchy.compatible | def compatible(self, a, b):
"""Return `True` if type *a* is compatible with type *b*."""
return len(set([a] + self.descendants(a))
.intersection([b] + self.descendants(b))) > 0 | python | def compatible(self, a, b):
"""Return `True` if type *a* is compatible with type *b*."""
return len(set([a] + self.descendants(a))
.intersection([b] + self.descendants(b))) > 0 | Return `True` if type *a* is compatible with type *b*. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tfs.py#L259-L262 |
delph-in/pydelphin | delphin/mrs/compare.py | isomorphic | def isomorphic(q, g, check_varprops=True):
"""
Return `True` if Xmrs objects *q* and *g* are isomorphic.
Isomorphicity compares the predicates of an Xmrs, the variable
properties of their predications (if `check_varprops=True`),
constant arguments, and the argument structure between
predications. Node IDs and Lnk values are ignored.
Args:
q: the left Xmrs to compare
g: the right Xmrs to compare
check_varprops: if `True`, make sure variable properties are
equal for mapped predications
"""
qdg = _make_digraph(q, check_varprops)
gdg = _make_digraph(g, check_varprops)
def nem(qd, gd): # node-edge-match
return qd.get('sig') == gd.get('sig')
return nx.is_isomorphic(qdg, gdg, node_match=nem, edge_match=nem) | python | def isomorphic(q, g, check_varprops=True):
"""
Return `True` if Xmrs objects *q* and *g* are isomorphic.
Isomorphicity compares the predicates of an Xmrs, the variable
properties of their predications (if `check_varprops=True`),
constant arguments, and the argument structure between
predications. Node IDs and Lnk values are ignored.
Args:
q: the left Xmrs to compare
g: the right Xmrs to compare
check_varprops: if `True`, make sure variable properties are
equal for mapped predications
"""
qdg = _make_digraph(q, check_varprops)
gdg = _make_digraph(g, check_varprops)
def nem(qd, gd): # node-edge-match
return qd.get('sig') == gd.get('sig')
return nx.is_isomorphic(qdg, gdg, node_match=nem, edge_match=nem) | Return `True` if Xmrs objects *q* and *g* are isomorphic.
Isomorphicity compares the predicates of an Xmrs, the variable
properties of their predications (if `check_varprops=True`),
constant arguments, and the argument structure between
predications. Node IDs and Lnk values are ignored.
Args:
q: the left Xmrs to compare
g: the right Xmrs to compare
check_varprops: if `True`, make sure variable properties are
equal for mapped predications | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/compare.py#L19-L39 |
delph-in/pydelphin | delphin/mrs/compare.py | _turbo_isomorphic | def _turbo_isomorphic(q, g, check_varprops=True):
"""
Query Xmrs q is isomorphic to given Xmrs g if there exists an
isomorphism (bijection of eps and vars) from q to g.
"""
# first some quick checks
if len(q.eps()) != len(g.eps()): return False
if len(q.variables()) != len(g.variables()): return False
#if len(a.hcons()) != len(b.hcons()): return False
try:
next(_isomorphisms(q, g, check_varprops=check_varprops))
return True
except StopIteration:
return False | python | def _turbo_isomorphic(q, g, check_varprops=True):
"""
Query Xmrs q is isomorphic to given Xmrs g if there exists an
isomorphism (bijection of eps and vars) from q to g.
"""
# first some quick checks
if len(q.eps()) != len(g.eps()): return False
if len(q.variables()) != len(g.variables()): return False
#if len(a.hcons()) != len(b.hcons()): return False
try:
next(_isomorphisms(q, g, check_varprops=check_varprops))
return True
except StopIteration:
return False | Query Xmrs q is isomorphic to given Xmrs g if there exists an
isomorphism (bijection of eps and vars) from q to g. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/compare.py#L65-L78 |
delph-in/pydelphin | delphin/mrs/compare.py | _isomorphisms | def _isomorphisms(q, g, check_varprops=True):
"""
Inspired by Turbo_ISO: http://dl.acm.org/citation.cfm?id=2465300
"""
# convert MRSs to be more graph-like, and add some indices
qig = _IsoGraph(q, varprops=check_varprops) # qig = q isograph
gig = _IsoGraph(g, varprops=check_varprops) # gig = q isograph
# qsigs, qsigidx = _isomorphism_sigs(q, check_varprops)
# gsigs, gsigidx = _isomorphism_sigs(g, check_varprops)
# (it would be nice to not have to do this... maybe later)
# qadj = _isomorphism_adj(q, qsigidx)
# gadj = _isomorphism_adj(g, gsigidx)
# the degree of each node is useful (but can it be combined with adj?)
# qdeg = _isomorphism_deg(qadj)
# gdeg = _isomorphism_deg(gadj)
u_s = _isomorphism_choose_start_q_vertex(qig, gig, subgraph=False)
q_ = _isomorphism_rewrite_to_NECtree(u_s, qig)
for v_s in gsigs.get(qsigidx[u_s], []):
cr = _isomorphism_explore_CR(q_, {v_s}, qig, gig)
if cr is None:
continue
order = _isomorphism_determine_matching_order(q_, cr)
update_state(M,F,{u_s}, {v_s})
subraph_search(q, q_, g, order, 1) # 1="the first query vertex to match"
restore_state(M, F, {u_s}, {v_s}) | python | def _isomorphisms(q, g, check_varprops=True):
"""
Inspired by Turbo_ISO: http://dl.acm.org/citation.cfm?id=2465300
"""
# convert MRSs to be more graph-like, and add some indices
qig = _IsoGraph(q, varprops=check_varprops) # qig = q isograph
gig = _IsoGraph(g, varprops=check_varprops) # gig = q isograph
# qsigs, qsigidx = _isomorphism_sigs(q, check_varprops)
# gsigs, gsigidx = _isomorphism_sigs(g, check_varprops)
# (it would be nice to not have to do this... maybe later)
# qadj = _isomorphism_adj(q, qsigidx)
# gadj = _isomorphism_adj(g, gsigidx)
# the degree of each node is useful (but can it be combined with adj?)
# qdeg = _isomorphism_deg(qadj)
# gdeg = _isomorphism_deg(gadj)
u_s = _isomorphism_choose_start_q_vertex(qig, gig, subgraph=False)
q_ = _isomorphism_rewrite_to_NECtree(u_s, qig)
for v_s in gsigs.get(qsigidx[u_s], []):
cr = _isomorphism_explore_CR(q_, {v_s}, qig, gig)
if cr is None:
continue
order = _isomorphism_determine_matching_order(q_, cr)
update_state(M,F,{u_s}, {v_s})
subraph_search(q, q_, g, order, 1) # 1="the first query vertex to match"
restore_state(M, F, {u_s}, {v_s}) | Inspired by Turbo_ISO: http://dl.acm.org/citation.cfm?id=2465300 | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/compare.py#L81-L106 |
delph-in/pydelphin | delphin/mrs/compare.py | _isomorphism_rewrite_to_NECtree | def _isomorphism_rewrite_to_NECtree(q_s, qgraph):
"""
Neighborhood Equivalence Class tree (see Turbo_ISO paper)
"""
qadj = qgraph.adj
adjsets = lambda x: set(chain.from_iterable(qadj[x].values()))
t = ([q_s], []) # (NEC_set, children)
visited = {q_s}
vcur, vnext = [t], []
while vcur:
for (nec, children) in vcur:
c = defaultdict(list)
for u in nec:
for sig, adjlist in qadj[u].items():
c[sig].extend(x for x, _, _ in adjlist if x not in visited)
for sig, c_adjlist in c.items():
visited.update(c_adjlist)
# these are already grouped by label; now group by adjacents
for key, grp in groupby(c_adjlist, key=adjsets):
grp = list(grp)
if len(grp) > 1:
children.append((list(grp), []))
else:
# NOTE: the paper says to look for mergeable things,
# but I don't know what else to merge by.
children.append((list(grp), []))
vnext.extend(children)
vcur, vnext = vnext, []
return t | python | def _isomorphism_rewrite_to_NECtree(q_s, qgraph):
"""
Neighborhood Equivalence Class tree (see Turbo_ISO paper)
"""
qadj = qgraph.adj
adjsets = lambda x: set(chain.from_iterable(qadj[x].values()))
t = ([q_s], []) # (NEC_set, children)
visited = {q_s}
vcur, vnext = [t], []
while vcur:
for (nec, children) in vcur:
c = defaultdict(list)
for u in nec:
for sig, adjlist in qadj[u].items():
c[sig].extend(x for x, _, _ in adjlist if x not in visited)
for sig, c_adjlist in c.items():
visited.update(c_adjlist)
# these are already grouped by label; now group by adjacents
for key, grp in groupby(c_adjlist, key=adjsets):
grp = list(grp)
if len(grp) > 1:
children.append((list(grp), []))
else:
# NOTE: the paper says to look for mergeable things,
# but I don't know what else to merge by.
children.append((list(grp), []))
vnext.extend(children)
vcur, vnext = vnext, []
return t | Neighborhood Equivalence Class tree (see Turbo_ISO paper) | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/compare.py#L183-L211 |
delph-in/pydelphin | delphin/mrs/compare.py | _node_isomorphic | def _node_isomorphic(a, b, check_varprops=True):
"""
Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds.
"""
# first some quick checks
a_var_refs = sorted(len(vd['refs']) for vd in a._vars.values())
b_var_refs = sorted(len(vd['refs']) for vd in b._vars.values())
if a_var_refs != b_var_refs:
return False
print()
# these signature: [node] indices are meant to avoid unnecessary
# comparisons; they also take care of "semantic feasibility"
# constraints (comparing node values and properties). All that's
# left is the "syntactic feasibility", or node-edge shapes.
# nodedicts are {sig: [(id, edges), ...], ...}
a_nd = _node_isomorphic_build_nodedict(a, check_varprops)
#print('a', a_nd)
b_nd = _node_isomorphic_build_nodedict(b, check_varprops)
#print('b', b_nd)
#return
a_sigs = {} # for node -> sig mapping
# don't recurse when things are unique
agenda = []
isomap = {}
for sig, a_pairs in sorted(a_nd.items(), key=lambda x: len(x[1])):
b_pairs = b_nd.get(sig, [])
if len(a_pairs) != len(b_pairs):
return False
if len(a_pairs) == 1:
a_, a_edges = a_pairs[0]
b_, b_edges = b_pairs[0]
if len(a_edges) != len(b_edges):
return False
a_sigs[a_] = sig
isomap[a_] = b_
for edge, a_tgt in a_edges.items():
if edge not in b_edges:
return False
isomap[a_tgt] = b_edges[edge]
else:
for a_, ed in a_pairs:
a_sigs[a_] = sig
agenda.append((a_, sig, ed))
#print(agenda)
#return
isomaps = _node_isomorphic(agenda, a_sigs, b_nd, isomap, {})
# for sig, a_candidates in sorted(a_nodes.items(), key=lambda x: len(x[1])):
# b_candidates = b_nodes.get(sig, [])
# if len(a_candidates) != len(b_candidates): return False
# candidates.append((a_candidates, b_candidates))
#
# nodemaps = _isomorphic(a, b, candidates, {})
try:
next(isomaps)
return True
except StopIteration:
return False | python | def _node_isomorphic(a, b, check_varprops=True):
"""
Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds.
"""
# first some quick checks
a_var_refs = sorted(len(vd['refs']) for vd in a._vars.values())
b_var_refs = sorted(len(vd['refs']) for vd in b._vars.values())
if a_var_refs != b_var_refs:
return False
print()
# these signature: [node] indices are meant to avoid unnecessary
# comparisons; they also take care of "semantic feasibility"
# constraints (comparing node values and properties). All that's
# left is the "syntactic feasibility", or node-edge shapes.
# nodedicts are {sig: [(id, edges), ...], ...}
a_nd = _node_isomorphic_build_nodedict(a, check_varprops)
#print('a', a_nd)
b_nd = _node_isomorphic_build_nodedict(b, check_varprops)
#print('b', b_nd)
#return
a_sigs = {} # for node -> sig mapping
# don't recurse when things are unique
agenda = []
isomap = {}
for sig, a_pairs in sorted(a_nd.items(), key=lambda x: len(x[1])):
b_pairs = b_nd.get(sig, [])
if len(a_pairs) != len(b_pairs):
return False
if len(a_pairs) == 1:
a_, a_edges = a_pairs[0]
b_, b_edges = b_pairs[0]
if len(a_edges) != len(b_edges):
return False
a_sigs[a_] = sig
isomap[a_] = b_
for edge, a_tgt in a_edges.items():
if edge not in b_edges:
return False
isomap[a_tgt] = b_edges[edge]
else:
for a_, ed in a_pairs:
a_sigs[a_] = sig
agenda.append((a_, sig, ed))
#print(agenda)
#return
isomaps = _node_isomorphic(agenda, a_sigs, b_nd, isomap, {})
# for sig, a_candidates in sorted(a_nodes.items(), key=lambda x: len(x[1])):
# b_candidates = b_nodes.get(sig, [])
# if len(a_candidates) != len(b_candidates): return False
# candidates.append((a_candidates, b_candidates))
#
# nodemaps = _isomorphic(a, b, candidates, {})
try:
next(isomaps)
return True
except StopIteration:
return False | Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/compare.py#L225-L284 |
delph-in/pydelphin | delphin/mrs/compare.py | _var_isomorphic | def _var_isomorphic(a, b, check_varprops=True):
"""
Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds.
"""
# first some quick checks
if len(a.eps()) != len(b.eps()): return False
if len(a.variables()) != len(b.variables()): return False
#if len(a.hcons()) != len(b.hcons()): return False
# pre-populate varmap; first top variables
varmap = {}
for pair in [(a.top, b.top), (a.index, b.index), (a.xarg, b.xarg)]:
if pair != (None, None):
v1, v2 = pair
if None in pair:
return False
if check_varprops and a.properties(v1) != b.properties(v2):
return False
varmap[v1] = v2
# find permutations of variables, grouped by those that share the
# same signature.
a_sigs = defaultdict(list)
for var, vd in a._vars.items():
if var not in varmap:
var_sig = _isomorphic_var_signature(vd, a, check_varprops)
a_sigs[var_sig].append(var)
b_sigs = defaultdict(list)
tgtmapped = set(varmap.values())
for var, vd in b._vars.items():
if var not in tgtmapped:
var_sig = _isomorphic_var_signature(vd, b, check_varprops)
b_sigs[var_sig].append(var)
candidates = []
for sig, a_vars in sorted(a_sigs.items(), key=lambda x: len(x[1])):
b_vars = b_sigs.get(sig, [])
if len(a_vars) != len(b_vars):
return False
print(sig, a_vars, b_vars)
candidates.append((a_vars, b_vars))
varmaps = _var_isomorphic(a, b, candidates, varmap)
# double check HCONS (it's hard to do with var signatures)
for vm in varmaps:
if all(vm[lo] == b._hcons.get(vm[hi], (None, None, None))[2]
for hi, _, lo in a.hcons()):
return True
return False | python | def _var_isomorphic(a, b, check_varprops=True):
"""
Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds.
"""
# first some quick checks
if len(a.eps()) != len(b.eps()): return False
if len(a.variables()) != len(b.variables()): return False
#if len(a.hcons()) != len(b.hcons()): return False
# pre-populate varmap; first top variables
varmap = {}
for pair in [(a.top, b.top), (a.index, b.index), (a.xarg, b.xarg)]:
if pair != (None, None):
v1, v2 = pair
if None in pair:
return False
if check_varprops and a.properties(v1) != b.properties(v2):
return False
varmap[v1] = v2
# find permutations of variables, grouped by those that share the
# same signature.
a_sigs = defaultdict(list)
for var, vd in a._vars.items():
if var not in varmap:
var_sig = _isomorphic_var_signature(vd, a, check_varprops)
a_sigs[var_sig].append(var)
b_sigs = defaultdict(list)
tgtmapped = set(varmap.values())
for var, vd in b._vars.items():
if var not in tgtmapped:
var_sig = _isomorphic_var_signature(vd, b, check_varprops)
b_sigs[var_sig].append(var)
candidates = []
for sig, a_vars in sorted(a_sigs.items(), key=lambda x: len(x[1])):
b_vars = b_sigs.get(sig, [])
if len(a_vars) != len(b_vars):
return False
print(sig, a_vars, b_vars)
candidates.append((a_vars, b_vars))
varmaps = _var_isomorphic(a, b, candidates, varmap)
# double check HCONS (it's hard to do with var signatures)
for vm in varmaps:
if all(vm[lo] == b._hcons.get(vm[hi], (None, None, None))[2]
for hi, _, lo in a.hcons()):
return True
return False | Two Xmrs objects are isomorphic if they have the same structure as
determined by variable linkages between preds. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/compare.py#L362-L413 |
delph-in/pydelphin | delphin/mrs/compare.py | compare_bags | def compare_bags(testbag, goldbag, count_only=True):
"""
Compare two bags of Xmrs objects, returning a triple of
(unique in test, shared, unique in gold).
Args:
testbag: An iterable of Xmrs objects to test.
goldbag: An iterable of Xmrs objects to compare against.
count_only: If True, the returned triple will only have the
counts of each; if False, a list of Xmrs objects will be
returned for each (using the ones from testbag for the
shared set)
Returns:
A triple of (unique in test, shared, unique in gold), where
each of the three items is an integer count if the count_only
parameter is True, or a list of Xmrs objects otherwise.
"""
gold_remaining = list(goldbag)
test_unique = []
shared = []
for test in testbag:
gold_match = None
for gold in gold_remaining:
if isomorphic(test, gold):
gold_match = gold
break
if gold_match is not None:
gold_remaining.remove(gold_match)
shared.append(test)
else:
test_unique.append(test)
if count_only:
return (len(test_unique), len(shared), len(gold_remaining))
else:
return (test_unique, shared, gold_remaining) | python | def compare_bags(testbag, goldbag, count_only=True):
"""
Compare two bags of Xmrs objects, returning a triple of
(unique in test, shared, unique in gold).
Args:
testbag: An iterable of Xmrs objects to test.
goldbag: An iterable of Xmrs objects to compare against.
count_only: If True, the returned triple will only have the
counts of each; if False, a list of Xmrs objects will be
returned for each (using the ones from testbag for the
shared set)
Returns:
A triple of (unique in test, shared, unique in gold), where
each of the three items is an integer count if the count_only
parameter is True, or a list of Xmrs objects otherwise.
"""
gold_remaining = list(goldbag)
test_unique = []
shared = []
for test in testbag:
gold_match = None
for gold in gold_remaining:
if isomorphic(test, gold):
gold_match = gold
break
if gold_match is not None:
gold_remaining.remove(gold_match)
shared.append(test)
else:
test_unique.append(test)
if count_only:
return (len(test_unique), len(shared), len(gold_remaining))
else:
return (test_unique, shared, gold_remaining) | Compare two bags of Xmrs objects, returning a triple of
(unique in test, shared, unique in gold).
Args:
testbag: An iterable of Xmrs objects to test.
goldbag: An iterable of Xmrs objects to compare against.
count_only: If True, the returned triple will only have the
counts of each; if False, a list of Xmrs objects will be
returned for each (using the ones from testbag for the
shared set)
Returns:
A triple of (unique in test, shared, unique in gold), where
each of the three items is an integer count if the count_only
parameter is True, or a list of Xmrs objects otherwise. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/compare.py#L458-L492 |
delph-in/pydelphin | delphin/tsql.py | query | def query(query, ts, **kwargs):
"""
Perform *query* on the testsuite *ts*.
Note: currently only 'select' queries are supported.
Args:
query (str): TSQL query string
ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over
kwargs: keyword arguments passed to the more specific query
function (e.g., :func:`select`)
Example:
>>> list(tsql.query('select i-id where i-length < 4', ts))
[[142], [1061]]
"""
queryobj = _parse_query(query)
if queryobj['querytype'] in ('select', 'retrieve'):
return _select(
queryobj['projection'],
queryobj['tables'],
queryobj['where'],
ts,
mode=kwargs.get('mode', 'list'),
cast=kwargs.get('cast', True))
else:
# not really a syntax error; replace with TSQLError or something
# when the proper exception class exists
raise TSQLSyntaxError(queryobj['querytype'] +
' queries are not supported') | python | def query(query, ts, **kwargs):
"""
Perform *query* on the testsuite *ts*.
Note: currently only 'select' queries are supported.
Args:
query (str): TSQL query string
ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over
kwargs: keyword arguments passed to the more specific query
function (e.g., :func:`select`)
Example:
>>> list(tsql.query('select i-id where i-length < 4', ts))
[[142], [1061]]
"""
queryobj = _parse_query(query)
if queryobj['querytype'] in ('select', 'retrieve'):
return _select(
queryobj['projection'],
queryobj['tables'],
queryobj['where'],
ts,
mode=kwargs.get('mode', 'list'),
cast=kwargs.get('cast', True))
else:
# not really a syntax error; replace with TSQLError or something
# when the proper exception class exists
raise TSQLSyntaxError(queryobj['querytype'] +
' queries are not supported') | Perform *query* on the testsuite *ts*.
Note: currently only 'select' queries are supported.
Args:
query (str): TSQL query string
ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over
kwargs: keyword arguments passed to the more specific query
function (e.g., :func:`select`)
Example:
>>> list(tsql.query('select i-id where i-length < 4', ts))
[[142], [1061]] | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tsql.py#L121-L150 |
delph-in/pydelphin | delphin/tsql.py | select | def select(query, ts, mode='list', cast=True):
"""
Perform the TSQL selection query *query* on testsuite *ts*.
Note: The `select`/`retrieve` part of the query is not included.
Args:
query (str): TSQL select query
ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over
mode (str): how to return the results (see
:func:`delphin.itsdb.select_rows` for more information
about the *mode* parameter; default: `list`)
cast (bool): if `True`, values will be cast to their datatype
according to the testsuite's relations (default: `True`)
Example:
>>> list(tsql.select('i-id where i-length < 4', ts))
[[142], [1061]]
"""
queryobj = _parse_select(query)
return _select(
queryobj['projection'],
queryobj['tables'],
queryobj['where'],
ts,
mode,
cast) | python | def select(query, ts, mode='list', cast=True):
"""
Perform the TSQL selection query *query* on testsuite *ts*.
Note: The `select`/`retrieve` part of the query is not included.
Args:
query (str): TSQL select query
ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over
mode (str): how to return the results (see
:func:`delphin.itsdb.select_rows` for more information
about the *mode* parameter; default: `list`)
cast (bool): if `True`, values will be cast to their datatype
according to the testsuite's relations (default: `True`)
Example:
>>> list(tsql.select('i-id where i-length < 4', ts))
[[142], [1061]]
"""
queryobj = _parse_select(query)
return _select(
queryobj['projection'],
queryobj['tables'],
queryobj['where'],
ts,
mode,
cast) | Perform the TSQL selection query *query* on testsuite *ts*.
Note: The `select`/`retrieve` part of the query is not included.
Args:
query (str): TSQL select query
ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over
mode (str): how to return the results (see
:func:`delphin.itsdb.select_rows` for more information
about the *mode* parameter; default: `list`)
cast (bool): if `True`, values will be cast to their datatype
according to the testsuite's relations (default: `True`)
Example:
>>> list(tsql.select('i-id where i-length < 4', ts))
[[142], [1061]] | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tsql.py#L153-L178 |
delph-in/pydelphin | delphin/tsql.py | _lex | def _lex(s):
"""
Lex the input string according to _tsql_lex_re.
Yields
(gid, token, line_number)
"""
s += '.' # make sure there's a terminator to know when to stop parsing
lines = enumerate(s.splitlines(), 1)
lineno = pos = 0
try:
for lineno, line in lines:
matches = _tsql_lex_re.finditer(line)
for m in matches:
gid = m.lastindex
if gid == 11:
raise TSQLSyntaxError('unexpected input',
lineno=lineno,
offset=m.start(),
text=line)
else:
token = m.group(gid)
yield (gid, token, lineno)
except StopIteration:
pass | python | def _lex(s):
"""
Lex the input string according to _tsql_lex_re.
Yields
(gid, token, line_number)
"""
s += '.' # make sure there's a terminator to know when to stop parsing
lines = enumerate(s.splitlines(), 1)
lineno = pos = 0
try:
for lineno, line in lines:
matches = _tsql_lex_re.finditer(line)
for m in matches:
gid = m.lastindex
if gid == 11:
raise TSQLSyntaxError('unexpected input',
lineno=lineno,
offset=m.start(),
text=line)
else:
token = m.group(gid)
yield (gid, token, lineno)
except StopIteration:
pass | Lex the input string according to _tsql_lex_re.
Yields
(gid, token, line_number) | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tsql.py#L333-L357 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.get_updates | def get_updates(self, offset=None, limit=None, timeout=None, allowed_updates=None):
"""
Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
Notes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting duplicate updates, recalculate offset after each server response.
https://core.telegram.org/bots/api#getupdates
Optional keyword parameters:
:param offset: 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 getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten.
: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 timeout: Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.
:type 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 getUpdates, so unwanted updates may be received for a short period of time.
:type allowed_updates: list of str|unicode
Returns:
:return: An Array of Update objects is returned
:rtype: list of pytgbot.api_types.receivable.updates.Update
"""
assert_type_or_raise(offset, None, int, parameter_name="offset")
assert_type_or_raise(limit, None, int, parameter_name="limit")
assert_type_or_raise(timeout, None, int, parameter_name="timeout")
assert_type_or_raise(allowed_updates, None, list, parameter_name="allowed_updates")
result = self.do("getUpdates", offset=offset, limit=limit, timeout=timeout, allowed_updates=allowed_updates)
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 | python | def get_updates(self, offset=None, limit=None, timeout=None, allowed_updates=None):
"""
Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
Notes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting duplicate updates, recalculate offset after each server response.
https://core.telegram.org/bots/api#getupdates
Optional keyword parameters:
:param offset: 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 getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten.
: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 timeout: Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.
:type 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 getUpdates, so unwanted updates may be received for a short period of time.
:type allowed_updates: list of str|unicode
Returns:
:return: An Array of Update objects is returned
:rtype: list of pytgbot.api_types.receivable.updates.Update
"""
assert_type_or_raise(offset, None, int, parameter_name="offset")
assert_type_or_raise(limit, None, int, parameter_name="limit")
assert_type_or_raise(timeout, None, int, parameter_name="timeout")
assert_type_or_raise(allowed_updates, None, list, parameter_name="allowed_updates")
result = self.do("getUpdates", offset=offset, limit=limit, timeout=timeout, allowed_updates=allowed_updates)
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 | Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
Notes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting duplicate updates, recalculate offset after each server response.
https://core.telegram.org/bots/api#getupdates
Optional keyword parameters:
:param offset: 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 getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten.
: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 timeout: Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.
:type 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 getUpdates, so unwanted updates may be received for a short period of time.
:type allowed_updates: list of str|unicode
Returns:
:return: An Array of Update objects is returned
:rtype: list of pytgbot.api_types.receivable.updates.Update | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L52-L101 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.set_webhook | def set_webhook(self, url, certificate=None, max_connections=None, allowed_updates=None):
"""
Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.
If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else knows your bot‘s token, you can be pretty sure it’s us.
Notes1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.3. Ports currently supported for Webhooks: 443, 80, 88, 8443.
NEW! If you're having any trouble setting up webhooks, please check out this amazing guide to Webhooks.
https://core.telegram.org/bots/api#setwebhook
Parameters:
:param url: HTTPS url to send updates to. Use an empty string to remove webhook integration
:type url: str|unicode
Optional keyword parameters:
:param certificate: Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details.
:type certificate: pytgbot.api_types.sendable.files.InputFile
:param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot‘s server, and higher values to increase your bot’s throughput.
:type max_connections: 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 setWebhook, so unwanted updates may be received for a short period of time.
:type allowed_updates: list of str|unicode
Returns:
:return: Returns True on success
:rtype: bool
"""
from pytgbot.api_types.sendable.files import InputFile
assert_type_or_raise(url, unicode_type, parameter_name="url")
assert_type_or_raise(certificate, None, InputFile, parameter_name="certificate")
assert_type_or_raise(max_connections, None, int, parameter_name="max_connections")
assert_type_or_raise(allowed_updates, None, list, parameter_name="allowed_updates")
result = self.do("setWebhook", url=url, certificate=certificate, max_connections=max_connections, allowed_updates=allowed_updates)
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 set_webhook(self, url, certificate=None, max_connections=None, allowed_updates=None):
"""
Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.
If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else knows your bot‘s token, you can be pretty sure it’s us.
Notes1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.3. Ports currently supported for Webhooks: 443, 80, 88, 8443.
NEW! If you're having any trouble setting up webhooks, please check out this amazing guide to Webhooks.
https://core.telegram.org/bots/api#setwebhook
Parameters:
:param url: HTTPS url to send updates to. Use an empty string to remove webhook integration
:type url: str|unicode
Optional keyword parameters:
:param certificate: Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details.
:type certificate: pytgbot.api_types.sendable.files.InputFile
:param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot‘s server, and higher values to increase your bot’s throughput.
:type max_connections: 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 setWebhook, so unwanted updates may be received for a short period of time.
:type allowed_updates: list of str|unicode
Returns:
:return: Returns True on success
:rtype: bool
"""
from pytgbot.api_types.sendable.files import InputFile
assert_type_or_raise(url, unicode_type, parameter_name="url")
assert_type_or_raise(certificate, None, InputFile, parameter_name="certificate")
assert_type_or_raise(max_connections, None, int, parameter_name="max_connections")
assert_type_or_raise(allowed_updates, None, list, parameter_name="allowed_updates")
result = self.do("setWebhook", url=url, certificate=certificate, max_connections=max_connections, allowed_updates=allowed_updates)
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 specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.
If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else knows your bot‘s token, you can be pretty sure it’s us.
Notes1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.3. Ports currently supported for Webhooks: 443, 80, 88, 8443.
NEW! If you're having any trouble setting up webhooks, please check out this amazing guide to Webhooks.
https://core.telegram.org/bots/api#setwebhook
Parameters:
:param url: HTTPS url to send updates to. Use an empty string to remove webhook integration
:type url: str|unicode
Optional keyword parameters:
:param certificate: Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details.
:type certificate: pytgbot.api_types.sendable.files.InputFile
:param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot‘s server, and higher values to increase your bot’s throughput.
:type max_connections: 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 setWebhook, so unwanted updates may be received for a short period of time.
:type allowed_updates: list of str|unicode
Returns:
:return: Returns True on success
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L104-L159 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.delete_webhook | def delete_webhook(self, ):
"""
Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.
https://core.telegram.org/bots/api#deletewebhook
Returns:
:return: Returns True on success
:rtype: bool
"""
result = self.do("deleteWebhook", )
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 delete_webhook(self, ):
"""
Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.
https://core.telegram.org/bots/api#deletewebhook
Returns:
:return: Returns True on success
:rtype: bool
"""
result = self.do("deleteWebhook", )
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 remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.
https://core.telegram.org/bots/api#deletewebhook
Returns:
:return: Returns True on success
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L162-L186 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.get_webhook_info | def get_webhook_info(self, ):
"""
Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
https://core.telegram.org/bots/api#getwebhookinfo
Returns:
:return: On success, returns a WebhookInfo object
:rtype: pytgbot.api_types.receivable.updates.WebhookInfo
"""
result = self.do("getWebhookInfo", )
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.updates import WebhookInfo
try:
return WebhookInfo.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type WebhookInfo", 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_webhook_info(self, ):
"""
Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
https://core.telegram.org/bots/api#getwebhookinfo
Returns:
:return: On success, returns a WebhookInfo object
:rtype: pytgbot.api_types.receivable.updates.WebhookInfo
"""
result = self.do("getWebhookInfo", )
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.updates import WebhookInfo
try:
return WebhookInfo.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type WebhookInfo", 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 get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
https://core.telegram.org/bots/api#getwebhookinfo
Returns:
:return: On success, returns a WebhookInfo object
:rtype: pytgbot.api_types.receivable.updates.WebhookInfo | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L189-L214 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.send_photo | def send_photo(self, chat_id, photo, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send photos. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendphoto
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 photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. More info on Sending Files »
:type photo: pytgbot.api_types.sendable.files.InputFile | str|unicode
Optional keyword parameters:
:param caption: Photo caption (may also be used when resending photos by file_id), 0-1024 characters
:type caption: str|unicode
:param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption.
:type parse_mode: str|unicode
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message
"""
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
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(photo, (InputFile, unicode_type), parameter_name="photo")
assert_type_or_raise(caption, None, unicode_type, parameter_name="caption")
assert_type_or_raise(parse_mode, None, unicode_type, parameter_name="parse_mode")
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")
assert_type_or_raise(reply_markup, None, (InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply), parameter_name="reply_markup")
result = self.do("sendPhoto", chat_id=chat_id, photo=photo, caption=caption, parse_mode=parse_mode, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
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 send_photo(self, chat_id, photo, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send photos. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendphoto
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 photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. More info on Sending Files »
:type photo: pytgbot.api_types.sendable.files.InputFile | str|unicode
Optional keyword parameters:
:param caption: Photo caption (may also be used when resending photos by file_id), 0-1024 characters
:type caption: str|unicode
:param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption.
:type parse_mode: str|unicode
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message
"""
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
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(photo, (InputFile, unicode_type), parameter_name="photo")
assert_type_or_raise(caption, None, unicode_type, parameter_name="caption")
assert_type_or_raise(parse_mode, None, unicode_type, parameter_name="parse_mode")
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")
assert_type_or_raise(reply_markup, None, (InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply), parameter_name="reply_markup")
result = self.do("sendPhoto", chat_id=chat_id, photo=photo, caption=caption, parse_mode=parse_mode, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
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 send photos. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendphoto
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 photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. More info on Sending Files »
:type photo: pytgbot.api_types.sendable.files.InputFile | str|unicode
Optional keyword parameters:
:param caption: Photo caption (may also be used when resending photos by file_id), 0-1024 characters
:type caption: str|unicode
:param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption.
:type parse_mode: str|unicode
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L369-L439 |
luckydonald/pytgbot | code_generation/output/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 JSON-serialized array describing photos and videos to be sent, must include 2–10 items
:type media: list of pytgbot.api_types.sendable.input_media.InputMediaPhoto | list of 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: list of pytgbot.api_types.receivable.updates.Message
"""
from pytgbot.api_types.sendable.input_media import InputMediaPhoto
from pytgbot.api_types.sendable.input_media import InputMediaVideo
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(media, (list, list), parameter_name="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=media, 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)))
from pytgbot.api_types.receivable.updates import Message
try:
return Message.from_array_list(result, list_level=1)
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 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 JSON-serialized array describing photos and videos to be sent, must include 2–10 items
:type media: list of pytgbot.api_types.sendable.input_media.InputMediaPhoto | list of 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: list of pytgbot.api_types.receivable.updates.Message
"""
from pytgbot.api_types.sendable.input_media import InputMediaPhoto
from pytgbot.api_types.sendable.input_media import InputMediaVideo
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(media, (list, list), parameter_name="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=media, 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)))
from pytgbot.api_types.receivable.updates import Message
try:
return Message.from_array_list(result, list_level=1)
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 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 JSON-serialized array describing photos and videos to be sent, must include 2–10 items
:type media: list of pytgbot.api_types.sendable.input_media.InputMediaPhoto | list of 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: list of pytgbot.api_types.receivable.updates.Message | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L961-L1013 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.send_location | def send_location(self, chat_id, latitude, longitude, live_period=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send point on the map. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendlocation
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 latitude: Latitude of the location
:type latitude: float
:param longitude: Longitude of the location
:type longitude: float
Optional keyword parameters:
:param live_period: Period in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400.
:type live_period: int
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message
"""
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
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(latitude, float, parameter_name="latitude")
assert_type_or_raise(longitude, float, parameter_name="longitude")
assert_type_or_raise(live_period, None, int, parameter_name="live_period")
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")
assert_type_or_raise(reply_markup, None, (InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply), parameter_name="reply_markup")
result = self.do("sendLocation", chat_id=chat_id, latitude=latitude, longitude=longitude, live_period=live_period, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
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 send_location(self, chat_id, latitude, longitude, live_period=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send point on the map. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendlocation
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 latitude: Latitude of the location
:type latitude: float
:param longitude: Longitude of the location
:type longitude: float
Optional keyword parameters:
:param live_period: Period in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400.
:type live_period: int
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message
"""
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
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(latitude, float, parameter_name="latitude")
assert_type_or_raise(longitude, float, parameter_name="longitude")
assert_type_or_raise(live_period, None, int, parameter_name="live_period")
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")
assert_type_or_raise(reply_markup, None, (InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply), parameter_name="reply_markup")
result = self.do("sendLocation", chat_id=chat_id, latitude=latitude, longitude=longitude, live_period=live_period, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
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 send point on the map. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendlocation
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 latitude: Latitude of the location
:type latitude: float
:param longitude: Longitude of the location
:type longitude: float
Optional keyword parameters:
:param live_period: Period in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400.
:type live_period: int
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L1016-L1085 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.send_contact | def send_contact(self, chat_id, phone_number, first_name, last_name=None, vcard=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send phone contacts. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendcontact
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 phone_number: Contact's phone number
:type phone_number: str|unicode
:param first_name: Contact's first name
:type first_name: str|unicode
Optional keyword parameters:
:param last_name: Contact's last name
:type last_name: str|unicode
:param vcard: Additional data about the contact in the form of a vCard, 0-2048 bytes
:type vcard: str|unicode
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove keyboard or to force a reply from the user.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message
"""
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
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(phone_number, unicode_type, parameter_name="phone_number")
assert_type_or_raise(first_name, unicode_type, parameter_name="first_name")
assert_type_or_raise(last_name, None, unicode_type, parameter_name="last_name")
assert_type_or_raise(vcard, None, unicode_type, parameter_name="vcard")
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")
assert_type_or_raise(reply_markup, None, (InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply), parameter_name="reply_markup")
result = self.do("sendContact", chat_id=chat_id, phone_number=phone_number, first_name=first_name, last_name=last_name, vcard=vcard, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
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 send_contact(self, chat_id, phone_number, first_name, last_name=None, vcard=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send phone contacts. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendcontact
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 phone_number: Contact's phone number
:type phone_number: str|unicode
:param first_name: Contact's first name
:type first_name: str|unicode
Optional keyword parameters:
:param last_name: Contact's last name
:type last_name: str|unicode
:param vcard: Additional data about the contact in the form of a vCard, 0-2048 bytes
:type vcard: str|unicode
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove keyboard or to force a reply from the user.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message
"""
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
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(phone_number, unicode_type, parameter_name="phone_number")
assert_type_or_raise(first_name, unicode_type, parameter_name="first_name")
assert_type_or_raise(last_name, None, unicode_type, parameter_name="last_name")
assert_type_or_raise(vcard, None, unicode_type, parameter_name="vcard")
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")
assert_type_or_raise(reply_markup, None, (InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply), parameter_name="reply_markup")
result = self.do("sendContact", chat_id=chat_id, phone_number=phone_number, first_name=first_name, last_name=last_name, vcard=vcard, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
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 send phone contacts. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendcontact
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 phone_number: Contact's phone number
:type phone_number: str|unicode
:param first_name: Contact's first name
:type first_name: str|unicode
Optional keyword parameters:
:param last_name: Contact's last name
:type last_name: str|unicode
:param vcard: Additional data about the contact in the form of a vCard, 0-2048 bytes
:type vcard: str|unicode
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove keyboard or to force a reply from the user.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L1302-L1376 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.get_user_profile_photos | def get_user_profile_photos(self, user_id, offset=None, limit=None):
"""
Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
https://core.telegram.org/bots/api#getuserprofilephotos
Parameters:
:param user_id: Unique identifier of the target user
:type user_id: int
Optional keyword parameters:
:param offset: Sequential number of the first photo to be returned. By default, all photos are returned.
:type offset: int
:param limit: Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.
:type limit: int
Returns:
:return: Returns a UserProfilePhotos object
:rtype: pytgbot.api_types.receivable.media.UserProfilePhotos
"""
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(offset, None, int, parameter_name="offset")
assert_type_or_raise(limit, None, int, parameter_name="limit")
result = self.do("getUserProfilePhotos", user_id=user_id, offset=offset, limit=limit)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.media import UserProfilePhotos
try:
return UserProfilePhotos.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type UserProfilePhotos", 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_user_profile_photos(self, user_id, offset=None, limit=None):
"""
Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
https://core.telegram.org/bots/api#getuserprofilephotos
Parameters:
:param user_id: Unique identifier of the target user
:type user_id: int
Optional keyword parameters:
:param offset: Sequential number of the first photo to be returned. By default, all photos are returned.
:type offset: int
:param limit: Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.
:type limit: int
Returns:
:return: Returns a UserProfilePhotos object
:rtype: pytgbot.api_types.receivable.media.UserProfilePhotos
"""
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(offset, None, int, parameter_name="offset")
assert_type_or_raise(limit, None, int, parameter_name="limit")
result = self.do("getUserProfilePhotos", user_id=user_id, offset=offset, limit=limit)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.media import UserProfilePhotos
try:
return UserProfilePhotos.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type UserProfilePhotos", 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 get a list of profile pictures for a user. Returns a UserProfilePhotos object.
https://core.telegram.org/bots/api#getuserprofilephotos
Parameters:
:param user_id: Unique identifier of the target user
:type user_id: int
Optional keyword parameters:
:param offset: Sequential number of the first photo to be returned. By default, all photos are returned.
:type offset: int
:param limit: Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.
:type limit: int
Returns:
:return: Returns a UserProfilePhotos object
:rtype: pytgbot.api_types.receivable.media.UserProfilePhotos | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L1422-L1466 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.get_file | def get_file(self, file_id):
"""
Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.
https://core.telegram.org/bots/api#getfile
Parameters:
:param file_id: File identifier to get info about
:type file_id: str|unicode
Returns:
:return: On success, a File object is returned
:rtype: pytgbot.api_types.receivable.media.File
"""
assert_type_or_raise(file_id, unicode_type, parameter_name="file_id")
result = self.do("getFile", file_id=file_id)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.media import File
try:
return File.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type File", 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_file(self, file_id):
"""
Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.
https://core.telegram.org/bots/api#getfile
Parameters:
:param file_id: File identifier to get info about
:type file_id: str|unicode
Returns:
:return: On success, a File object is returned
:rtype: pytgbot.api_types.receivable.media.File
"""
assert_type_or_raise(file_id, unicode_type, parameter_name="file_id")
result = self.do("getFile", file_id=file_id)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.media import File
try:
return File.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type File", 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 get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.
https://core.telegram.org/bots/api#getfile
Parameters:
:param file_id: File identifier to get info about
:type file_id: str|unicode
Returns:
:return: On success, a File object is returned
:rtype: pytgbot.api_types.receivable.media.File | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L1469-L1502 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.restrict_chat_member | def restrict_chat_member(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None):
"""
Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success.
https://core.telegram.org/bots/api#restrictchatmember
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
:type chat_id: int | str|unicode
:param user_id: Unique identifier of the target user
:type user_id: int
Optional keyword parameters:
:param until_date: Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever
:type until_date: int
:param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues
:type can_send_messages: bool
:param can_send_media_messages: Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages
:type can_send_media_messages: bool
:param can_send_other_messages: Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages
:type can_send_other_messages: bool
:param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, implies can_send_media_messages
:type can_add_web_page_previews: bool
Returns:
:return: Returns True on success
:rtype: bool
"""
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(until_date, None, int, parameter_name="until_date")
assert_type_or_raise(can_send_messages, None, bool, parameter_name="can_send_messages")
assert_type_or_raise(can_send_media_messages, None, bool, parameter_name="can_send_media_messages")
assert_type_or_raise(can_send_other_messages, None, bool, parameter_name="can_send_other_messages")
assert_type_or_raise(can_add_web_page_previews, None, bool, parameter_name="can_add_web_page_previews")
result = self.do("restrictChatMember", chat_id=chat_id, user_id=user_id, until_date=until_date, can_send_messages=can_send_messages, can_send_media_messages=can_send_media_messages, can_send_other_messages=can_send_other_messages, can_add_web_page_previews=can_add_web_page_previews)
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 restrict_chat_member(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None):
"""
Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success.
https://core.telegram.org/bots/api#restrictchatmember
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
:type chat_id: int | str|unicode
:param user_id: Unique identifier of the target user
:type user_id: int
Optional keyword parameters:
:param until_date: Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever
:type until_date: int
:param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues
:type can_send_messages: bool
:param can_send_media_messages: Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages
:type can_send_media_messages: bool
:param can_send_other_messages: Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages
:type can_send_other_messages: bool
:param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, implies can_send_media_messages
:type can_add_web_page_previews: bool
Returns:
:return: Returns True on success
:rtype: bool
"""
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(until_date, None, int, parameter_name="until_date")
assert_type_or_raise(can_send_messages, None, bool, parameter_name="can_send_messages")
assert_type_or_raise(can_send_media_messages, None, bool, parameter_name="can_send_media_messages")
assert_type_or_raise(can_send_other_messages, None, bool, parameter_name="can_send_other_messages")
assert_type_or_raise(can_add_web_page_previews, None, bool, parameter_name="can_add_web_page_previews")
result = self.do("restrictChatMember", chat_id=chat_id, user_id=user_id, until_date=until_date, can_send_messages=can_send_messages, can_send_media_messages=can_send_media_messages, can_send_other_messages=can_send_other_messages, can_add_web_page_previews=can_add_web_page_previews)
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 restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success.
https://core.telegram.org/bots/api#restrictchatmember
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
:type chat_id: int | str|unicode
:param user_id: Unique identifier of the target user
:type user_id: int
Optional keyword parameters:
:param until_date: Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever
:type until_date: int
:param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues
:type can_send_messages: bool
:param can_send_media_messages: Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages
:type can_send_media_messages: bool
:param can_send_other_messages: Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages
:type can_send_other_messages: bool
:param can_add_web_page_previews: Pass True, if the user may add web page previews to their messages, implies can_send_media_messages
:type can_add_web_page_previews: bool
Returns:
:return: Returns True on success
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L1593-L1656 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.promote_chat_member | def promote_chat_member(self, chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None):
"""
Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success.
https://core.telegram.org/bots/api#promotechatmember
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 user_id: Unique identifier of the target user
:type user_id: int
Optional keyword parameters:
:param can_change_info: Pass True, if the administrator can change chat title, photo and other settings
:type can_change_info: bool
:param can_post_messages: Pass True, if the administrator can create channel posts, channels only
:type can_post_messages: bool
:param can_edit_messages: Pass True, if the administrator can edit messages of other users and can pin messages, channels only
:type can_edit_messages: bool
:param can_delete_messages: Pass True, if the administrator can delete messages of other users
:type can_delete_messages: bool
:param can_invite_users: Pass True, if the administrator can invite new users to the chat
:type can_invite_users: bool
:param can_restrict_members: Pass True, if the administrator can restrict, ban or unban chat members
:type can_restrict_members: bool
:param can_pin_messages: Pass True, if the administrator can pin messages, supergroups only
:type can_pin_messages: bool
:param can_promote_members: Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him)
:type can_promote_members: bool
Returns:
:return: Returns True on success
:rtype: bool
"""
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(can_change_info, None, bool, parameter_name="can_change_info")
assert_type_or_raise(can_post_messages, None, bool, parameter_name="can_post_messages")
assert_type_or_raise(can_edit_messages, None, bool, parameter_name="can_edit_messages")
assert_type_or_raise(can_delete_messages, None, bool, parameter_name="can_delete_messages")
assert_type_or_raise(can_invite_users, None, bool, parameter_name="can_invite_users")
assert_type_or_raise(can_restrict_members, None, bool, parameter_name="can_restrict_members")
assert_type_or_raise(can_pin_messages, None, bool, parameter_name="can_pin_messages")
assert_type_or_raise(can_promote_members, None, bool, parameter_name="can_promote_members")
result = self.do("promoteChatMember", chat_id=chat_id, user_id=user_id, can_change_info=can_change_info, can_post_messages=can_post_messages, can_edit_messages=can_edit_messages, can_delete_messages=can_delete_messages, can_invite_users=can_invite_users, can_restrict_members=can_restrict_members, can_pin_messages=can_pin_messages, can_promote_members=can_promote_members)
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 promote_chat_member(self, chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None):
"""
Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success.
https://core.telegram.org/bots/api#promotechatmember
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 user_id: Unique identifier of the target user
:type user_id: int
Optional keyword parameters:
:param can_change_info: Pass True, if the administrator can change chat title, photo and other settings
:type can_change_info: bool
:param can_post_messages: Pass True, if the administrator can create channel posts, channels only
:type can_post_messages: bool
:param can_edit_messages: Pass True, if the administrator can edit messages of other users and can pin messages, channels only
:type can_edit_messages: bool
:param can_delete_messages: Pass True, if the administrator can delete messages of other users
:type can_delete_messages: bool
:param can_invite_users: Pass True, if the administrator can invite new users to the chat
:type can_invite_users: bool
:param can_restrict_members: Pass True, if the administrator can restrict, ban or unban chat members
:type can_restrict_members: bool
:param can_pin_messages: Pass True, if the administrator can pin messages, supergroups only
:type can_pin_messages: bool
:param can_promote_members: Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him)
:type can_promote_members: bool
Returns:
:return: Returns True on success
:rtype: bool
"""
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(can_change_info, None, bool, parameter_name="can_change_info")
assert_type_or_raise(can_post_messages, None, bool, parameter_name="can_post_messages")
assert_type_or_raise(can_edit_messages, None, bool, parameter_name="can_edit_messages")
assert_type_or_raise(can_delete_messages, None, bool, parameter_name="can_delete_messages")
assert_type_or_raise(can_invite_users, None, bool, parameter_name="can_invite_users")
assert_type_or_raise(can_restrict_members, None, bool, parameter_name="can_restrict_members")
assert_type_or_raise(can_pin_messages, None, bool, parameter_name="can_pin_messages")
assert_type_or_raise(can_promote_members, None, bool, parameter_name="can_promote_members")
result = self.do("promoteChatMember", chat_id=chat_id, user_id=user_id, can_change_info=can_change_info, can_post_messages=can_post_messages, can_edit_messages=can_edit_messages, can_delete_messages=can_delete_messages, can_invite_users=can_invite_users, can_restrict_members=can_restrict_members, can_pin_messages=can_pin_messages, can_promote_members=can_promote_members)
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 promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success.
https://core.telegram.org/bots/api#promotechatmember
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 user_id: Unique identifier of the target user
:type user_id: int
Optional keyword parameters:
:param can_change_info: Pass True, if the administrator can change chat title, photo and other settings
:type can_change_info: bool
:param can_post_messages: Pass True, if the administrator can create channel posts, channels only
:type can_post_messages: bool
:param can_edit_messages: Pass True, if the administrator can edit messages of other users and can pin messages, channels only
:type can_edit_messages: bool
:param can_delete_messages: Pass True, if the administrator can delete messages of other users
:type can_delete_messages: bool
:param can_invite_users: Pass True, if the administrator can invite new users to the chat
:type can_invite_users: bool
:param can_restrict_members: Pass True, if the administrator can restrict, ban or unban chat members
:type can_restrict_members: bool
:param can_pin_messages: Pass True, if the administrator can pin messages, supergroups only
:type can_pin_messages: bool
:param can_promote_members: Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him)
:type can_promote_members: bool
Returns:
:return: Returns True on success
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L1659-L1737 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.set_chat_photo | def set_chat_photo(self, chat_id, photo):
"""
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.
https://core.telegram.org/bots/api#setchatphoto
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 photo: New chat photo, uploaded using multipart/form-data
:type photo: pytgbot.api_types.sendable.files.InputFile
Returns:
:return: Returns True on success
:rtype: bool
"""
from pytgbot.api_types.sendable.files import InputFile
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(photo, InputFile, parameter_name="photo")
result = self.do("setChatPhoto", chat_id=chat_id, photo=photo)
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 set_chat_photo(self, chat_id, photo):
"""
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.
https://core.telegram.org/bots/api#setchatphoto
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 photo: New chat photo, uploaded using multipart/form-data
:type photo: pytgbot.api_types.sendable.files.InputFile
Returns:
:return: Returns True on success
:rtype: bool
"""
from pytgbot.api_types.sendable.files import InputFile
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(photo, InputFile, parameter_name="photo")
result = self.do("setChatPhoto", chat_id=chat_id, photo=photo)
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 set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.
https://core.telegram.org/bots/api#setchatphoto
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 photo: New chat photo, uploaded using multipart/form-data
:type photo: pytgbot.api_types.sendable.files.InputFile
Returns:
:return: Returns True on success
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L1777-L1818 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.get_chat | def get_chat(self, chat_id):
"""
Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
https://core.telegram.org/bots/api#getchat
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
:type chat_id: int | str|unicode
Returns:
:return: Returns a Chat object on success
:rtype: pytgbot.api_types.receivable.peer.Chat
"""
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
result = self.do("getChat", chat_id=chat_id)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.peer import Chat
try:
return Chat.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type Chat", 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_chat(self, chat_id):
"""
Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
https://core.telegram.org/bots/api#getchat
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
:type chat_id: int | str|unicode
Returns:
:return: Returns a Chat object on success
:rtype: pytgbot.api_types.receivable.peer.Chat
"""
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
result = self.do("getChat", chat_id=chat_id)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.peer import Chat
try:
return Chat.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type Chat", 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 get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
https://core.telegram.org/bots/api#getchat
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
:type chat_id: int | str|unicode
Returns:
:return: Returns a Chat object on success
:rtype: pytgbot.api_types.receivable.peer.Chat | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2055-L2087 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.get_chat_administrators | def get_chat_administrators(self, chat_id):
"""
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
https://core.telegram.org/bots/api#getchatadministrators
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
:type chat_id: int | str|unicode
Returns:
:return: On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots
:rtype: list of pytgbot.api_types.receivable.peer.ChatMember
"""
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
result = self.do("getChatAdministrators", chat_id=chat_id)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.peer import ChatMember
try:
return ChatMember.from_array_list(result, list_level=1)
except TgApiParseException:
logger.debug("Failed parsing as api_type ChatMember", 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_chat_administrators(self, chat_id):
"""
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
https://core.telegram.org/bots/api#getchatadministrators
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
:type chat_id: int | str|unicode
Returns:
:return: On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots
:rtype: list of pytgbot.api_types.receivable.peer.ChatMember
"""
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
result = self.do("getChatAdministrators", chat_id=chat_id)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.peer import ChatMember
try:
return ChatMember.from_array_list(result, list_level=1)
except TgApiParseException:
logger.debug("Failed parsing as api_type ChatMember", 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 get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
https://core.telegram.org/bots/api#getchatadministrators
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
:type chat_id: int | str|unicode
Returns:
:return: On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots
:rtype: list of pytgbot.api_types.receivable.peer.ChatMember | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2090-L2122 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.set_chat_sticker_set | def set_chat_sticker_set(self, chat_id, sticker_set_name):
"""
Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
https://core.telegram.org/bots/api#setchatstickerset
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
:type chat_id: int | str|unicode
:param sticker_set_name: Name of the sticker set to be set as the group sticker set
:type sticker_set_name: str|unicode
Returns:
:return: Returns True on success
:rtype: bool
"""
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(sticker_set_name, unicode_type, parameter_name="sticker_set_name")
result = self.do("setChatStickerSet", chat_id=chat_id, sticker_set_name=sticker_set_name)
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 set_chat_sticker_set(self, chat_id, sticker_set_name):
"""
Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
https://core.telegram.org/bots/api#setchatstickerset
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
:type chat_id: int | str|unicode
:param sticker_set_name: Name of the sticker set to be set as the group sticker set
:type sticker_set_name: str|unicode
Returns:
:return: Returns True on success
:rtype: bool
"""
assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
assert_type_or_raise(sticker_set_name, unicode_type, parameter_name="sticker_set_name")
result = self.do("setChatStickerSet", chat_id=chat_id, sticker_set_name=sticker_set_name)
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 set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
https://core.telegram.org/bots/api#setchatstickerset
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
:type chat_id: int | str|unicode
:param sticker_set_name: Name of the sticker set to be set as the group sticker set
:type sticker_set_name: str|unicode
Returns:
:return: Returns True on success
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2199-L2235 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.answer_callback_query | def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None):
"""
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @Botfather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
https://core.telegram.org/bots/api#answercallbackquery
Parameters:
:param callback_query_id: Unique identifier for the query to be answered
:type callback_query_id: str|unicode
Optional keyword parameters:
:param text: Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters
:type text: str|unicode
:param show_alert: If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false.
:type show_alert: bool
:param url: URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
:type url: str|unicode
:param cache_time: The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.
:type cache_time: int
Returns:
:return: On success, True is returned
:rtype: bool
"""
assert_type_or_raise(callback_query_id, unicode_type, parameter_name="callback_query_id")
assert_type_or_raise(text, None, unicode_type, parameter_name="text")
assert_type_or_raise(show_alert, None, bool, parameter_name="show_alert")
assert_type_or_raise(url, None, unicode_type, parameter_name="url")
assert_type_or_raise(cache_time, None, int, parameter_name="cache_time")
result = self.do("answerCallbackQuery", callback_query_id=callback_query_id, text=text, show_alert=show_alert, url=url, cache_time=cache_time)
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_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None):
"""
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @Botfather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
https://core.telegram.org/bots/api#answercallbackquery
Parameters:
:param callback_query_id: Unique identifier for the query to be answered
:type callback_query_id: str|unicode
Optional keyword parameters:
:param text: Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters
:type text: str|unicode
:param show_alert: If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false.
:type show_alert: bool
:param url: URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
:type url: str|unicode
:param cache_time: The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.
:type cache_time: int
Returns:
:return: On success, True is returned
:rtype: bool
"""
assert_type_or_raise(callback_query_id, unicode_type, parameter_name="callback_query_id")
assert_type_or_raise(text, None, unicode_type, parameter_name="text")
assert_type_or_raise(show_alert, None, bool, parameter_name="show_alert")
assert_type_or_raise(url, None, unicode_type, parameter_name="url")
assert_type_or_raise(cache_time, None, int, parameter_name="cache_time")
result = self.do("answerCallbackQuery", callback_query_id=callback_query_id, text=text, show_alert=show_alert, url=url, cache_time=cache_time)
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 callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @Botfather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
https://core.telegram.org/bots/api#answercallbackquery
Parameters:
:param callback_query_id: Unique identifier for the query to be answered
:type callback_query_id: str|unicode
Optional keyword parameters:
:param text: Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters
:type text: str|unicode
:param show_alert: If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false.
:type show_alert: bool
:param url: URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
:type url: str|unicode
:param cache_time: The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.
:type cache_time: int
Returns:
:return: On success, True is returned
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2272-L2328 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.edit_message_text | def edit_message_text(self, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, disable_web_page_preview=None, reply_markup=None):
"""
Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
https://core.telegram.org/bots/api#editmessagetext
Parameters:
:param text: New text of the message
:type text: str|unicode
Optional keyword parameters:
: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 | str|unicode
: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
:param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.
:type parse_mode: str|unicode
:param disable_web_page_preview: Disables link previews for links in this message
:type disable_web_page_preview: bool
:param reply_markup: A JSON-serialized object for an inline keyboard.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup
Returns:
:return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned
:rtype: pytgbot.api_types.receivable.updates.Message | bool
"""
from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup
assert_type_or_raise(text, unicode_type, parameter_name="text")
assert_type_or_raise(chat_id, None, (int, unicode_type), 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")
assert_type_or_raise(parse_mode, None, unicode_type, parameter_name="parse_mode")
assert_type_or_raise(disable_web_page_preview, None, bool, parameter_name="disable_web_page_preview")
assert_type_or_raise(reply_markup, None, InlineKeyboardMarkup, parameter_name="reply_markup")
result = self.do("editMessageText", text=text, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id, parse_mode=parse_mode, disable_web_page_preview=disable_web_page_preview, reply_markup=reply_markup)
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 edit_message_text(self, text, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, disable_web_page_preview=None, reply_markup=None):
"""
Use this method to edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
https://core.telegram.org/bots/api#editmessagetext
Parameters:
:param text: New text of the message
:type text: str|unicode
Optional keyword parameters:
: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 | str|unicode
: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
:param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.
:type parse_mode: str|unicode
:param disable_web_page_preview: Disables link previews for links in this message
:type disable_web_page_preview: bool
:param reply_markup: A JSON-serialized object for an inline keyboard.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup
Returns:
:return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned
:rtype: pytgbot.api_types.receivable.updates.Message | bool
"""
from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup
assert_type_or_raise(text, unicode_type, parameter_name="text")
assert_type_or_raise(chat_id, None, (int, unicode_type), 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")
assert_type_or_raise(parse_mode, None, unicode_type, parameter_name="parse_mode")
assert_type_or_raise(disable_web_page_preview, None, bool, parameter_name="disable_web_page_preview")
assert_type_or_raise(reply_markup, None, InlineKeyboardMarkup, parameter_name="reply_markup")
result = self.do("editMessageText", text=text, chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id, parse_mode=parse_mode, disable_web_page_preview=disable_web_page_preview, reply_markup=reply_markup)
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 edit text and game messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
https://core.telegram.org/bots/api#editmessagetext
Parameters:
:param text: New text of the message
:type text: str|unicode
Optional keyword parameters:
: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 | str|unicode
: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
:param parse_mode: Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.
:type parse_mode: str|unicode
:param disable_web_page_preview: Disables link previews for links in this message
:type disable_web_page_preview: bool
:param reply_markup: A JSON-serialized object for an inline keyboard.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup
Returns:
:return: On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned
:rtype: pytgbot.api_types.receivable.updates.Message | bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2331-L2403 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.get_sticker_set | def get_sticker_set(self, name):
"""
Use this method to get a sticker set. On success, a StickerSet object is returned.
https://core.telegram.org/bots/api#getstickerset
Parameters:
:param name: Name of the sticker set
:type name: str|unicode
Returns:
:return: On success, a StickerSet object is returned
:rtype: pytgbot.api_types.receivable.stickers.StickerSet
"""
assert_type_or_raise(name, unicode_type, parameter_name="name")
result = self.do("getStickerSet", name=name)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.stickers import StickerSet
try:
return StickerSet.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type StickerSet", 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_sticker_set(self, name):
"""
Use this method to get a sticker set. On success, a StickerSet object is returned.
https://core.telegram.org/bots/api#getstickerset
Parameters:
:param name: Name of the sticker set
:type name: str|unicode
Returns:
:return: On success, a StickerSet object is returned
:rtype: pytgbot.api_types.receivable.stickers.StickerSet
"""
assert_type_or_raise(name, unicode_type, parameter_name="name")
result = self.do("getStickerSet", name=name)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.stickers import StickerSet
try:
return StickerSet.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type StickerSet", 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 get a sticker set. On success, a StickerSet object is returned.
https://core.telegram.org/bots/api#getstickerset
Parameters:
:param name: Name of the sticker set
:type name: str|unicode
Returns:
:return: On success, a StickerSet object is returned
:rtype: pytgbot.api_types.receivable.stickers.StickerSet | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2698-L2730 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.upload_sticker_file | def upload_sticker_file(self, user_id, png_sticker):
"""
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
https://core.telegram.org/bots/api#uploadstickerfile
Parameters:
:param user_id: User identifier of sticker file owner
:type user_id: int
:param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. More info on Sending Files »
:type png_sticker: pytgbot.api_types.sendable.files.InputFile
Returns:
:return: Returns the uploaded File on success
:rtype: pytgbot.api_types.receivable.media.File
"""
from pytgbot.api_types.sendable.files import InputFile
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(png_sticker, InputFile, parameter_name="png_sticker")
result = self.do("uploadStickerFile", user_id=user_id, png_sticker=png_sticker)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.media import File
try:
return File.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type File", 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 upload_sticker_file(self, user_id, png_sticker):
"""
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
https://core.telegram.org/bots/api#uploadstickerfile
Parameters:
:param user_id: User identifier of sticker file owner
:type user_id: int
:param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. More info on Sending Files »
:type png_sticker: pytgbot.api_types.sendable.files.InputFile
Returns:
:return: Returns the uploaded File on success
:rtype: pytgbot.api_types.receivable.media.File
"""
from pytgbot.api_types.sendable.files import InputFile
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(png_sticker, InputFile, parameter_name="png_sticker")
result = self.do("uploadStickerFile", user_id=user_id, png_sticker=png_sticker)
if self.return_python_objects:
logger.debug("Trying to parse {data}".format(data=repr(result)))
from pytgbot.api_types.receivable.media import File
try:
return File.from_array(result)
except TgApiParseException:
logger.debug("Failed parsing as api_type File", 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 upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
https://core.telegram.org/bots/api#uploadstickerfile
Parameters:
:param user_id: User identifier of sticker file owner
:type user_id: int
:param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. More info on Sending Files »
:type png_sticker: pytgbot.api_types.sendable.files.InputFile
Returns:
:return: Returns the uploaded File on success
:rtype: pytgbot.api_types.receivable.media.File | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2733-L2772 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.create_new_sticker_set | def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, mask_position=None):
"""
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.
https://core.telegram.org/bots/api#createnewstickerset
Parameters:
:param user_id: User identifier of created sticker set owner
:type user_id: int
:param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters.
:type name: str|unicode
:param title: Sticker set title, 1-64 characters
:type title: str|unicode
:param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files »
:type png_sticker: pytgbot.api_types.sendable.files.InputFile | str|unicode
:param emojis: One or more emoji corresponding to the sticker
:type emojis: str|unicode
Optional keyword parameters:
:param contains_masks: Pass True, if a set of mask stickers should be created
:type contains_masks: bool
:param mask_position: A JSON-serialized object for position where the mask should be placed on faces
:type mask_position: pytgbot.api_types.receivable.stickers.MaskPosition
Returns:
:return: Returns True on success
:rtype: bool
"""
from pytgbot.api_types.receivable.stickers import MaskPosition
from pytgbot.api_types.sendable.files import InputFile
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(name, unicode_type, parameter_name="name")
assert_type_or_raise(title, unicode_type, parameter_name="title")
assert_type_or_raise(png_sticker, (InputFile, unicode_type), parameter_name="png_sticker")
assert_type_or_raise(emojis, unicode_type, parameter_name="emojis")
assert_type_or_raise(contains_masks, None, bool, parameter_name="contains_masks")
assert_type_or_raise(mask_position, None, MaskPosition, parameter_name="mask_position")
result = self.do("createNewStickerSet", user_id=user_id, name=name, title=title, png_sticker=png_sticker, emojis=emojis, contains_masks=contains_masks, mask_position=mask_position)
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 create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, mask_position=None):
"""
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.
https://core.telegram.org/bots/api#createnewstickerset
Parameters:
:param user_id: User identifier of created sticker set owner
:type user_id: int
:param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters.
:type name: str|unicode
:param title: Sticker set title, 1-64 characters
:type title: str|unicode
:param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files »
:type png_sticker: pytgbot.api_types.sendable.files.InputFile | str|unicode
:param emojis: One or more emoji corresponding to the sticker
:type emojis: str|unicode
Optional keyword parameters:
:param contains_masks: Pass True, if a set of mask stickers should be created
:type contains_masks: bool
:param mask_position: A JSON-serialized object for position where the mask should be placed on faces
:type mask_position: pytgbot.api_types.receivable.stickers.MaskPosition
Returns:
:return: Returns True on success
:rtype: bool
"""
from pytgbot.api_types.receivable.stickers import MaskPosition
from pytgbot.api_types.sendable.files import InputFile
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(name, unicode_type, parameter_name="name")
assert_type_or_raise(title, unicode_type, parameter_name="title")
assert_type_or_raise(png_sticker, (InputFile, unicode_type), parameter_name="png_sticker")
assert_type_or_raise(emojis, unicode_type, parameter_name="emojis")
assert_type_or_raise(contains_masks, None, bool, parameter_name="contains_masks")
assert_type_or_raise(mask_position, None, MaskPosition, parameter_name="mask_position")
result = self.do("createNewStickerSet", user_id=user_id, name=name, title=title, png_sticker=png_sticker, emojis=emojis, contains_masks=contains_masks, mask_position=mask_position)
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 create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.
https://core.telegram.org/bots/api#createnewstickerset
Parameters:
:param user_id: User identifier of created sticker set owner
:type user_id: int
:param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters.
:type name: str|unicode
:param title: Sticker set title, 1-64 characters
:type title: str|unicode
:param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files »
:type png_sticker: pytgbot.api_types.sendable.files.InputFile | str|unicode
:param emojis: One or more emoji corresponding to the sticker
:type emojis: str|unicode
Optional keyword parameters:
:param contains_masks: Pass True, if a set of mask stickers should be created
:type contains_masks: bool
:param mask_position: A JSON-serialized object for position where the mask should be placed on faces
:type mask_position: pytgbot.api_types.receivable.stickers.MaskPosition
Returns:
:return: Returns True on success
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2775-L2841 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.set_sticker_position_in_set | def set_sticker_position_in_set(self, sticker, position):
"""
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
https://core.telegram.org/bots/api#setstickerpositioninset
Parameters:
:param sticker: File identifier of the sticker
:type sticker: str|unicode
:param position: New sticker position in the set, zero-based
:type position: int
Returns:
:return: Returns True on success
:rtype: bool
"""
assert_type_or_raise(sticker, unicode_type, parameter_name="sticker")
assert_type_or_raise(position, int, parameter_name="position")
result = self.do("setStickerPositionInSet", sticker=sticker, position=position)
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 set_sticker_position_in_set(self, sticker, position):
"""
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
https://core.telegram.org/bots/api#setstickerpositioninset
Parameters:
:param sticker: File identifier of the sticker
:type sticker: str|unicode
:param position: New sticker position in the set, zero-based
:type position: int
Returns:
:return: Returns True on success
:rtype: bool
"""
assert_type_or_raise(sticker, unicode_type, parameter_name="sticker")
assert_type_or_raise(position, int, parameter_name="position")
result = self.do("setStickerPositionInSet", sticker=sticker, position=position)
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 move a sticker in a set created by the bot to a specific position . Returns True on success.
https://core.telegram.org/bots/api#setstickerpositioninset
Parameters:
:param sticker: File identifier of the sticker
:type sticker: str|unicode
:param position: New sticker position in the set, zero-based
:type position: int
Returns:
:return: Returns True on success
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L2903-L2939 |
luckydonald/pytgbot | code_generation/output/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
"""
from pytgbot.api_types.sendable.inline import InlineQueryResult
assert_type_or_raise(inline_query_id, unicode_type, parameter_name="inline_query_id")
assert_type_or_raise(results, list, parameter_name="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, parameter_name="next_offset")
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=results, 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
"""
from pytgbot.api_types.sendable.inline import InlineQueryResult
assert_type_or_raise(inline_query_id, unicode_type, parameter_name="inline_query_id")
assert_type_or_raise(results, list, parameter_name="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, parameter_name="next_offset")
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=results, 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/code_generation/output/pytgbot/bot.py#L2976-L3041 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.send_invoice | def send_invoice(self, chat_id, title, description, payload, provider_token, start_parameter, currency, prices, provider_data=None, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, send_phone_number_to_provider=None, send_email_to_provider=None, is_flexible=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send invoices. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendinvoice
Parameters:
:param chat_id: Unique identifier for the target private chat
:type chat_id: int
:param title: Product name, 1-32 characters
:type title: str|unicode
:param description: Product description, 1-255 characters
:type description: str|unicode
:param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
:type payload: str|unicode
:param provider_token: Payments provider token, obtained via Botfather
:type provider_token: str|unicode
:param start_parameter: Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter
:type start_parameter: str|unicode
:param currency: Three-letter ISO 4217 currency code, see more on currencies
:type currency: str|unicode
:param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
:type prices: list of pytgbot.api_types.sendable.payments.LabeledPrice
Optional keyword parameters:
:param provider_data: JSON-encoded data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.
:type provider_data: str|unicode
:param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.
:type photo_url: str|unicode
:param photo_size: Photo size
:type photo_size: int
:param photo_width: Photo width
:type photo_width: int
:param photo_height: Photo height
:type photo_height: int
:param need_name: Pass True, if you require the user's full name to complete the order
:type need_name: bool
:param need_phone_number: Pass True, if you require the user's phone number to complete the order
:type need_phone_number: bool
:param need_email: Pass True, if you require the user's email address to complete the order
:type need_email: bool
:param need_shipping_address: Pass True, if you require the user's shipping address to complete the order
:type need_shipping_address: bool
:param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider
:type send_phone_number_to_provider: bool
:param send_email_to_provider: Pass True, if user's email address should be sent to provider
:type send_email_to_provider: bool
:param is_flexible: Pass True, if the final price depends on the shipping method
:type is_flexible: bool
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message
"""
from pytgbot.api_types.sendable.payments import LabeledPrice
from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup
assert_type_or_raise(chat_id, int, parameter_name="chat_id")
assert_type_or_raise(title, unicode_type, parameter_name="title")
assert_type_or_raise(description, unicode_type, parameter_name="description")
assert_type_or_raise(payload, unicode_type, parameter_name="payload")
assert_type_or_raise(provider_token, unicode_type, parameter_name="provider_token")
assert_type_or_raise(start_parameter, unicode_type, parameter_name="start_parameter")
assert_type_or_raise(currency, unicode_type, parameter_name="currency")
assert_type_or_raise(prices, list, parameter_name="prices")
assert_type_or_raise(provider_data, None, unicode_type, parameter_name="provider_data")
assert_type_or_raise(photo_url, None, unicode_type, parameter_name="photo_url")
assert_type_or_raise(photo_size, None, int, parameter_name="photo_size")
assert_type_or_raise(photo_width, None, int, parameter_name="photo_width")
assert_type_or_raise(photo_height, None, int, parameter_name="photo_height")
assert_type_or_raise(need_name, None, bool, parameter_name="need_name")
assert_type_or_raise(need_phone_number, None, bool, parameter_name="need_phone_number")
assert_type_or_raise(need_email, None, bool, parameter_name="need_email")
assert_type_or_raise(need_shipping_address, None, bool, parameter_name="need_shipping_address")
assert_type_or_raise(send_phone_number_to_provider, None, bool, parameter_name="send_phone_number_to_provider")
assert_type_or_raise(send_email_to_provider, None, bool, parameter_name="send_email_to_provider")
assert_type_or_raise(is_flexible, None, bool, parameter_name="is_flexible")
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")
assert_type_or_raise(reply_markup, None, InlineKeyboardMarkup, parameter_name="reply_markup")
result = self.do("sendInvoice", chat_id=chat_id, title=title, description=description, payload=payload, provider_token=provider_token, start_parameter=start_parameter, currency=currency, prices=prices, provider_data=provider_data, photo_url=photo_url, photo_size=photo_size, photo_width=photo_width, photo_height=photo_height, need_name=need_name, need_phone_number=need_phone_number, need_email=need_email, need_shipping_address=need_shipping_address, send_phone_number_to_provider=send_phone_number_to_provider, send_email_to_provider=send_email_to_provider, is_flexible=is_flexible, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
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 send_invoice(self, chat_id, title, description, payload, provider_token, start_parameter, currency, prices, provider_data=None, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, send_phone_number_to_provider=None, send_email_to_provider=None, is_flexible=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send invoices. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendinvoice
Parameters:
:param chat_id: Unique identifier for the target private chat
:type chat_id: int
:param title: Product name, 1-32 characters
:type title: str|unicode
:param description: Product description, 1-255 characters
:type description: str|unicode
:param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
:type payload: str|unicode
:param provider_token: Payments provider token, obtained via Botfather
:type provider_token: str|unicode
:param start_parameter: Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter
:type start_parameter: str|unicode
:param currency: Three-letter ISO 4217 currency code, see more on currencies
:type currency: str|unicode
:param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
:type prices: list of pytgbot.api_types.sendable.payments.LabeledPrice
Optional keyword parameters:
:param provider_data: JSON-encoded data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.
:type provider_data: str|unicode
:param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.
:type photo_url: str|unicode
:param photo_size: Photo size
:type photo_size: int
:param photo_width: Photo width
:type photo_width: int
:param photo_height: Photo height
:type photo_height: int
:param need_name: Pass True, if you require the user's full name to complete the order
:type need_name: bool
:param need_phone_number: Pass True, if you require the user's phone number to complete the order
:type need_phone_number: bool
:param need_email: Pass True, if you require the user's email address to complete the order
:type need_email: bool
:param need_shipping_address: Pass True, if you require the user's shipping address to complete the order
:type need_shipping_address: bool
:param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider
:type send_phone_number_to_provider: bool
:param send_email_to_provider: Pass True, if user's email address should be sent to provider
:type send_email_to_provider: bool
:param is_flexible: Pass True, if the final price depends on the shipping method
:type is_flexible: bool
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message
"""
from pytgbot.api_types.sendable.payments import LabeledPrice
from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup
assert_type_or_raise(chat_id, int, parameter_name="chat_id")
assert_type_or_raise(title, unicode_type, parameter_name="title")
assert_type_or_raise(description, unicode_type, parameter_name="description")
assert_type_or_raise(payload, unicode_type, parameter_name="payload")
assert_type_or_raise(provider_token, unicode_type, parameter_name="provider_token")
assert_type_or_raise(start_parameter, unicode_type, parameter_name="start_parameter")
assert_type_or_raise(currency, unicode_type, parameter_name="currency")
assert_type_or_raise(prices, list, parameter_name="prices")
assert_type_or_raise(provider_data, None, unicode_type, parameter_name="provider_data")
assert_type_or_raise(photo_url, None, unicode_type, parameter_name="photo_url")
assert_type_or_raise(photo_size, None, int, parameter_name="photo_size")
assert_type_or_raise(photo_width, None, int, parameter_name="photo_width")
assert_type_or_raise(photo_height, None, int, parameter_name="photo_height")
assert_type_or_raise(need_name, None, bool, parameter_name="need_name")
assert_type_or_raise(need_phone_number, None, bool, parameter_name="need_phone_number")
assert_type_or_raise(need_email, None, bool, parameter_name="need_email")
assert_type_or_raise(need_shipping_address, None, bool, parameter_name="need_shipping_address")
assert_type_or_raise(send_phone_number_to_provider, None, bool, parameter_name="send_phone_number_to_provider")
assert_type_or_raise(send_email_to_provider, None, bool, parameter_name="send_email_to_provider")
assert_type_or_raise(is_flexible, None, bool, parameter_name="is_flexible")
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")
assert_type_or_raise(reply_markup, None, InlineKeyboardMarkup, parameter_name="reply_markup")
result = self.do("sendInvoice", chat_id=chat_id, title=title, description=description, payload=payload, provider_token=provider_token, start_parameter=start_parameter, currency=currency, prices=prices, provider_data=provider_data, photo_url=photo_url, photo_size=photo_size, photo_width=photo_width, photo_height=photo_height, need_name=need_name, need_phone_number=need_phone_number, need_email=need_email, need_shipping_address=need_shipping_address, send_phone_number_to_provider=send_phone_number_to_provider, send_email_to_provider=send_email_to_provider, is_flexible=is_flexible, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
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 send invoices. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendinvoice
Parameters:
:param chat_id: Unique identifier for the target private chat
:type chat_id: int
:param title: Product name, 1-32 characters
:type title: str|unicode
:param description: Product description, 1-255 characters
:type description: str|unicode
:param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
:type payload: str|unicode
:param provider_token: Payments provider token, obtained via Botfather
:type provider_token: str|unicode
:param start_parameter: Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter
:type start_parameter: str|unicode
:param currency: Three-letter ISO 4217 currency code, see more on currencies
:type currency: str|unicode
:param prices: Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
:type prices: list of pytgbot.api_types.sendable.payments.LabeledPrice
Optional keyword parameters:
:param provider_data: JSON-encoded data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.
:type provider_data: str|unicode
:param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.
:type photo_url: str|unicode
:param photo_size: Photo size
:type photo_size: int
:param photo_width: Photo width
:type photo_width: int
:param photo_height: Photo height
:type photo_height: int
:param need_name: Pass True, if you require the user's full name to complete the order
:type need_name: bool
:param need_phone_number: Pass True, if you require the user's phone number to complete the order
:type need_phone_number: bool
:param need_email: Pass True, if you require the user's email address to complete the order
:type need_email: bool
:param need_shipping_address: Pass True, if you require the user's shipping address to complete the order
:type need_shipping_address: bool
:param send_phone_number_to_provider: Pass True, if user's phone number should be sent to provider
:type send_phone_number_to_provider: bool
:param send_email_to_provider: Pass True, if user's email address should be sent to provider
:type send_email_to_provider: bool
:param is_flexible: Pass True, if the final price depends on the shipping method
:type is_flexible: bool
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L3044-L3191 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.answer_shipping_query | def answer_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None):
"""
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
https://core.telegram.org/bots/api#answershippingquery
Parameters:
:param shipping_query_id: Unique identifier for the query to be answered
:type shipping_query_id: str|unicode
:param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
:type ok: bool
Optional keyword parameters:
:param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options.
:type shipping_options: list of pytgbot.api_types.sendable.payments.ShippingOption
:param error_message: Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.
:type error_message: str|unicode
Returns:
:return: On success, True is returned
:rtype: bool
"""
from pytgbot.api_types.sendable.payments import ShippingOption
assert_type_or_raise(shipping_query_id, unicode_type, parameter_name="shipping_query_id")
assert_type_or_raise(ok, bool, parameter_name="ok")
assert_type_or_raise(shipping_options, None, list, parameter_name="shipping_options")
assert_type_or_raise(error_message, None, unicode_type, parameter_name="error_message")
result = self.do("answerShippingQuery", shipping_query_id=shipping_query_id, ok=ok, shipping_options=shipping_options, error_message=error_message)
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_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None):
"""
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
https://core.telegram.org/bots/api#answershippingquery
Parameters:
:param shipping_query_id: Unique identifier for the query to be answered
:type shipping_query_id: str|unicode
:param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
:type ok: bool
Optional keyword parameters:
:param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options.
:type shipping_options: list of pytgbot.api_types.sendable.payments.ShippingOption
:param error_message: Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.
:type error_message: str|unicode
Returns:
:return: On success, True is returned
:rtype: bool
"""
from pytgbot.api_types.sendable.payments import ShippingOption
assert_type_or_raise(shipping_query_id, unicode_type, parameter_name="shipping_query_id")
assert_type_or_raise(ok, bool, parameter_name="ok")
assert_type_or_raise(shipping_options, None, list, parameter_name="shipping_options")
assert_type_or_raise(error_message, None, unicode_type, parameter_name="error_message")
result = self.do("answerShippingQuery", shipping_query_id=shipping_query_id, ok=ok, shipping_options=shipping_options, error_message=error_message)
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 | If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
https://core.telegram.org/bots/api#answershippingquery
Parameters:
:param shipping_query_id: Unique identifier for the query to be answered
:type shipping_query_id: str|unicode
:param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
:type ok: bool
Optional keyword parameters:
:param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options.
:type shipping_options: list of pytgbot.api_types.sendable.payments.ShippingOption
:param error_message: Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.
:type error_message: str|unicode
Returns:
:return: On success, True is returned
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L3194-L3244 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.answer_pre_checkout_query | def answer_pre_checkout_query(self, pre_checkout_query_id, ok, error_message=None):
"""
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
https://core.telegram.org/bots/api#answerprecheckoutquery
Parameters:
:param pre_checkout_query_id: Unique identifier for the query to be answered
:type pre_checkout_query_id: str|unicode
:param ok: Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
:type ok: bool
Optional keyword parameters:
:param error_message: Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.
:type error_message: str|unicode
Returns:
:return: On success, True is returned
:rtype: bool
"""
assert_type_or_raise(pre_checkout_query_id, unicode_type, parameter_name="pre_checkout_query_id")
assert_type_or_raise(ok, bool, parameter_name="ok")
assert_type_or_raise(error_message, None, unicode_type, parameter_name="error_message")
result = self.do("answerPreCheckoutQuery", pre_checkout_query_id=pre_checkout_query_id, ok=ok, error_message=error_message)
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_pre_checkout_query(self, pre_checkout_query_id, ok, error_message=None):
"""
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
https://core.telegram.org/bots/api#answerprecheckoutquery
Parameters:
:param pre_checkout_query_id: Unique identifier for the query to be answered
:type pre_checkout_query_id: str|unicode
:param ok: Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
:type ok: bool
Optional keyword parameters:
:param error_message: Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.
:type error_message: str|unicode
Returns:
:return: On success, True is returned
:rtype: bool
"""
assert_type_or_raise(pre_checkout_query_id, unicode_type, parameter_name="pre_checkout_query_id")
assert_type_or_raise(ok, bool, parameter_name="ok")
assert_type_or_raise(error_message, None, unicode_type, parameter_name="error_message")
result = self.do("answerPreCheckoutQuery", pre_checkout_query_id=pre_checkout_query_id, ok=ok, error_message=error_message)
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 | Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
https://core.telegram.org/bots/api#answerprecheckoutquery
Parameters:
:param pre_checkout_query_id: Unique identifier for the query to be answered
:type pre_checkout_query_id: str|unicode
:param ok: Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
:type ok: bool
Optional keyword parameters:
:param error_message: Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.
:type error_message: str|unicode
Returns:
:return: On success, True is returned
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L3247-L3290 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.set_passport_data_errors | def set_passport_data_errors(self, user_id, errors):
"""
Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.
Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
https://core.telegram.org/bots/api#setpassportdataerrors
Parameters:
:param user_id: User identifier
:type user_id: int
:param errors: A JSON-serialized array describing the errors
:type errors: list of pytgbot.api_types.sendable.passport.PassportElementError
Returns:
:return: Returns True on success
:rtype: bool
"""
from pytgbot.api_types.sendable.passport import PassportElementError
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(errors, list, parameter_name="errors")
result = self.do("setPassportDataErrors", user_id=user_id, errors=errors)
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 set_passport_data_errors(self, user_id, errors):
"""
Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.
Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
https://core.telegram.org/bots/api#setpassportdataerrors
Parameters:
:param user_id: User identifier
:type user_id: int
:param errors: A JSON-serialized array describing the errors
:type errors: list of pytgbot.api_types.sendable.passport.PassportElementError
Returns:
:return: Returns True on success
:rtype: bool
"""
from pytgbot.api_types.sendable.passport import PassportElementError
assert_type_or_raise(user_id, int, parameter_name="user_id")
assert_type_or_raise(errors, list, parameter_name="errors")
result = self.do("setPassportDataErrors", user_id=user_id, errors=errors)
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 | Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.
Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
https://core.telegram.org/bots/api#setpassportdataerrors
Parameters:
:param user_id: User identifier
:type user_id: int
:param errors: A JSON-serialized array describing the errors
:type errors: list of pytgbot.api_types.sendable.passport.PassportElementError
Returns:
:return: Returns True on success
:rtype: bool | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L3293-L3332 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.send_game | def send_game(self, chat_id, game_short_name, disable_notification=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send a game. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendgame
Parameters:
:param chat_id: Unique identifier for the target chat
:type chat_id: int
:param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather.
:type game_short_name: str|unicode
Optional keyword parameters:
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message
"""
from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup
assert_type_or_raise(chat_id, int, parameter_name="chat_id")
assert_type_or_raise(game_short_name, unicode_type, parameter_name="game_short_name")
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")
assert_type_or_raise(reply_markup, None, InlineKeyboardMarkup, parameter_name="reply_markup")
result = self.do("sendGame", chat_id=chat_id, game_short_name=game_short_name, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
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 send_game(self, chat_id, game_short_name, disable_notification=None, reply_to_message_id=None, reply_markup=None):
"""
Use this method to send a game. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendgame
Parameters:
:param chat_id: Unique identifier for the target chat
:type chat_id: int
:param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather.
:type game_short_name: str|unicode
Optional keyword parameters:
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message
"""
from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup
assert_type_or_raise(chat_id, int, parameter_name="chat_id")
assert_type_or_raise(game_short_name, unicode_type, parameter_name="game_short_name")
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")
assert_type_or_raise(reply_markup, None, InlineKeyboardMarkup, parameter_name="reply_markup")
result = self.do("sendGame", chat_id=chat_id, game_short_name=game_short_name, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
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 send a game. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendgame
Parameters:
:param chat_id: Unique identifier for the target chat
:type chat_id: int
:param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather.
:type game_short_name: str|unicode
Optional keyword parameters:
:param disable_notification: Sends the message silently. Users will receive a notification with no sound.
:type disable_notification: bool
:param reply_to_message_id: If the message is a reply, ID of the original message
:type reply_to_message_id: int
:param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game.
:type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup
Returns:
:return: On success, the sent Message is returned
:rtype: pytgbot.api_types.receivable.updates.Message | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L3335-L3391 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.get_game_high_scores | def get_game_high_scores(self, user_id, chat_id=None, message_id=None, inline_message_id=None):
"""
Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.
This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change.
https://core.telegram.org/bots/api#getgamehighscores
Parameters:
:param user_id: Target user id
:type user_id: int
Optional keyword parameters:
:param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat
: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, returns an Array of GameHighScore objects
:rtype: list of pytgbot.api_types.receivable.game.GameHighScore
"""
assert_type_or_raise(user_id, int, parameter_name="user_id")
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("getGameHighScores", user_id=user_id, 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.game import GameHighScore
try:
return GameHighScore.from_array_list(result, list_level=1)
except TgApiParseException:
logger.debug("Failed parsing as api_type GameHighScore", 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_game_high_scores(self, user_id, chat_id=None, message_id=None, inline_message_id=None):
"""
Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.
This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change.
https://core.telegram.org/bots/api#getgamehighscores
Parameters:
:param user_id: Target user id
:type user_id: int
Optional keyword parameters:
:param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat
: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, returns an Array of GameHighScore objects
:rtype: list of pytgbot.api_types.receivable.game.GameHighScore
"""
assert_type_or_raise(user_id, int, parameter_name="user_id")
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("getGameHighScores", user_id=user_id, 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.game import GameHighScore
try:
return GameHighScore.from_array_list(result, list_level=1)
except TgApiParseException:
logger.debug("Failed parsing as api_type GameHighScore", 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 get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.
This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change.
https://core.telegram.org/bots/api#getgamehighscores
Parameters:
:param user_id: Target user id
:type user_id: int
Optional keyword parameters:
:param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat
: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, returns an Array of GameHighScore objects
:rtype: list of pytgbot.api_types.receivable.game.GameHighScore | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L3467-L3519 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.do | def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query):
"""
Send a request to the api.
If the bot is set to return the json objects, it will look like this:
```json
{
"ok": bool,
"result": {...},
# optionally present:
"description": "human-readable description of the result",
"error_code": int
}
```
:param command: The Url command parameter
:type command: str
:param request_timeout: When the request should time out. Default: `None`
:type request_timeout: int
:param files: if it needs to send files.
:param use_long_polling: if it should use long polling. Default: `False`
(see http://docs.python-requests.org/en/latest/api/#requests.Response.iter_content)
:type use_long_polling: bool
:param query: all the other `**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
"""
import requests
url, params = self._prepare_request(command, query)
r = requests.post(url, params=params, files=files, stream=use_long_polling,
verify=True, # No self signed certificates. Telegram should be trustworthy anyway...
timeout=request_timeout)
return self._postprocess_request(r) | python | def do(self, command, files=None, use_long_polling=False, request_timeout=None, **query):
"""
Send a request to the api.
If the bot is set to return the json objects, it will look like this:
```json
{
"ok": bool,
"result": {...},
# optionally present:
"description": "human-readable description of the result",
"error_code": int
}
```
:param command: The Url command parameter
:type command: str
:param request_timeout: When the request should time out. Default: `None`
:type request_timeout: int
:param files: if it needs to send files.
:param use_long_polling: if it should use long polling. Default: `False`
(see http://docs.python-requests.org/en/latest/api/#requests.Response.iter_content)
:type use_long_polling: bool
:param query: all the other `**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
"""
import requests
url, params = self._prepare_request(command, query)
r = requests.post(url, params=params, files=files, stream=use_long_polling,
verify=True, # No self signed certificates. Telegram should be trustworthy anyway...
timeout=request_timeout)
return self._postprocess_request(r) | Send a request to the api.
If the bot is set to return the json objects, it will look like this:
```json
{
"ok": bool,
"result": {...},
# optionally present:
"description": "human-readable description of the result",
"error_code": int
}
```
:param command: The Url command parameter
:type command: str
:param request_timeout: When the request should time out. Default: `None`
:type request_timeout: int
:param files: if it needs to send files.
:param use_long_polling: if it should use long polling. Default: `False`
(see http://docs.python-requests.org/en/latest/api/#requests.Response.iter_content)
:type use_long_polling: bool
:param query: all the other `**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 | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L3527-L3566 |
luckydonald/pytgbot | code_generation/output/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:
logger.exception("Parsing answer failed.\nRequest: {r!s}\nContent: {r.content}".format(r=r))
raise
# 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 != 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
# end def _postprocess_request
def _do_fileupload(self, file_param_name, value, _command=None, **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`.
:type value: pytgbot.api_types.sendable.files.InputFile | str
:param _command: Overwrite the sended command.
Default is to convert `file_param_name` to camel case (`"voice_note"` -> `"sendVoiceNote"`)
: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 pytgbot.api_types.sendable.files import InputFile
from luckydonaldUtils.encoding import unicode_type
from luckydonaldUtils.encoding import to_native as n
if isinstance(value, str):
kwargs[file_param_name] = str(value)
elif isinstance(value, unicode_type):
kwargs[file_param_name] = n(value)
elif isinstance(value, InputFile):
kwargs["files"] = value.get_request_files(file_param_name)
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 _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:
logger.exception("Parsing answer failed.\nRequest: {r!s}\nContent: {r.content}".format(r=r))
raise
# 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 != 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
# end def _postprocess_request
def _do_fileupload(self, file_param_name, value, _command=None, **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`.
:type value: pytgbot.api_types.sendable.files.InputFile | str
:param _command: Overwrite the sended command.
Default is to convert `file_param_name` to camel case (`"voice_note"` -> `"sendVoiceNote"`)
: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 pytgbot.api_types.sendable.files import InputFile
from luckydonaldUtils.encoding import unicode_type
from luckydonaldUtils.encoding import to_native as n
if isinstance(value, str):
kwargs[file_param_name] = str(value)
elif isinstance(value, unicode_type):
kwargs[file_param_name] = n(value)
elif isinstance(value, InputFile):
kwargs["files"] = value.get_request_files(file_param_name)
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) | 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/code_generation/output/pytgbot/bot.py#L3596-L3677 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot.get_download_url | def get_download_url(self, file):
"""
Creates a url to download the file.
Note: Contains the secret API key, so you should not share this url!
:param file: The File you want to get the url to download.
:type file: pytgbot.api_types.receivable.media.File
:return: url
:rtype: str
"""
from .api_types.receivable.media import File
assert isinstance(file, File)
return file.get_download_url(self.api_key) | python | def get_download_url(self, file):
"""
Creates a url to download the file.
Note: Contains the secret API key, so you should not share this url!
:param file: The File you want to get the url to download.
:type file: pytgbot.api_types.receivable.media.File
:return: url
:rtype: str
"""
from .api_types.receivable.media import File
assert isinstance(file, File)
return file.get_download_url(self.api_key) | Creates a url to download the file.
Note: Contains the secret API key, so you should not share this url!
:param file: The File you want to get the url to download.
:type file: pytgbot.api_types.receivable.media.File
:return: url
:rtype: str | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L3680-L3694 |
luckydonald/pytgbot | code_generation/output/pytgbot/bot.py | Bot._load_info | def _load_info(self):
"""
This functions stores the id and the username of the bot.
Called by `.username` and `.id` properties.
:return:
"""
myself = self.get_me()
if self.return_python_objects:
self._id = myself.id
self._username = myself.username
else:
self._id = myself["result"]["id"]
self._username = myself["result"]["username"] | python | def _load_info(self):
"""
This functions stores the id and the username of the bot.
Called by `.username` and `.id` properties.
:return:
"""
myself = self.get_me()
if self.return_python_objects:
self._id = myself.id
self._username = myself.username
else:
self._id = myself["result"]["id"]
self._username = myself["result"]["username"] | This functions stores the id and the username of the bot.
Called by `.username` and `.id` properties.
:return: | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/bot.py#L3697-L3709 |
luckydonald/pytgbot | pytgbot/api_types/sendable/input_media.py | InputMedia.get_request_data | def get_request_data(self, var_name, full_data=False):
"""
:param var_name:
:param full_data: If you want `.to_array()` with this data, ready to be sent.
:return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`).
Files can be None, if no file was given, but an url or existing `file_id`.
If `media` is :py:class:`InputFile` however, the first tuple element,
media, will have ['media'] set to `attach://{var_name}_media` automatically.
"""
if full_data:
data = self.to_array()
data['media'], file = self.get_inputfile_data(self.media, var_name, suffix='_media')
return data, file
# end if
return self.get_inputfile_data(self.media, var_name, suffix='_media') | python | def get_request_data(self, var_name, full_data=False):
"""
:param var_name:
:param full_data: If you want `.to_array()` with this data, ready to be sent.
:return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`).
Files can be None, if no file was given, but an url or existing `file_id`.
If `media` is :py:class:`InputFile` however, the first tuple element,
media, will have ['media'] set to `attach://{var_name}_media` automatically.
"""
if full_data:
data = self.to_array()
data['media'], file = self.get_inputfile_data(self.media, var_name, suffix='_media')
return data, file
# end if
return self.get_inputfile_data(self.media, var_name, suffix='_media') | :param var_name:
:param full_data: If you want `.to_array()` with this data, ready to be sent.
:return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`).
Files can be None, if no file was given, but an url or existing `file_id`.
If `media` is :py:class:`InputFile` however, the first tuple element,
media, will have ['media'] set to `attach://{var_name}_media` automatically. | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/input_media.py#L77-L91 |
luckydonald/pytgbot | pytgbot/api_types/sendable/input_media.py | InputMediaWithThumb.get_request_data | def get_request_data(self, var_name, full_data=False):
"""
:param var_name:
:param full_data: If you want `.to_array()` with this data, ready to be sent.
:return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`).
Files can be None, if no file was given, but an url or existing `file_id`.
If `self.media` is an `InputFile` however,
the first tuple element (either the string, or the dict's `['media']` if `full_data=True`),
will be set to `attach://{var_name}_media` automatically.
If `self.thumb` is an `InputFile` however, the first tuple element's `['thumb']`, will be set to `attach://{var_name}_thumb` automatically.
"""
if not full_data:
raise ArithmeticError('we have a thumbnail, please use `full_data=True`.')
# end if
file = {}
data, file_to_add = super(InputMediaWithThumb, self).get_request_data(var_name, full_data=True)
if file_to_add:
file.update(file_to_add)
# end if
data['thumb'], file_to_add = self.get_inputfile_data(self.thumb, var_name, suffix='_thumb')
if data['thumb'] is None:
del data['thumb'] # having `'thumb': null` in the json produces errors.
# end if
if file_to_add:
file.update(file_to_add)
# end if
return data, (file or None) | python | def get_request_data(self, var_name, full_data=False):
"""
:param var_name:
:param full_data: If you want `.to_array()` with this data, ready to be sent.
:return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`).
Files can be None, if no file was given, but an url or existing `file_id`.
If `self.media` is an `InputFile` however,
the first tuple element (either the string, or the dict's `['media']` if `full_data=True`),
will be set to `attach://{var_name}_media` automatically.
If `self.thumb` is an `InputFile` however, the first tuple element's `['thumb']`, will be set to `attach://{var_name}_thumb` automatically.
"""
if not full_data:
raise ArithmeticError('we have a thumbnail, please use `full_data=True`.')
# end if
file = {}
data, file_to_add = super(InputMediaWithThumb, self).get_request_data(var_name, full_data=True)
if file_to_add:
file.update(file_to_add)
# end if
data['thumb'], file_to_add = self.get_inputfile_data(self.thumb, var_name, suffix='_thumb')
if data['thumb'] is None:
del data['thumb'] # having `'thumb': null` in the json produces errors.
# end if
if file_to_add:
file.update(file_to_add)
# end if
return data, (file or None) | :param var_name:
:param full_data: If you want `.to_array()` with this data, ready to be sent.
:return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`).
Files can be None, if no file was given, but an url or existing `file_id`.
If `self.media` is an `InputFile` however,
the first tuple element (either the string, or the dict's `['media']` if `full_data=True`),
will be set to `attach://{var_name}_media` automatically.
If `self.thumb` is an `InputFile` however, the first tuple element's `['thumb']`, will be set to `attach://{var_name}_thumb` automatically. | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/input_media.py#L120-L147 |
luckydonald/pytgbot | pytgbot/api_types/sendable/input_media.py | InputMediaVideo.to_array | def to_array(self):
"""
Serializes this InputMediaVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
from .files import InputFile
array = super(InputMediaVideo, self).to_array()
# 'type' given by superclass
# 'media' given by superclass
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = None # 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
# 'caption' given by superclass
# 'parse_mode' given by superclass
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.duration is not None:
array['duration'] = int(self.duration) # type int
if self.supports_streaming is not None:
array['supports_streaming'] = bool(self.supports_streaming) # type bool
return array | python | def to_array(self):
"""
Serializes this InputMediaVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
from .files import InputFile
array = super(InputMediaVideo, self).to_array()
# 'type' given by superclass
# 'media' given by superclass
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = None # 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
# 'caption' given by superclass
# 'parse_mode' given by superclass
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.duration is not None:
array['duration'] = int(self.duration) # type int
if self.supports_streaming is not None:
array['supports_streaming'] = bool(self.supports_streaming) # type bool
return array | Serializes this InputMediaVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/input_media.py#L363-L392 |
luckydonald/pytgbot | pytgbot/api_types/sendable/input_media.py | InputMediaAnimation.to_array | def to_array(self):
"""
Serializes this InputMediaAnimation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaAnimation, self).to_array()
# 'type' given by superclass
# 'media' given by superclass
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = None # 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
# 'caption' given by superclass
# 'parse_mode' given by superclass
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.duration is not None:
array['duration'] = int(self.duration) # type int
return array | python | def to_array(self):
"""
Serializes this InputMediaAnimation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaAnimation, self).to_array()
# 'type' given by superclass
# 'media' given by superclass
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = None # 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
# 'caption' given by superclass
# 'parse_mode' given by superclass
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.duration is not None:
array['duration'] = int(self.duration) # type int
return array | Serializes this InputMediaAnimation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/input_media.py#L544-L570 |
luckydonald/pytgbot | pytgbot/api_types/sendable/input_media.py | InputMediaAudio.to_array | def to_array(self):
"""
Serializes this InputMediaAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaAudio, self).to_array()
# 'type' given by superclass
# 'media' given by superclass
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = None # 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
# 'caption' given by superclass
# 'parse_mode' given by superclass
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
return array | python | def to_array(self):
"""
Serializes this InputMediaAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaAudio, self).to_array()
# 'type' given by superclass
# 'media' given by superclass
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = None # 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
# 'caption' given by superclass
# 'parse_mode' given by superclass
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
return array | Serializes this InputMediaAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/input_media.py#L723-L749 |
luckydonald/pytgbot | pytgbot/api_types/sendable/input_media.py | InputMediaDocument.to_array | def to_array(self):
"""
Serializes this InputMediaDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaDocument, self).to_array()
# 'type' given by superclass
# 'media' given by superclass
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = None # 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
# 'caption' given by superclass
# 'parse_mode' given by superclass
return array | python | def to_array(self):
"""
Serializes this InputMediaDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaDocument, self).to_array()
# 'type' given by superclass
# 'media' given by superclass
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = None # 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
# 'caption' given by superclass
# 'parse_mode' given by superclass
return array | Serializes this InputMediaDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/input_media.py#L873-L893 |
luckydonald/pytgbot | pytgbot/api_types/sendable/input_media.py | InputMediaDocument.from_array | def from_array(array):
"""
Deserialize a new InputMediaDocument from a given dictionary.
:return: new InputMediaDocument instance.
:rtype: InputMediaDocument
"""
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
data = {}
# 'type' is given by class type
data['media'] = u(array.get('media'))
if array.get('thumb') is None:
data['thumb'] = None
elif isinstance(array.get('thumb'), InputFile):
data['thumb'] = None # will be filled later by get_request_data()
elif isinstance(array.get('thumb'), str):
data['thumb'] = u(array.get('thumb'))
else:
raise TypeError('Unknown type, must be one of InputFile, str or None.')
# end if
data['caption'] = u(array.get('caption')) if array.get('caption') is not None else None
data['parse_mode'] = u(array.get('parse_mode')) if array.get('parse_mode') is not None else None
instance = InputMediaDocument(**data)
instance._raw = array
return instance | python | def from_array(array):
"""
Deserialize a new InputMediaDocument from a given dictionary.
:return: new InputMediaDocument instance.
:rtype: InputMediaDocument
"""
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
data = {}
# 'type' is given by class type
data['media'] = u(array.get('media'))
if array.get('thumb') is None:
data['thumb'] = None
elif isinstance(array.get('thumb'), InputFile):
data['thumb'] = None # will be filled later by get_request_data()
elif isinstance(array.get('thumb'), str):
data['thumb'] = u(array.get('thumb'))
else:
raise TypeError('Unknown type, must be one of InputFile, str or None.')
# end if
data['caption'] = u(array.get('caption')) if array.get('caption') is not None else None
data['parse_mode'] = u(array.get('parse_mode')) if array.get('parse_mode') is not None else None
instance = InputMediaDocument(**data)
instance._raw = array
return instance | Deserialize a new InputMediaDocument from a given dictionary.
:return: new InputMediaDocument instance.
:rtype: InputMediaDocument | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/input_media.py#L897-L928 |
delph-in/pydelphin | delphin/repp.py | _mergemap | def _mergemap(map1, map2):
"""
Positions in map2 have an integer indicating the relative shift to
the equivalent position in map1. E.g., the i'th position in map2
corresponds to the i + map2[i] position in map1.
"""
merged = array('i', [0] * len(map2))
for i, shift in enumerate(map2):
merged[i] = shift + map1[i + shift]
return merged | python | def _mergemap(map1, map2):
"""
Positions in map2 have an integer indicating the relative shift to
the equivalent position in map1. E.g., the i'th position in map2
corresponds to the i + map2[i] position in map1.
"""
merged = array('i', [0] * len(map2))
for i, shift in enumerate(map2):
merged[i] = shift + map1[i + shift]
return merged | Positions in map2 have an integer indicating the relative shift to
the equivalent position in map1. E.g., the i'th position in map2
corresponds to the i + map2[i] position in map1. | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/repp.py#L473-L482 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.