Internal modules

Classes documented here are used by other parts of the library, and are typically not needed for client use of the API.

HTTP API requests

class skpy.conn.SkypeConnection[source]

The main connection class – handles all requests to API resources.

To authenticate with a username and password, use setUserPwd() to store the credentials. Token files can be specified with setTokenFile().

tokens

Token strings used to connect to various Skype APIs. Uses keys skype and reg.

Type

dict

tokenExpiry

Map from token key to datetime of expiry.

Type

dict

tokenFile

Path to file holding token data for the current session.

Type

str

msgsHost

Derived API base URL during registration token retrieval.

Type

str

sess

Shared session used for all API requests.

Type

requests.Session

endpoints

Container of SkypeEndpoint instances for the current session.

Type

dict

connected

Whether the connection instance is ready to make API calls.

Type

bool

guest

Whether the connected account only has guest privileges.

Type

bool

Auth = ('SkypeToken', 'Authorize', 'RegToken')

Authentication types for different API calls.

Auth.SkypeToken

Add an X-SkypeToken header with the Skype token.

Auth.Authorize

Add an Authorization header with the Skype token.

Auth.RegToken

Add a RegistrationToken header with the registration token.

Type

SkypeEnum

static handle(*codes, **kwargs)[source]

Method decorator: if a given status code is received, re-authenticate and try again.

Parameters
  • codes (int list) – status codes to respond to

  • regToken (bool) – whether to try retrieving a new token on error

Returns

decorator function, ready to apply to other methods

Return type

method

classmethod externalCall(method, url, codes=(200, 201, 204, 207), **kwargs)[source]

Make a public API call without a connected Skype instance.

The obvious implications are that no authenticated calls are possible, though this allows accessing some public APIs such as join URL lookups.

Parameters
  • method (str) – HTTP request method

  • url (str) – full URL to connect to

  • codes (int list) – expected HTTP response codes for success

  • kwargs (dict) – any extra parameters to pass to requests.request()

Returns

response object provided by requests

Return type

requests.Response

Raises
__init__()[source]

Create a new, unconnected instance.

closure(method, *args, **kwargs)[source]

Create a generic closure to call a method with fixed arguments.

Parameters
  • method (MethodType) – bound method of the class

  • args (list) – positional arguments for the method

  • kwargs (dict) – keyword arguments for the method

Returns

bound method closure

Return type

MethodType

__call__(method, url, codes=(200, 201, 202, 204, 207), auth=None, headers=None, **kwargs)[source]

Make an API call. Most parameters are passed directly to requests.

Set codes to a list of valid HTTP response codes – an exception is raised if the response does not match.

If authentication is required, set auth to one of the Auth constants.

Parameters
  • method (str) – HTTP request method

  • url (str) – full URL to connect to

  • codes (int list) – expected HTTP response codes for success

  • auth (Auth) – authentication type to be included

  • headers (dict) – additional headers to be included

  • kwargs (dict) – any extra parameters to pass to requests.request()

Returns

response object provided by requests

Return type

requests.Response

Raises
syncStateCall(method, url, params={}, **kwargs)[source]

Follow and track sync state URLs provided by an API endpoint, in order to implicitly handle pagination.

In the first call, url and params are used as-is. If a syncState endpoint is provided in the response, subsequent calls go to the latest URL instead.

Parameters
  • method (str) – HTTP request method

  • url (str) – full URL to connect to

  • params (dict) – query parameters to include in the URL

  • kwargs (dict) – any extra parameters to pass to __call__()

setTokenFile(path)[source]

Enable reading and writing session tokens to a file at the given location.

Parameters

path (str) – path to file used for token storage

readToken()[source]

Attempt to re-establish a connection using previously acquired tokens.

If the Skype token is valid but the registration token is invalid, a new endpoint will be registered.

Raises

SkypeAuthException – if the token file cannot be used to authenticate

writeToken()[source]

Store details of the current connection in the named file.

This can be used by readToken() to re-authenticate at a later time.

verifyToken(auth)[source]

Ensure the authentication token for the given auth method is still valid.

Parameters

auth (Auth) – authentication type to check

Raises

SkypeAuthException – if Skype auth is required, and the current token has expired and can’t be renewed

skypeTokenClosure(method, *args, **kwargs)[source]

Replace the stub getSkypeToken() method with one that connects using the given credentials. Avoids storing the account password in an accessible way.

setUserPwd(user, pwd)[source]

Replace the stub getSkypeToken() method with one that connects via SOAP login using the given credentials. Avoids storing the account password in an accessible way.

Parameters
  • user (str) – username or email address of the connecting account

  • pwd (str) – password of the connecting account

