spade package

Submodules

spade.agent module

class spade.agent.Agent(jid: str, password: str, port: int = 5222, verify_security: bool = False)[source]

Bases: object

add_behaviour(behaviour: BehaviourType, template: Optional[Template] = None) None[source]

Adds and starts a behaviour to the agent. If template is not None it is used to match new messages and deliver them to the behaviour.

Args:

behaviour (Type[spade.behaviour.CyclicBehaviour]): the behaviour to be started template (spade.template.Template, optional): the template to match messages with (Default value = None)

property avatar: str

Generates a unique avatar for the agent based on its JID. Uses Gravatar service with MonsterID option.

Returns:

str: the url of the agent’s avatar

static build_avatar_url(jid: str) str[source]

Static method to build a gravatar url with the agent’s JID

Args:

jid (aioxmpp.JID): an XMPP identifier

Returns:

str: a URL for the gravatar

dispatch(msg: Message) List[Task][source]

Dispatch the message to every behaviour that is waiting for it using their templates match.

Args:

msg (spade.message.Message): the message to dispatch.

Returns:

list(asyncio.Future): a list of tasks for each message queuing in each matching behavior.

get(name: str) Any[source]

Recovers a knowledge item from the agent’s knowledge base.

Args:

name(str): name of the item

Returns:

object: the object retrieved or None

has_behaviour(behaviour: Type[CyclicBehaviour]) bool[source]

Checks if a behaviour is added to an agent.

Args:

behaviour (Type[spade.behaviour.CyclicBehaviour]): the behaviour instance to check

Returns:

bool: a boolean that indicates wether the behaviour is inside the agent.

is_alive() bool[source]

Checks if the agent is alive.

Returns:

bool: wheter the agent is alive or not

property name: str

Returns the name of the agent (the string before the ‘@’)

Returns:

str: the name of the agent (the string before the ‘@’)

remove_behaviour(behaviour: Type[CyclicBehaviour]) None[source]

Removes a behaviour from the agent. The behaviour is first killed.

Args:

behaviour (Type[spade.behaviour.CyclicBehaviour]): the behaviour instance to be removed

set(name: str, value: Any)[source]

Stores a knowledge item in the agent knowledge base.

Args:

name (str): name of the item value (object): value of the item

set_container(container: Container) None[source]

Sets the container to which the agent is attached

Args:

container (spade.container.Container): the container to be attached to

set_loop(loop) None[source]
async setup() None[source]

Setup agent before startup. This coroutine may be overloaded.

async start(auto_register: bool = True) None[source]

Starts this agent.

Args:

auto_register (bool): register the agent in the server (Default value = True)

Returns:

None

async stop() None[source]

Stops this agent.

submit(coro: Coroutine) Task[source]

Runs a coroutine in the event loop of the agent. this call is not blocking.

Args:

coro (Coroutine): the coroutine to be run

Returns:

asyncio.Task: the Task assigned to the coroutine execution

exception spade.agent.AuthenticationFailure[source]

Bases: Exception

exception spade.agent.DisconnectedException[source]

Bases: Exception

spade.behaviour module

exception spade.behaviour.BehaviourNotFinishedException[source]

Bases: Exception

class spade.behaviour.CyclicBehaviour[source]

Bases: object

This behaviour is executed cyclically until it is stopped.

async enqueue(message: Message) None[source]

Enqueues a message in the behaviour’s mailbox

Args:

message (spade.message.Message): the message to be enqueued

property exit_code: Any

Returns the exit_code of the behaviour. It only works when the behaviour is done or killed, otherwise it raises an exception.

Returns:

object: the exit code of the behaviour

Raises:

BehaviourNotFinishedException: if the behaviour is not yet finished

get(name: str) Any[source]

Recovers a knowledge item from the agent’s knowledge base.

Args:

name (str): name of the item

Returns:

Any: the object retrieved or None

is_done() bool[source]

Check if the behaviour is finished

Returns:

bool: whether the behaviour is finished or not

is_killed() bool[source]

Checks if the behaviour was killed by means of the kill() method.

Returns:

bool: whether the behaviour is killed or not

async join(timeout: Optional[float] = None) None[source]

Wait for the behaviour to complete

Args:

timeout (Optional[float]): an optional timeout to wait to join (if None, the join is blocking)

Returns:

None

Raises:

TimeoutError: if the timeout is reached

kill(exit_code: Optional[Any] = None) None[source]

Stops the behaviour

Args:

exit_code (object, optional): the exit code of the behaviour (Default value = None)

mailbox_size() int[source]

