spade package

Submodules

spade.agent module

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

Bases: object

add_behaviour(behaviour: BehaviourType, template: Optional[spade.template.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)
avatar

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: an URL for the gravatar
dispatch(msg: spade.message.Message) → List[_asyncio.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[spade.behaviour.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
name

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[spade.behaviour.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: spade.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]
setup() → None[source]

Setup agent before startup. This coroutine may be overloaded.

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
stop() → None[source]

Stops this agent.

submit(coro: Coroutine) → _asyncio.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

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.

enqueue(message: spade.message.Message) → None[source]

Enqueues a message in the behaviour’s mailbox

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

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
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: spade.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
on_end() → None[source]

Coroutine called after the behaviour is done or killed.

on_start() → None[source]

Coroutine called before the behaviour is started.

receive(timeout: Optional[float] = None) → Optional[spade.message.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
run() → None[source]

Body of the behaviour. To be implemented by user.

send(msg: spade.message.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: spade.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: spade.behaviour.CyclicBehaviour

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

add_state(name: str, state: spade.behaviour.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) → spade.behaviour.State[source]
get_states() → Dict[str, spade.behaviour.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
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: spade.behaviour.CyclicBehaviour

This behaviour is only executed once

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

Bases: spade.behaviour.CyclicBehaviour

This behaviour is executed periodically with an interval

period

Get the period.

class spade.behaviour.State[source]

Bases: spade.behaviour.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: spade.behaviour.OneShotBehaviour

This behaviour is executed once at after specified datetime

spade.behaviour.now()

Returns new datetime object representing current time local to tz.

tz
Timezone object.

If no tz is specified, uses local timezone.

spade.container module

class spade.container.Container[source]

Bases: spade.container.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]
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: spade.message.MessageBase

make_reply() → spade.message.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() → aioxmpp.stanza.Message[source]

Returns an aioxmpp.stanza.Message built from the Message and prepared to be sent.

Returns:
aioxmpp.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

body

Get body of the message Returns:

str: the body of the message
classmethod from_node(node: aioxmpp.stanza.Message) → Type[spade.message.MessageBase][source]

Creates a new spade.message.Message from an aixoxmpp.stanza.Message

Args:
node (aioxmpp.stanza.Message): an aioxmpp 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)
id
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
sender

Get jid of the sender

Returns:
aioxmpp.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
thread

Get Thread of the message

Returns:
str: thread id
to

Gets the jid of the receiver.

Returns:
aioxmpp.JID: jid of the receiver

spade.presence module

exception spade.presence.ContactNotFound[source]

Bases: Exception

class spade.presence.PresenceManager(agent)[source]

Bases: object

approve(peer_jid: str) → None[source]

Approve a subscription request from jid

Args:
peer_jid (str): the JID to approve
get_contact(jid: aioxmpp.structs.JID) → Dict[source]

Returns a contact

Args:
jid (aioxmpp.JID): jid of the contact
Returns:
dict: the roster of contacts
get_contacts() → Dict[str, Dict][source]

Returns list of contacts

Returns:
dict: the roster of contacts
is_available() → bool[source]

Returns the available flag from the state

Returns:
bool: wether the agent is available or not
on_available(peer_jid: str, stanza: aioxmpp.stanza.Presence) → None[source]

Callback called when a contact becomes available. To be overloaded by user.

Args:
peer_jid (str): the JID of the agent that is available stanza (aioxmpp.Presence): The presence message containing type, show, priority and status values.
on_subscribe(peer_jid: str) → None[source]

Callback called when a subscribe query is received. To be overloaded by user.

Args:
peer_jid (str): the JID of the agent asking for subscription
on_subscribed(peer_jid: str) → None[source]

Callback called when a subscribed message is received. To be overloaded by user.

Args:
peer_jid (str): the JID of the agent that accepted subscription
on_unavailable(peer_jid: str, stanza: aioxmpp.stanza.Presence) → None[source]

Callback called when a contact becomes unavailable. To be overloaded by user.

Args:
peer_jid (str): the JID of the agent that is unavailable stanza (aioxmpp.Presence): The presence message containing type, show, priority and status values.
on_unsubscribe(peer_jid: str) → None[source]

Callback called when an unsubscribe query is received. To be overloaded by user.

Args:
peer_jid (str): the JID of the agent asking for unsubscription
on_unsubscribed(peer_jid: str) → None[source]

Callback called when an unsubscribed message is received. To be overloaded by user.

Args:
peer_jid (str): the JID of the agent that unsubscribed
priority

The currently set priority which is broadcast when the client connects and when the presence is re-emitted.

This attribute cannot be written. It does not reflect the actual presence seen by others. For example when the client is in fact offline, others will see unavailable presence no matter what is set here.

Returns:
int: the priority of the connection
set_available(show: Optional[<unknown>.PresenceShow] = <PresenceShow.NONE: None>)[source]

Sets the agent availability to True.

Args:
show (aioxmpp.PresenceShow, optional): the show state of the presence (Default value = PresenceShow.NONE)
set_presence(state: Optional[aioxmpp.structs.PresenceState] = None, status: Optional[str] = None, priority: Optional[int] = None)[source]

Change the presence broadcast by the client. If the client is currently connected, the new presence is broadcast immediately.

Args:
state(aioxmpp.PresenceState, optional): New presence state to broadcast (Default value = None) status(dict or str, optional): New status information to broadcast (Default value = None) priority (int, optional): New priority for the resource (Default value = None)
set_unavailable() → None[source]

Sets the agent availability to False.

state

The currently set presence state (as aioxmpp.PresenceState) which is broadcast when the client connects and when the presence is re-emitted.

This attribute cannot be written. It does not reflect the actual presence seen by others. For example when the client is in fact offline, others will see unavailable presence no matter what is set here.

Returns:
aioxmpp.PresenceState: the presence state of the agent
status

The currently set textual presence status which is broadcast when the client connects and when the presence is re-emitted.

This attribute cannot be written. It does not reflect the actual presence seen by others. For example when the client is in fact offline, others will see unavailable presence no matter what is set here.

Returns:
dict: a dict with the status in different languages (default key is None)
subscribe(peer_jid: str) → None[source]

Asks for subscription

Args:
peer_jid (str): the JID you ask for subscriptiion
unsubscribe(peer_jid: str) → None[source]

Asks for unsubscription

Args:
peer_jid (str): the JID you ask for unsubscriptiion

spade.template module

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

Bases: spade.template.BaseTemplate

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

Bases: object

Template operators

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

Bases: spade.template.BaseTemplate

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

Bases: spade.template.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: spade.template.BaseTemplate, spade.message.MessageBase

Template for message matching

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

Bases: spade.template.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[spade.message.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: spade.message.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[spade.message.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[spade.message.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
agent_processor(request)[source]
find_behaviour(behaviour_str: str) → Optional[Type[spade.behaviour.CyclicBehaviour]][source]
get_agent(request)[source]
get_behaviour(request)[source]
get_messages(request)[source]
index(request)[source]
is_started() → bool[source]
kill_behaviour(request)[source]
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)
stop_agent(request)[source]
stop_now(request)[source]
static timeago(date)[source]
unsubscribe_agent(request)[source]
spade.web.start_server_in_loop(runner: aiohttp.web_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.

Module contents