liveLogin(user, pwd)[source]

Obtain connection parameters from the Microsoft account login page, and perform a login with the given email address or Skype username, and its password. This emulates a login to Skype for Web on login.live.com.

Note

Microsoft accounts with two-factor authentication enabled are not supported, and will cause a SkypeAuthException to be raised. See the exception definitions for other possible causes.

Parameters
  • user (str) – username or email address of the connecting account

  • pwd (str) – password of the connecting account

Returns

Skype token, and associated expiry if known

Return type

(str, datetime.datetime) tuple

Raises
soapLogin(user, pwd)[source]

Perform a login with the given email address or Skype username, and its password, using the Microsoft account SOAP login APIs.

Note

Microsoft accounts with two-factor authentication enabled are supported if an application-specific password is provided. Skype accounts must be linked to a Microsoft account with an email address, otherwise SkypeAuthException will be raised. See the exception definitions for other possible causes.

Parameters
  • user (str) – username or email address of the connecting account

  • pwd (str) – password of the connecting account

Returns

Skype token, and associated expiry if known

Return type

(str, datetime.datetime) tuple

Raises
guestLogin(url, name)[source]

Connect to Skype as a guest, joining a given conversation.

In this state, some APIs (such as contacts) will return 401 status codes. A guest can only communicate with the conversation they originally joined.

Parameters
  • url (str) – public join URL for conversation, or identifier from it

  • name (str) – display name as shown to other participants

Raises
getSkypeToken()[source]

A wrapper for the default login provider that applies the previously given username and password.

Raises

SkypeAuthException – if credentials were never provided

refreshSkypeToken()[source]

Take the existing Skype token and refresh it, to extend the expiry time without other credentials.

Raises
getUserId()[source]

Ask Skype for the authenticated user’s identifier, and store it on the connection object.

getRegToken()[source]

Acquire a new registration token.

Once successful, all tokens and expiry times are written to the token file (if specified on initialisation).

syncEndpoints()[source]

Retrieve all current endpoints for the connected user.

class skpy.conn.SkypeAuthProvider[source]

A base class for authentication providers. Subclasses should implement the auth() method.

auth(*args, **kwargs)[source]

Authenticate a user, given some form of identification.

Returns

Skype token, and associated expiry if known

Return type

(str, datetime.datetime) tuple

Raises
class skpy.conn.SkypeAPIAuthProvider[source]

An authentication provider that connects via the Skype API. Only compatible with Skype usernames.

auth(user, pwd)[source]

Perform a login with the given Skype username and its password. This emulates a login to Skype for Web on api.skype.com.

Parameters
  • user (str) – username of the connecting account

  • pwd (str) – password of the connecting account

Returns

Skype token, and associated expiry if known

Return type

(str, datetime.datetime) tuple

Raises
class skpy.conn.SkypeLiveAuthProvider[source]

An authentication provider that connects via Microsoft account authentication.

checkUser(user)[source]

Query a username or email address to see if a corresponding Microsoft account exists.

Parameters

user (str) – username or email address of an account

Returns

whether the account exists

Return type

bool

auth(user, pwd)[source]

Obtain connection parameters from the Microsoft account login page, and perform a login with the given email address or Skype username, and its password. This emulates a login to Skype for Web on login.live.com.

Note

Microsoft accounts with two-factor authentication enabled are not supported, and will cause a SkypeAuthException to be raised. See the exception definitions for other possible causes.

Parameters
  • user (str) – username or email address of the connecting account

  • pwd (str) – password of the connecting account

Returns

Skype token, and associated expiry if known

Return type

(str, datetime.datetime) tuple

Raises
class skpy.conn.SkypeSOAPAuthProvider[source]

An authentication provider that connects via Microsoft account SOAP authentication.

auth(user, pwd)[source]

Perform a SOAP login with the given email address or Skype username, and its password.

Note

Microsoft accounts with two-factor authentication enabled must provide an application-specific password.

Parameters
  • user (str) – username or email address of the connecting account

  • pwd (str) – password of the connecting account

Returns

Skype token, and associated expiry if known

Return type

(str, datetime.datetime) tuple

Raises
class skpy.conn.SkypeGuestAuthProvider[source]

An authentication provider that connects and joins a public conversation via a join URL.

auth(url, name)[source]

Connect to Skype as a guest, joining a given conversation.

In this state, some APIs (such as contacts) will return 401 status codes. A guest can only communicate with the conversation they originally joined.

Parameters
  • url (str) – public join URL for conversation, or identifier from it

  • name (str) – display name as shown to other participants

Returns

Skype token, and associated expiry if known

Return type

(str, datetime.datetime) tuple