Checks if there is a message in the mailbox

Returns:

int: the number of messages in the mailbox

match(message: Message) bool[source]

Matches a message with the behaviour’s template

Args:

message(spade.message.Message): the message to match with

Returns:

bool: wheter the messaged matches or not

async on_end() None[source]

Coroutine called after the behaviour is done or killed.

async on_start() None[source]

Coroutine called before the behaviour is started.

async receive(timeout: Optional[float] = None) Optional[Message][source]

Receives a message for this behaviour. If timeout is not None it returns the message or “None” after timeout is done.

Args:

timeout (float, optional): number of seconds until return

Returns:

spade.message.Message: a Message or None

abstract async run() None[source]

Body of the behaviour. To be implemented by user.

async send(msg: Message) None[source]

Sends a message.

Args:

msg (spade.message.Message): the message to be sent.

set(name: str, value: Any) None[source]

Stores a knowledge item in the agent knowledge base.

Args:

name (str): name of the item value (Any): value of the item

set_agent(agent) None[source]

Links behaviour with its owner agent

Args:

agent (spade.agent.Agent): the agent who owns the behaviour

set_template(template: Template) None[source]

Sets the template that is used to match incoming messages with this behaviour.

Args:

template (spade.template.Template): the template to match with

start() None[source]

starts behaviour in the event loop

class spade.behaviour.FSMBehaviour[source]

Bases: CyclicBehaviour

A behaviour composed of states (oneshotbehaviours) that may transition from one state to another.

add_state(name: str, state: State, initial: bool = False) None[source]

Adds a new state to the FSM.

Args:

name (str): the name of the state, which is used as its identifier. state (spade.behaviour.State): The state class initial (bool, optional): wether the state is the initial state or not. (Only one initial state is allowed) (Default value = False)

add_transition(source: str, dest: str) None[source]

Adds a transition from one state to another.

Args:

source (str): the name of the state from where the transition starts dest (str): the name of the state where the transition ends

get_state(name) State[source]
get_states() Dict[str, State][source]
is_valid_transition(source: str, dest: str) bool[source]

Checks if a transitions is registered in the FSM

Args:

source (str): the source state name dest (str): the destination state name

Returns:

bool: wether the transition is valid or not

async run() None[source]

In this kind of behaviour there is no need to overload run. The run methods to be overloaded are in the State class.

setup() None[source]
to_graphviz() str[source]

Converts the FSM behaviour structure to Graphviz syntax

Returns:

str: the graph in Graphviz syntax

exception spade.behaviour.NotValidState[source]

Bases: Exception

exception spade.behaviour.NotValidTransition[source]

Bases: Exception

class spade.behaviour.OneShotBehaviour[source]

Bases: CyclicBehaviour

This behaviour is only executed once

class spade.behaviour.PeriodicBehaviour(period: float, start_at: Optional[datetime] = None)[source]

Bases: CyclicBehaviour

This behaviour is executed periodically with an interval

property period: timedelta

Get the period.

class spade.behaviour.State[source]

Bases: OneShotBehaviour

A state of a FSMBehaviour is a OneShotBehaviour

set_next_state(state_name: str) None[source]

Set the state to transition to when this state is finished. state_name must be a valid state and the transition must be registered. If set_next_state is not called then current state is a final state.

Args:

state_name (str): the name of the state to transition to

class spade.behaviour.TimeoutBehaviour(start_at)[source]

Bases: OneShotBehaviour

This behaviour is executed once at after specified datetime

spade.behaviour.now(tz=None)

Returns new datetime object representing current time local to tz.

tz

Timezone object.

If no tz is specified, uses local timezone.

spade.cli module

spade.cli.check_port_in_use(port, host='0.0.0.0')[source]

Checks if a port is in use

spade.cli.create_cli()[source]

Factory function to create the CLI

spade.container module

class spade.container.Container[source]

Bases: Container

The container class allows agents to exchange messages without using the XMPP socket if they are in the same process. The container is a singleton.

spade.container.get_or_create_eventloop()[source]

Create or retrieve the appropriate event loop, using uvloop on Linux/macOS and winloop on Windows if available.

spade.container.run_container(main_func: Coroutine) None[source]

spade.message module

class spade.message.Message(to: Optional[str] = None, sender: Optional[str] = None, body: Optional[str] = None, thread: Optional[str] = None, metadata: Optional[Dict[str, str]] = None)[source]

Bases: MessageBase

make_reply() Message[source]

Creates a copy of the message, exchanging sender and receiver

Returns:

spade.message.Message: a new message with exchanged sender and receiver

prepare(client: ClientXMPP) Message[source]

Returns a slixmpp.stanza.Message built from the Message and prepared to be sent.

Args:

client (ClientXMPP): An XMPP client, whose stream will be used to send the message

Returns:

slixmpp.stanza.Message: the message prepared to be sent

class spade.message.MessageBase(to: Optional[str] = None, sender: Optional[str] = None, body: Optional[str] = None, thread: Optional[str] = None, metadata: Optional[Dict[str, str]] = None)[source]

Bases: object

property body: str

Get body of the message Returns:

str: the body of the message

classmethod from_node(node: Message) Type[MessageBase][source]

Creates a new spade.message.Message from a slixmpp.stanza.Message

Args:

node (slixmpp.stanza.Message): a slixmpp Message

Returns:

spade.message.Message: a new spade Message

get_metadata(key: str) str[source]

Get the value of a metadata. Returns None if metadata does not exist.

Args:

key (str): name of the metadata

Returns:

str: the value of the metadata (or None)

property id: int
match(message: Type[MessageBase]) bool[source]

Returns wether a message matches with this message or not. The message can be a Message object or a Template object.

Args:

message (spade.message.Message): the message to match to

Returns:

bool: wether the message matches or not

property sender: JID

Get jid of the sender

Returns:

slixmpp.JID: jid of the sender

set_metadata(key: str, value: str) None[source]

Add a new metadata to the message

Args:

key (str): name of the metadata value (str): value of the metadata

property thread: str

Get Thread of the message

Returns:

str: thread id

property to: JID

Gets the jid of the receiver.

Returns:

slixmpp.JID: jid of the receiver

spade.presence module

class spade.presence.Contact(jid: JID, name: str, subscription: str, ask: str, groups: list)[source]

Bases: object

get_presence(resource: Optional[str] = None) PresenceInfo[source]
is_available() bool[source]
is_subscribed() bool[source]
update_presence(resource: str, presence_info: PresenceInfo)[source]
update_subscription(subscription: str, ask: str)[source]
exception spade.presence.ContactNotFound[source]

Bases: Exception

class spade.presence.PresenceInfo(presence_type: PresenceType, show: PresenceShow, status: Optional[str] = '', priority: int = 0)[source]

Bases: object

is_available() bool[source]
class spade.presence.PresenceManager(agent, approve_all: bool = False)[source]

Bases: object

approve_subscription(jid: str)[source]
get_contact(jid: Union[str, JID]) Contact[source]
get_contact_presence(jid: Union[str, JID], resource: Optional[str] = None) PresenceInfo[source]
get_contacts() Dict[str, Contact][source]
get_presence() PresenceInfo[source]
get_priority() int[source]
get_show() PresenceShow[source]
get_status() Optional[str][source]
handle_presence(presence: Presence)[source]
handle_roster_update(event)[source]

Executed when the roster is received or updated.

handle_subscription(presence: Presence)[source]
is_available() bool[source]
on_available(peer_jid: str, presence_info: PresenceInfo, last_presence: Optional[PresenceInfo])[source]
on_presence_received(presence: Presence)[source]
on_subscribe(peer_jid: str)[source]
on_subscribed(peer_jid: str)[source]
on_unavailable(peer_jid: str, presence_info: PresenceInfo, last_presence: Optional[PresenceInfo])[source]
on_unsubscribe(peer_jid: str)[source]
on_unsubscribed(peer_jid: str)[source]
set_available()[source]
set_presence(presence_type: PresenceType = PresenceType.AVAILABLE, show: PresenceShow = PresenceShow.CHAT, status: Optional[str] = '', priority: int = 0)[source]
set_unavailable()[source]
subscribe(jid: str)[source]
subscribed(jid: str)[source]
unsubscribe(jid: str)[source]
unsubscribed(jid: str)[source]
exception spade.presence.PresenceNotFound[source]

Bases: Exception

