Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
raise ZenpyException("Incremental Endpoint requires a start_time parameter!")
elif isinstance(start_time, datetime):
unix_time = to_unix_ts(start_time)
else:
unix_time = start_time
params = dict(start_time=str(unix_time))
if include is not None:
if is_iterable_but_not_string(include):
params.update(dict(include=",".join(include)))
else:
params.update(dict(include=include))
return Url(self.endpoint, params=params)
class ChatIncrementalEndpoint(BaseEndpoint):
"""
An ChatsIncrementalEndpoint takes parameters
for querying the chats incremental api endpoint.
Note: The Zendesk API expects UTC time. If a timezone aware datetime object is passed
Zenpy will convert it to UTC, however if a naive object or unix timestamp is passed there is nothing
Zenpy can do. It is recommended to always pass timezone aware objects to this endpoint.
:param start_time: unix timestamp or datetime object
:param fields: list of chat fields to load without "chats(xxx)". Defaults to "*"
"""
def __call__(self, start_time=None, **kwargs):
if start_time is None:
raise ZenpyException("Incremental Endpoint requires a start_time parameter!")
params = kwargs
params.update(dict(start_time=str(unix_time)))
if 'fields' in kwargs:
if is_iterable_but_not_string(kwargs['fields']):
f = ",".join(kwargs['fields'])
else:
f = kwargs['fields']
else:
f = "*"
params.update(dict(fields="chats(" + f + ")"))
return Url(self.endpoint, params=params)
class AttachmentEndpoint(BaseEndpoint):
def __call__(self, **kwargs):
return Url(self.endpoint, params={k: v for k, v in kwargs.items() if v is not None})
class SearchEndpoint(BaseEndpoint):
"""
The search endpoint accepts all the parameters defined in the Zendesk
`Search Documentation `_.
Zenpy defines several keywords that are mapped to the Zendesk comparison operators:
+-----------------+------------------+
| **Keyword** | **Operator** |
+-----------------+------------------+
| keyword | : (equality) |
+-----------------+------------------+
| \*_greater_than | > (numeric|type) |
# this is a bit of a hack
elif key == 'role':
if isinstance(value, basestring) or len(value) == 1:
parameters['role[]'] = value
else:
parameters['role[]'] = value[0] + '&' + "&".join(('role[]={}'.format(role) for role in value[1:]))
elif key.endswith('ids'):
# if it looks like a type of unknown id, send it through as such
parameters[key] = ",".join(map(str, value))
if path == self.endpoint and not path.endswith('.json'):
path += '.json'
return Url(path=path, params=parameters)
class SecondaryEndpoint(BaseEndpoint):
def __call__(self, id, **kwargs):
return Url(self.endpoint % dict(id=id), params=kwargs)
class MultipleIDEndpoint(BaseEndpoint):
def __call__(self, *args):
if not args or len(args) < 2:
raise ZenpyException("This endpoint requires at least two arguments!")
return Url(self.endpoint.format(*args))
class IncrementalEndpoint(BaseEndpoint):
"""
An IncrementalEndpoint takes a start_time parameter
for querying the incremental api endpoint.
path += "/{}.json".format(value)
else:
params[key] = value
if sort_order:
params['sort_order'] = sort_order
if sort_by:
params['sort_by'] = sort_by
if path == self.endpoint:
path += '.json'
return Url(path, params=params)
class ChatEndpoint(BaseEndpoint):
def __call__(self, **kwargs):
if len(kwargs) > 1:
raise ZenpyException("Only expect a single keyword to the ChatEndpoint")
endpoint_path = self.endpoint
params = dict()
if 'ids' in kwargs:
endpoint_path = self.endpoint
params['ids'] = ','.join(kwargs['ids'])
else:
for key, value in kwargs.items():
if key == 'email':
endpoint_path = '{}/email/{}'.format(self.endpoint, value)
elif self.endpoint == 'departments' and key == 'name':
endpoint_path = '{}/name/{}'.format(self.endpoint, value)
else:
endpoint_path = "{}/{}".format(self.endpoint, value)
parameters['role[]'] = value[0] + '&' + "&".join(('role[]={}'.format(role) for role in value[1:]))
elif key.endswith('ids'):
# if it looks like a type of unknown id, send it through as such
parameters[key] = ",".join(map(str, value))
if path == self.endpoint and not path.endswith('.json'):
path += '.json'
return Url(path=path, params=parameters)
class SecondaryEndpoint(BaseEndpoint):
def __call__(self, id, **kwargs):
return Url(self.endpoint % dict(id=id), params=kwargs)
class MultipleIDEndpoint(BaseEndpoint):
def __call__(self, *args):
if not args or len(args) < 2:
raise ZenpyException("This endpoint requires at least two arguments!")
return Url(self.endpoint.format(*args))
class IncrementalEndpoint(BaseEndpoint):
"""
An IncrementalEndpoint takes a start_time parameter
for querying the incremental api endpoint.
Note: The Zendesk API expects UTC time. If a timezone aware datetime object is passed
Zenpy will convert it to UTC, however if a naive object or unix timestamp is passed there is nothing
Zenpy can do. It is recommended to always pass timezone aware objects to this endpoint.
:param start_time: unix timestamp or datetime object
params = dict()
if 'ids' in kwargs:
endpoint_path = self.endpoint
params['ids'] = ','.join(kwargs['ids'])
else:
for key, value in kwargs.items():
if key == 'email':
endpoint_path = '{}/email/{}'.format(self.endpoint, value)
elif self.endpoint == 'departments' and key == 'name':
endpoint_path = '{}/name/{}'.format(self.endpoint, value)
else:
endpoint_path = "{}/{}".format(self.endpoint, value)
break
return Url(endpoint_path, params=params)
class ChatSearchEndpoint(BaseEndpoint):
def __call__(self, *args, **kwargs):
conditions = list()
if args:
conditions.append(' '.join(args))
conditions.extend(["{}:{}".format(k, v) for k, v in kwargs.items()])
query = " AND ".join(conditions)
return Url(self.endpoint, params=dict(q=query))
class ViewSearchEndpoint(BaseEndpoint):
def __call__(self, query, **kwargs):
kwargs['query'] = query
return Url(self.endpoint, params=kwargs)
class EndpointFactory(object):
f = ",".join(kwargs['fields'])
else:
f = kwargs['fields']
else:
f = "*"
params.update(dict(fields="chats(" + f + ")"))
return Url(self.endpoint, params=params)
class AttachmentEndpoint(BaseEndpoint):
def __call__(self, **kwargs):
return Url(self.endpoint, params={k: v for k, v in kwargs.items() if v is not None})
class SearchEndpoint(BaseEndpoint):
"""
The search endpoint accepts all the parameters defined in the Zendesk
`Search Documentation `_.
Zenpy defines several keywords that are mapped to the Zendesk comparison operators:
+-----------------+------------------+
| **Keyword** | **Operator** |
+-----------------+------------------+
| keyword | : (equality) |
+-----------------+------------------+
| \*_greater_than | > (numeric|type) |
+-----------------+------------------+
| \*_less_than | < (numeric|type) |
+-----------------+------------------+
| \*_after | > (time|date) |
+-----------------+------------------+
def __call__(self, score=None, sort_order=None, start_time=None, end_time=None):
if sort_order and sort_order not in ('asc', 'desc'):
raise ZenpyException("sort_order must be one of (asc, desc)")
params = dict()
if score:
params['score'] = score
if sort_order:
params['sort_order'] = sort_order
if start_time:
params['start_time'] = to_unix_ts(start_time)
if end_time:
params['end_time'] = to_unix_ts(end_time)
return Url(self.endpoint, params=params)
class MacroEndpoint(BaseEndpoint):
def __call__(self, sort_order=None, sort_by=None, **kwargs):
if sort_order and sort_order not in ('asc', 'desc'):
raise ZenpyException("sort_order must be one of (asc, desc)")
if sort_by and sort_by not in ('alphabetical', 'created_at', 'updated_at', 'usage_1h', 'usage_24h', 'usage_7d'):
raise ZenpyException(
"sort_by is invalid - https://developer.zendesk.com/rest_api/docs/core/macros#available-parameters")
if 'id' in kwargs:
if len(kwargs) > 1:
raise ZenpyException("When specifying an id it must be the only parameter")
params = dict()
path = self.endpoint
for key, value in kwargs.items():
if isinstance(value, bool):
value = str(value).lower()
else:
endpoint_path = "{}/{}".format(self.endpoint, value)
break
return Url(endpoint_path, params=params)
class ChatSearchEndpoint(BaseEndpoint):
def __call__(self, *args, **kwargs):
conditions = list()
if args:
conditions.append(' '.join(args))
conditions.extend(["{}:{}".format(k, v) for k, v in kwargs.items()])
query = " AND ".join(conditions)
return Url(self.endpoint, params=dict(q=query))
class ViewSearchEndpoint(BaseEndpoint):
def __call__(self, query, **kwargs):
kwargs['query'] = query
return Url(self.endpoint, params=kwargs)
class EndpointFactory(object):
"""
Provide access to the various endpoints.
"""
activities = PrimaryEndpoint('activities')
attachments = PrimaryEndpoint('attachments')
attachments.upload = AttachmentEndpoint('uploads.json')
automations = PrimaryEndpoint('automations')
brands = PrimaryEndpoint('brands')
chats = ChatEndpoint('chats')
return Url(path=path, params=parameters)
class SecondaryEndpoint(BaseEndpoint):
def __call__(self, id, **kwargs):
return Url(self.endpoint % dict(id=id), params=kwargs)
class MultipleIDEndpoint(BaseEndpoint):
def __call__(self, *args):
if not args or len(args) < 2:
raise ZenpyException("This endpoint requires at least two arguments!")
return Url(self.endpoint.format(*args))
class IncrementalEndpoint(BaseEndpoint):
"""
An IncrementalEndpoint takes a start_time parameter
for querying the incremental api endpoint.
Note: The Zendesk API expects UTC time. If a timezone aware datetime object is passed
Zenpy will convert it to UTC, however if a naive object or unix timestamp is passed there is nothing
Zenpy can do. It is recommended to always pass timezone aware objects to this endpoint.
:param start_time: unix timestamp or datetime object
:param include: list of items to sideload
"""
def __call__(self, start_time=None, include=None):
if start_time is None:
raise ZenpyException("Incremental Endpoint requires a start_time parameter!")