Raises
class skpy.conn.SkypeRefreshAuthProvider[source]

An authentication provider that connects via the Skype API. Only compatible with Skype usernames.

auth(token)[source]

Take an existing Skype token and refresh it, to extend the expiry time without other credentials.

Parameters

token (str) – existing Skype token

Returns

Skype token, and associated expiry if known

Return type

(str, datetime.datetime) tuple

Raises
class skpy.conn.SkypeRegistrationTokenProvider[source]

An authentication provider that handles the handshake for a registration token.

auth(skypeToken)[source]

Request a new registration token using a current Skype token.

Parameters

skypeToken (str) – existing Skype token

Returns

registration token, associated expiry if known,

resulting endpoint hostname, endpoint if provided

Return type

(str, datetime.datetime, str, SkypeEndpoint) tuple

Raises
static getMac256Hash(challenge, appId='msmsgs@msnmsgr.com', key='Q1P7W2E4J9R8U3S5')[source]

Generate the lock-and-key response, needed to acquire registration tokens.

class skpy.conn.SkypeEndpoint[source]

An endpoint represents a single point of presence within Skype.

Typically, a user with multiple devices would have one endpoint per device (desktop, laptop, mobile and so on).

Endpoints are time-sensitive – they lapse after a short time unless kept alive (by ping() or otherwise).

__init__(conn, id)[source]

Create a new instance based on a newly-created endpoint identifier.

Parameters
  • conn (SkypeConnection) – parent connection instance

  • id (str) – endpoint identifier as generated by the API

config(name='skype')[source]

Configure this endpoint to allow setting presence.

Parameters

name (str) – display name for this endpoint

ping(timeout=12)[source]

Send a keep-alive request for the endpoint.

Parameters

timeout (int) – maximum amount of time for the endpoint to stay active

subscribe()[source]

Subscribe to contact and conversation events. These are accessible through getEvents().

subscribePresence(contacts)[source]

Enable presence subscriptions for the authenticated user’s contacts.

Parameters

contacts (SkypeContacts) – contact list to select user IDs

getEvents()[source]

Retrieve a list of events since the last poll. Multiple calls may be needed to retrieve all events.

If no events occur, the API will block for up to 30 seconds, after which an empty list is returned.

If any event occurs whilst blocked, it is returned immediately.

Returns

list of events, possibly empty

Return type

SkypeEvent list

Miscellaneous

class skpy.core.SkypeObj[source]

A basic Skype object. Holds references to the parent Skype instance, and a raw object from the API.

attrs

List of defined fields for the class. Used by initAttrs() to create an __init__() method.

Type

tuple

defaults

Collection of default values when any keyword arguments are omitted from the constructor.

Type

dict

skype

Parent Skype instance.

Type

Skype

raw

Raw object, as provided by the API.

Type

dict

__init__(skype=None, raw=None)[source]

Instantiate a plain instance of this class, and store a reference to the Skype object for later API calls.

Normally this method won’t be called or implemented directly.

Implementers should make use of fromRaw() and the initAttrs() decorator instead.

Parameters
  • skype (Skype) – parent Skype instance

  • raw (dict) – raw object, as provided by the API

classmethod rawToFields(raw={})[source]

Convert the raw properties of an API response into class fields. Override to process additional values.

Parameters

raw (dict) – raw object, as provided by the API

Returns

a collection of fields, with keys matching attrs

Return type

dict

classmethod fromRaw(skype=None, raw={})[source]

Create a new instance based on the raw properties of an API response.

This can be overridden to automatically create subclass instances based on the raw content.

Parameters
  • skype (Skype) – parent Skype instance

  • raw (dict) – raw object, as provided by the API

Returns

the new class instance

Return type

SkypeObj

merge(other)[source]

Copy properties from other into self, skipping None values. Also merges the raw data.

Parameters

other (SkypeObj) – second object to copy fields from

__str__()[source]

Pretty print the object, based on the class’ attrs. Produces output something like:

[<class name>]
<attribute>: <value>

Nested objects are indented as needed.

__repr__()[source]

Dump properties of the object into a Python-like statement, based on the class’ attrs.

The resulting string is an expression that should evaluate to a similar object, minus Skype connection.

class skpy.core.SkypeObjs[source]

A basic Skype collection. Acts as a container for objects of a given type.

synced

Whether an initial set of objects has been cached.

Type

bool

cache

Storage of objects by identifier key.

Type

dict

__init__(skype=None)[source]

Create a new container object. The synced state and internal cache are initialised here.

Parameters

skype (Skype) – parent Skype instance

__getitem__(key)[source]