class spade.presence.PresenceShow(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

AWAY = 'away'
CHAT = 'chat'
DND = 'dnd'
EXTENDED_AWAY = 'xa'
NONE = 'none'
class spade.presence.PresenceType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

AVAILABLE = 'available'
ERROR = 'error'
PROBE = 'probe'
SUBSCRIBE = 'subscribe'
SUBSCRIBED = 'subscribed'
UNAVAILABLE = 'unavailable'
UNSUBSCRIBE = 'unsubscribe'
UNSUBSCRIBED = 'unsubscribed'

spade.template module

class spade.template.ANDTemplate(expr1, expr2)[source]

Bases: BaseTemplate

match(message)[source]
class spade.template.BaseTemplate[source]

Bases: object

Template operators

class spade.template.NOTTemplate(expr)[source]

Bases: BaseTemplate

match(message)[source]
class spade.template.ORTemplate(expr1, expr2)[source]

Bases: BaseTemplate

match(message)[source]
class spade.template.Template(to: Optional[str] = None, sender: Optional[str] = None, body: Optional[str] = None, thread: Optional[str] = None, metadata: Optional[Dict[str, str]] = None)[source]

Bases: BaseTemplate, MessageBase

Template for message matching

class spade.template.XORTemplate(expr1, expr2)[source]

Bases: BaseTemplate

match(message)[source]

spade.trace module

class spade.trace.TraceStore(size: int)[source]

Bases: object

Stores and allows queries about events.

all(limit: Optional[int] = None) List[Message][source]

Returns all the events, until a limit if defined

Args:

limit (int, optional): the max length of the events to return (Default value = None)

Returns:

list: a list of events

append(event: Message, category: Optional[str] = None) None[source]

Adds a new event to the trace store. The event may hava a category

Args:

event (spade.message.Message): the event to be stored category (str, optional): a category to classify the event (Default value = None)

filter(limit: Optional[int] = None, to: Optional[str] = None, category: Optional[str] = None) List[Message][source]

Returns the events that match the filters

Args:

limit (int, optional): the max length of the events to return (Default value = None) to (str, optional): only events that have been sent or received by ‘to’ (Default value = None) category (str, optional): only events belonging to the category (Default value = None)

Returns:

list: a list of filtered events

len() int[source]

Length of the store

Returns:

int: the size of the trace store

received(limit: Optional[int] = None) List[Message][source]

Returns all the events that have been received (excluding sent events), until a limit if defined

Args:

limit (int, optional): the max length of the events to return (Default value = None)

Returns:

list: a list of received events

reset() None[source]

Resets the trace store

spade.web module

class spade.web.WebApp(agent)[source]

Bases: object

Module to handle agent’s web interface

add_get(path: str, controller: Coroutine, template: str, raw: Optional[bool] = False) None[source]

Setup a route of type GET

Args:

path (str): URL to listen to controller (coroutine): the coroutine to handle the request template (str): the template to render the response or None if it is a JSON response raw (bool): indicates if post-processing (jinja, json, etc) is needed or not

add_menu_entry(name: str, url: str, icon='fa fa-circle') None[source]

Adds a new entry to the menu.

Args:

name (str): name of the entry url (str): url to be redirected to icon (str): icon to be displayed (Default value = “fa fa-circle”)

add_post(path: str, controller: Coroutine, template: str, raw: Optional[bool] = False) None[source]

Setup a route of type POST

Args:

path (str): URL to listen to controller (coroutine): the coroutine to handle the request template (str): the template to render the response or None if it is a JSON response raw (bool): indicates if post-processing (jinja, json, etc) is needed or not

add_template_path(templates_path)[source]
async agent_processor(request)[source]
find_behaviour(behaviour_str: str) Optional[Type[CyclicBehaviour]][source]
async get_agent(request)[source]
async get_behaviour(request)[source]
async get_messages(request)[source]
async index(request)[source]
is_started() bool[source]
async kill_behaviour(request)[source]
async send_agent(request)[source]
setup_routes() None[source]
start(hostname: Optional[str] = None, port: Optional[int] = None, templates_path: Optional[str] = None)[source]

Starts the web interface.

Args:

hostname (str, optional): host name to listen from. (Default value = None) port (int, optional): port to listen from. (Default value = None) templates_path (str, optional): path to look for templates. (Default value = None)

async stop_agent(request)[source]
async stop_now(request)[source]
static timeago(date)[source]
async unsubscribe_agent(request)[source]
async spade.web.start_server_in_loop(runner: AppRunner, hostname: str, port: int, agent)[source]

Listens to http requests and sends them to the webapp.

Args:

runner (AppRunner): AppRunner to process the http requests hostname (str): host name to listen from. port (int): port to listen from. agent (spade.agent.Agent): agent that owns the web app.

spade.web.unused_port(hostname: str) None[source]

Return a port that is unused on the current host.

spade.xmpp_client module

exception spade.xmpp_client.RegistrationException[source]

Bases: Exception

class spade.xmpp_client.XMPPClient(jid, password, verify_security, auto_register)[source]

Bases: ClientXMPP

async register(event)[source]
session_start(event)[source]

Module contents