aiobtclientrpc

Asynchronous low-level communication with BitTorrent clients

Functions

aiobtclientrpc.client(name, *args, **kwargs)[source]

Convenience function to instantiate a RPCBase subclass

Parameters:
  • name (str) – name of the client

  • args – Positional arguments to pass to the RPCBase subclass

  • kwargs – Keyword arguments to pass to the RPCBase subclass

Raises:

ValueError – if there is no RPCBase subclass with a matching name

Returns:

RPCBase instance

aiobtclientrpc.clients()[source]

Return list of RPCBase subclasses

Classes

class aiobtclientrpc.ConnectionStatus(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Current state of the client connection

connected = 'connected'

Connection was established

connecting = 'connecting'

Attempting to connect

disconnected = 'disconnected'

Connection was either lost or terminated

class aiobtclientrpc.DelugeRPC(url=None, *, host=None, port=None, username=None, password=None, timeout=None, proxy_url=None)[source]

Bases: RPCBase

RPC client for Deluge

URL format: [USERNAME:PASSWORD@]HOST[:PORT]

References:

https://deluge.readthedocs.io/en/latest/reference/index.html https://www.rasterbar.com/products/libtorrent/manual-ref.html https://git.deluge-torrent.org/deluge/tree/

RPC methods

RPC methods are only documented as Deluge code. Look for funtions decorated with @export. The RPC method is the module name and the function name concatenated with “.”.

For example, the RPC method name of Daemon.get_method_list() in deluge/core/daemon.py would be “daemon.get_method_list”.

Arguments for RPC methods must be positional/keyword as specified in the function’s call signature.

Events

Like RPC methods, events are not properly documented. You can find event names by grepping for the class name DelugeEvent. The names of subclasses of DelugeEvent are also event names.

Warning

The Deluge daemon does not complain about invalid event names and silently accepts subscribtions to anything. Check your event names carefully!

Raises:

ValueError – if any argument is invalid

URL

alias of DelugeURL

class aiobtclientrpc.DelugeURL(url=None, default=None, on_change=None)[source]

Bases: URL

Deluge RPC URL

default = DelugeURL('localhost:58846')

URL to use when url and default arguments are both falsy

property path

Always None

property scheme

Valid schemes: None

class aiobtclientrpc.QbittorrentRPC(url=None, *, scheme=None, host=None, port=None, username=None, password=None, timeout=None, proxy_url=None)[source]

Bases: RPCBase

RPC client for qBittorrent

URL format: [http[s]://][USERNAME:PASSWORD@]HOST[:PORT]

Reference: https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1)

Calling RPC methods

Passing arguments as keywords:

>>> call(
>>>     "torrents/info",
>>>     hashes="|".join([
>>>         "d5a34e9eb4709e265f0f03a1c8ab60890dcb94a9",
>>>         "4435ef55af79b350e7b85d5b330a7886a61e3bdf",
>>>     ]),
>>>     sort="size",
>>>     limit=20,
>>> )

Passing arguments as dictionary:

>>> call(
>>>     "torrents/info",
>>>     {
>>>         "hashes": "|".join([
>>>             "d5a34e9eb4709e265f0f03a1c8ab60890dcb94a9",
>>>             "4435ef55af79b350e7b85d5b330a7886a61e3bdf",
>>>         ]),
>>>         "sort": "size",
>>>         "limit" 20,
>>>     },
>>> )

Passing arguments as both keywords and dictionary (keyword values are overloaded by dictionary values):

>>> call(
>>>     "torrents/info",
>>>     options={
>>>         "hashes": "|".join([
>>>             "d5a34e9eb4709e265f0f03a1c8ab60890dcb94a9",
>>>             "4435ef55af79b350e7b85d5b330a7886a61e3bdf",
>>>         ]),
>>>         "sort": "size",
>>>     },
>>>     limit=20,
>>> )

The files argument is special. It is used to add torrents:

>>> call(
>>>     'torrents/add',
>>>     files=[
>>>         ('filename', (
>>>             os.path.abspath('path/to/1.torrent'),
>>>             open('path/to/1.torrent', 'rb'),
>>>             'application/x-bittorrent',
>>>         )),
>>>         ('filename', (
>>>             os.path.abspath('path/to/2.torrent'),
>>>             open('path/to/2.torrent', 'rb'),
>>>             'application/x-bittorrent',
>>>         )),
>>>     ],
>>>     options={
>>>         'savepath': 'special/download/path',
>>>         'paused': 'true',
>>>     },
>>> )
Raises:

ValueError – if any argument is invalid

URL

alias of QbittorrentURL

class aiobtclientrpc.QbittorrentURL(url=None, default=None, on_change=None)[source]

Bases: URL

qBittorrent RPC URL

default = QbittorrentURL('http://localhost:8080')

URL to use when url and default arguments are both falsy

property path

Always None

property scheme

Valid schemes: http, https

class aiobtclientrpc.RPCBase[source]

Bases: ABC

Base class for BitTorrent client RPC interfaces

abstract property URL

URL subclass

Setting properties on an instance of this subclass to invalid values should raise ValueError. For example, RtorrentURL only accepts the schemes http, scgi or file.

async add_event_handler(event, handler, autoremove=False)[source]

Call callable when event happens

Parameters:
  • event – Name or other identifier of the event (refer to the client documentation for valid values)

  • handler – Callable to be called when event happens (refer to the client documentation for the call signature)

  • autoremove – Whether handler should be unregistered automatically after it is garbage collected (see weakref)

If handler is already registered for event, do nothing.

Multiple handlers can be registered for the same event. They will be called in the order they are added.

Raises:

NotImplementedError – if the client doesn’t support events

async call(*args, **kwargs)[source]

Call RPC method and return the result

If status is not ConnectionStatus.connected, call connect() first.

Raises:
Returns:

the return value of the RPC method

This should be decoded bytes, deserialized JSON, etc. Exceptions from decoding and deserializing should be raised as RPCError.

async connect()[source]

Connect to RPC interface

Do nothing if status indicates we are already connected.

It is safe to call this method multiple times concurrently. The first call will actually connect while the remaining calls wait for the first call to finish. If the first call fails, each of the remaining calls will become the first call, i.e. it will attempt to connect while the others wait for it.

Raises:
default_timeout = 60.0

Default timeout

async disconnect()[source]

Disconnect from RPC interface

Do nothing if status indicates we are already disconnected.

It is safe to call this method multiple times concurrently. The first call will actually disconnect while the remaining calls wait for the first call to finish. If the first call fails, each of the remaining call will become the first call, i.e. it will attempt to disconnect while the others wait for it.

status is always ConnectionStatus.disconnected when this method returns, regardless of any raised exceptions.

Raises:
property is_connected

True if status: is :attr:`~.ConnectionStatus.connected, False otherwise

abstract property label

Properly capitalized name of the BitTorrent client

abstract property name

Lowercase name of the BitTorrent client

property proxy_url

SOCKS5, SOCKS4 or HTTP proxy URL for tunneling the RPC connection

If this property is set to a falsy value, no proxy is used.

Raises:

ValueError – if set to an invalid URL

async remove_event_handler(event, handler)[source]

Stop calling callable when event happens

See add_event_handler().

If handler is not registered for event, do nothing.

Raises:

NotImplementedError – if the client doesn’t support events

set_connected_callback(callback, *args, **kwargs)[source]

Schedule callback to be called when a connection attempt was successful

Parameters:

callback – Callable to call

All remaining arguments are passed to callback when it is called.

set_connecting_callback(callback, *args, **kwargs)[source]

Schedule callback to be called when a connection attempt is made

Parameters:

callback – Callable to call

All remaining arguments are passed to callback when it is called.

set_disconnected_callback(callback, *args, **kwargs)[source]

Schedule callback to be called when the connection was lost or a connection attempt has failed

Parameters:

callback – Callable to call

All remaining arguments are passed to callback when it is called.

property status

ConnectionStatus enum

property timeout

Timeout in seconds for RPC calls

If this property is set to a falsy value, default_timeout is used.

Raises:

ValueError – if set to something that can’t be coerced into a float

unset_connected_callback(callback)[source]

Unschedule callback to be called when a connection attempt was successful

Parameters:

callback – Callable to call

unset_connecting_callback(callback)[source]

Unschedule callback to be called when a connection attempt is made

Parameters:

callback – Callable to call

unset_disconnected_callback(callback)[source]

Unschedule callback to be called when the connection was lost or a connection attempt has failed

Parameters:

callback – Callable to call

property url

URL of the RPC interface

Changing any of the properties will re-connect to the new URL on the next call().

If this property is set to a falsy value, default is used.

Raises:

ValueError – if set to an invalid URL

async wait_for_event(event)[source]

Block until event happens

Parameters:

event – Name or other identifier of the event (refer to the client documentation for valid values)

Raises:

NotImplementedError – if the client doesn’t support events

class aiobtclientrpc.RtorrentRPC(url=None, *, scheme=None, host=None, port=None, username=None, password=None, timeout=None, proxy_url=None)[source]

Bases: RPCBase

RPC client for rTorrent

URL formats:
  • [scgi://]HOST[:PORT]

  • [file://]SOCKET_PATH

  • http[s]://[USERNAME:PASSWORD@]HOST[:PORT][/PATH]

References:
Raises:

ValueError – if any argument is invalid

URL

alias of RtorrentURL

async get_supported_method(*candidates)[source]

Get first supported method from multiple candidates

Parameters:

candidates – Sequence of method names

Raises:

ValueError – if no method name in candidates is supported

class aiobtclientrpc.RtorrentURL(url=None, default=None, on_change=None)[source]

Bases: URL

rTorrent RPC URL

default = RtorrentURL('scgi://127.0.0.1:5000')

URL to use when url and default arguments are both falsy

property host

Host name or IP address or None

property password

Password for authentication

property path

File system path or request path or None

property port

Port number or None

property scheme

Valid schemes: file, scgi, http, https

property username

Username for authentication

class aiobtclientrpc.TransmissionRPC(url=None, *, scheme=None, host=None, port=None, path=None, username=None, password=None, timeout=None, proxy_url=None)[source]

Bases: RPCBase

RPC client for Transmission

URL format: [http[s]://][USERNAME:PASSWORD@]HOST[:PORT][/PATH]

Reference: https://github.com/transmission/transmission/blob/main/docs/rpc-spec.md

Calling RPC methods

RPC methods can be called like python functions:

>>> client.call("torrent-add", filename="path/to.torrent", paused=True)

If you need to pass argument names that contain characters that are illegal for keyword arguments (e.g. “-“), provide a dictionary:

>>> client.call(
    "torrent-add",
    {"filename": "file.torrent", "download-dir": "/some/path"},
)

If you provide keyword arguments and a dictionary, values from the dictionary overload keyword arguments.

Raises:

ValueError – if any argument is invalid

URL

alias of TransmissionURL

class aiobtclientrpc.TransmissionURL(url=None, default=None, on_change=None)[source]

Bases: URL

Transmission RPC URL

default = TransmissionURL('http://localhost:9091/transmission/rpc')

URL to use when url and default arguments are both falsy

property scheme

Valid schemes: http, https

class aiobtclientrpc.URL(url=None, default=None, on_change=None)[source]

Bases: object

URL of an RPC interface

This implementation attempts to parse URLs more intuitively instead of following any specs. For example "localhost:1234" is interpreted as host=localhost, port=1234 instead of scheme=localhost, path=1234.

Parameters:
  • url (str) – URL string

  • default (str) – Fallback URL when url is falsy

  • on_change (callable) – Callback that is called with no arguments when any property is modified

Raises:

ValueError – if url is invalid

default = URL('')

URL to use when url and default arguments are both falsy

property host

Host name or IP address or None

property password

Password for authentication

property path

File system path or request path or None

property port

Port number or None

property scheme

Scheme (e.g. "http" or "file")

property username

Username for authentication

property with_auth

URL string with username and password

property without_auth

URL string without username and password

Exceptions

exception aiobtclientrpc.AuthenticationError[source]

Failed to prove identity

exception aiobtclientrpc.ConnectionError(msg)[source]

Failed to connect to the client, e.g. because it isn’t running

exception aiobtclientrpc.Error[source]

Base class for all exceptions raised by this package

exception aiobtclientrpc.RPCError(msg, info=None)[source]

Generic RPC error

This can be some kind of miscommunication with the RPC service (e.g. unknown method called, invalid or missing argument, etc), which should be a considered a bug. But it can also be a normal error message (e.g. unknown torrent), that should be communicated to the user.

exception aiobtclientrpc.TimeoutError[source]

Timeout for sending request and reading response

Besides Error, this is also a subclass of the builtin TimeoutError.

exception aiobtclientrpc.ValueError[source]

Invalid value (e.g. port 65536)

Besides Error, this is also a subclass of the builtin ValueError.