Provide key lookups for items in the cache. Subclasses may override this to handle not-yet-cached objects.

__iter__()[source]

Create an iterator for all objects (not their keys) in this collection.

sync()[source]

A stub method that subclasses can implement to retrieve an initial set of objects.

merge(obj)[source]

Add a given object to the cache, or update an existing entry to include more fields.

Parameters

obj (SkypeObj) – object to add to the cache

class skpy.core.SkypeEnum[source]

A basic implementation for an enum.

__init__(label, names=(), path=None)[source]

Create a new enumeration. The parent enum creates an instance for each item.

Parameters
  • label (str) – enum name

  • names (list) – item labels

  • path (list) – qualified parent name, for repr() output

__getitem__(item)[source]

Provide list-style index lookups for each item.

__str__()[source]

Show a list of items for the parent, or just the label for each item.

exception skpy.core.SkypeException[source]

A generic Skype-related exception.

exception skpy.core.SkypeApiException[source]

An exception thrown for errors specific to external API calls.

Arguments will usually be of the form (message, response).

exception skpy.core.SkypeAuthException[source]

An exception thrown when authentication cannot be completed.

Arguments will usually be of the form (message, response). If the server provided an error message, it will be present in a third argument.

Unfortunately there are many possible reasons why a login may be rejected, including but not limited to:

  • an incorrect username or password

  • two-factor authentication

  • rate-limiting after multiple failed login attempts

  • a captcha being required

  • an update to the Terms of Service that must be accepted

class skpy.util.SkypeUtils[source]

A collection of miscellaneous static methods used throughout the library.

config

Raw object containing miscellaneous server-side flags and configuration.

Type

dict

static

Raw object containing emoticons and packs.

Type

dict

Status = ('Offline', 'Hidden', 'Busy', 'Away', 'Idle', 'Online')

Types of user availability.

Status.Offline

User is not connected.

Status.Hidden

User is pretending to be offline. Shows as hidden to the current user, offline to anyone else.

Status.Busy

User wishes not to be disturbed. Disables notifications on some clients (e.g. on the desktop).

Status.Away

User has explicitly marked themselves as away. Alternatively, this may just be an alias for idle.

Status.Idle

User is online but not active. Messages will likely be delivered as normal, though may not be read.

Status.Online

User is available to talk.

Type

SkypeEnum

static noPrefix(s)[source]

Remove the type prefix from a chat identifier (e.g. 8: for a one-to-one, 19: for a group).

Parameters

s (str) – string to transform

Returns

unprefixed string

Return type

str

static userToId(url)[source]

Extract the username from a contact URL.

Matches addresses containing users/<user> or users/ME/contacts/<user>.

Parameters

url (str) – Skype API URL

Returns

extracted identifier

Return type

str

static chatToId(url)[source]

Extract the conversation ID from a conversation URL.

Matches addresses containing conversations/<chat>.

Parameters

url (str) – Skype API URL

Returns

extracted identifier

Return type

str

class classprop[source]

Method decorator: allows designating class methods as properties.

static initAttrs(cls)[source]

Class decorator: automatically generate an __init__ method that expects args from cls.attrs and stores them.

Parameters

cls (class) – class to decorate

Returns

same, but modified, class

Return type

class

static convertIds(*types, **kwargs)[source]

Class decorator: add helper methods to convert identifier properties into SkypeObjs.

Parameters
  • types (str list) – simple field types to add properties for (user, users or chat)

  • user (str list) – attribute names to treat as single user identifier fields

  • users (str list) – attribute names to treat as user identifier lists

  • chat (str list) – attribute names to treat as chat identifier fields

Returns

decorator function, ready to apply to other methods

Return type

method

static truthyAttrs(cls)[source]

Class decorator: override __bool__ to set truthiness based on any attr being present.

Parameters

cls (class) – class to decorate

Returns

same, but modified, class

Return type

class

static exhaust(fn, transform=None, *args, **kwargs)[source]

Repeatedly call a function, starting with init, until false-y, yielding each item in turn.

The transform parameter can be used to map a collection to another format, for example iterating over a dict by value rather than key.

Use with state-synced functions to retrieve all results.

Parameters
  • fn (method) – function to call

  • transform (method) – secondary function to convert result into an iterable

  • args (list) – positional arguments to pass to fn

  • kwargs (dict) – keyword arguments to pass to fn

Returns

generator of objects produced from the method

Return type

generator

static cacheResult(fn)[source]

Method decorator: calculate the value on first access, produce the cached value thereafter.

If the function takes arguments, the cache is a dictionary using all arguments as the key.

Parameters

fn (method) – function to decorate

Returns

wrapper function with caching

Return type

method