scratchcloud docs
scratchcloud.client module
- class scratchcloud.client.CloudChange(name: str, value: str, id: int, previous_value: str = None, sender: 'CloudClient' | str = None)
Bases:
object
This is a class that stores cloud data received from
client.CloudClient
.- Parameters
name (str) – the cloud variable’s name excluding “☁️ “.
value (str) – the cloud variable’s value. If an decoder is specified in
client.CloudClient
this value will be decoded.id (int) – the library-assigned cloud variable’s id. This value will start at 1 for the first cloud variable received and increment for each new change.
previous_value (str, optional) – the cloud variable’s previous value. Never encoded. None if not found.
sender (
client.CloudClient
| str) – the cloud variable’s sender. If sent from the client, will be theclient.CloudClient
object. None otherwise. This value may be changed by extensions.
- class scratchcloud.client.CloudClient(username: str, project_id: str, max_reconnect: Optional[int] = None, reconnect_cooldown: int = 10, encoder: Optional[Callable[[str], str]] = None, decoder: Optional[Callable[[str], str]] = None, disconnect_messages: bool = False, max_cache_length: int = 1000, event_loop=<_UnixSelectorEventLoop running=False closed=False debug=False>)
Bases:
object
Represents the connection with the scratch websocket server.
- Parameters
username (str) – the username of the account that will connect to scratch.
project_id (str) – the project id that will be connected to.
max_reconnect (int, optional) – the maximum number of reconnects by the client. If reconnecting fails this number of times, the error that caused the reconnect will be raised. Defaults to None, which means always reconnect.
reconnect_cooldown (int, optional) – the time in seconds between reconnecting. Defaults to 10. Low values may result in account ratelimiting and bans.
encoder (Callable[[str], str], optional) – a callable function that is used to encode all sent cloud data. The function must return a string of digits and take 1 argument.
decoder (Callable[[str], str], optional) – a callable function that is used to decode all received cloud data. The function must take 1 argument.
disconnect_messages (bool) – a boolean that when true, prints the cause of disconnects. defaults to False
max_cache_length (int) – the maximum length of saved RawCloudChange objects. defaults to 1000
event_loop (AbstractEventLoop) – the event loop that the CloudClient will use. defaults to asyncio.get_event_loop()
Attributes:
- http_session
aiohttp.ClientSession
The HTTP session used for logging into scratch
- http_session
- cookies
dict
The cookies gathered from the HTTP session
- cookies
- headers
dict
The headers gathered from the HTTP session
- headers
- logged_in
bool
If client is logged in
- logged_in
- ws
websockets.client
The websocket connection
- ws
- connected
bool
If the client is connected to the websocket server
- connected
- cloud_variables
dict
The current values of the cloud variables
- cloud_variables
- cloud_cache
list[RawCloudChange]
A list of all of the cloud variable changed since the client has been active. Newer cloud changes will be later in the list
- cloud_cache
- cloud_events
dict
Internal registers for cloud events
- cloud_events
- cloud_event_errors
dict
Internal registers for cloud event errors
- cloud_event_errors
- on_message_registered
bool
If the on_messsage event is registered
- on_message_registered
Methods:
- add_to_cloud_cache(item)
Adds an item to the cloud cache. If the cloud cache is too long, delete the least recent item to be added.
Internal.
- Parameters
item – the item that will be added
- async close()
A coroutine that closes self.http_session.
Internal.
- cloud_event(variable_name: str)
A decorator that registers cloud events. Cloud events call specific functions whenever a specific variable changes. Using them takes away the user overhead of parsing each CloudChange object.
- Parameters
variable_name – The variable name that will be registered
variable_name – str
- Raises
KeyError – If the cloud variable has already been registered
Example Usage:
@client.cloud_event('CloudVariableName') async def cloud_variable_name_changed(cloud: CloudChange): print(f'The variable CloudVariableName changed to {cloud.value}!')
- cloud_event_error(variable_name: str)
A decorator that registers cloud error events. This coroutine is called whenever an error occurs in
cloud_event()
for the same variable name.- Parameters
variable_name – The variable name that will be registered
variable_name – str
- Raises
KeyError – If the cloud variable has already been registered
Example Usage:
@client.cloud_event('myvar') async def myvar_changed(cloud: CloudChange): print(f'2 divided by myvar is {2 / cloud.value}!') @client.cloud_event_error('myvar') async def myvar_error(cloud: CloudChange, error: Exception): if isinstance(error, ZeroDivisionError): print('Somebody entered a zero in myvar!)
- async cloud_event_task(cloud: scratchcloud.client.CloudChange, func_name: str, error_func_name: Optional[str] = None)
A cloud event task. Calls a function when an internally registered cloud variable changes.
Internal.
- async connect_ws()
A coroutine that establishes a websocket connection with project_id. Assumes that the http session has already been created.
Internal.
- event(func)
A decorator that registers on_message, on_connect, and, on_disconnect events.
- Parameters
func (Callable) – A function that will be registered. Must have an identical name to an event
The on_message event is called whenever the client recieves a CloudChange object
The on_connect event is called whenever the client connects to the cloud
The on_disconnect event is called whenever the client disconnects from the cloud
Example Usage:
@client.event async def on_message(): print('We got a new message!') @client.event async def on_connect(): print('Client connected to scratch!') @client.event async def on_disconnect(): print('Client disconnected from scratch!')
- async login(token: str | scratchcloud.client.LoginCookie) None
A coroutine that sets http_session, cookies, and headers.
- Parameters
token (str) – the password of the account that will be used to establish a connection
Internal.
- async on_connect()
The default value for on_connect.
Example Usage:
@client.event async def on_connect(): print('Connected to Scratch :D')
- async on_connect_task()
A coroutine that calls on_connect.
Internal.
- async on_disconnect()
The default value for on_disconnect.
Example Usage:
@client.event async def on_disconnect(): print('Disconnected from Scratch D:')
- async on_disconnect_task()
A coroutine that calls on_disconnect.
Internal.
- async on_message(cloud: scratchcloud.client.CloudChange)
The default value for on_message.
- Parameters
cloud (
client.CloudChange
) – An object that contains Cloud information
Example Usage:
@client.event async def on_message(cloud: CloudChange): print(f'{cloud.name} changed to {cloud.value}!')
- async on_message_error(cloud: scratchcloud.client.CloudChange, error: Exception)
The default value for on_message_error. Called whenever an error occurs in
on_message()
.- Parameters
cloud (
client.CloudChange
) – A cloudchange object that stores data from on_recverror (
Exception
) – The exception raised in on_message
Example Usage:
@client.event async def on_message(cloud: CloudChange): if cloud.value.isdigit(): val = int(cloud.value) print(100 / val) @client.event async def on_message_error(cloud: CloudChange, error: Exception): if isinstance(error, ZeroDivisionError): print('Somebody entered a zero!)
- async on_message_event_task(cloud: scratchcloud.client.CloudChange)
The message task. Called whenever a cloud variable changes. If the on_message event is linked, calls on_message
Internal.
- async on_recv()
A coroutine that receives data from the cloud connection and calls event functions. Creates CloudChange objects, manages the cache, and handles events and cloud_events.
Internal.
- parse_raw_cloud(raw_data: str) dict
A method that parses data received directly from the websocket
- Parameters
raw_data (str) – The data to be parsed
- Return type
dict
Internal.
- raise_exc_callback(task: _asyncio.Task)
A exception callback.
Internal.
- run(token: str | scratchcloud.client.LoginCookie)
A blocking function to run the client with library reconnecting. Basically runs start repeatedly and disconnects properly after a KeyboardInterrupt. Also handles common connection errors.
- Parameters
token – the password or a LoginCookie object for the account that will be used to establish a connection
- Return type
None
Example Usage:
client = CloudClient('username', '123') client.run('password')
Cookie Example Usage:
login_cookie = LoginCookie( csrftoken = 'abc123', sessionid = 'def456' ) client = CloudClient('username', '123') client.run(login_cookie)
- async run_client()
A coroutine that calls the on_connect_task and starts receving data from the websocket. Assumes that the websocket connection has already been established.
Internal.
- async set_cloud(name: str, value: str, encode: bool = True)
A coroutine that sets cloud variables through the websocket connection. This must be called from another coroutine.
- Parameters
name (str) – The name of the cloud variable that will be set. This value must not include “☁️ “. A cloud variable named “☁️ MyVariable” should be refrenced here as “MyVariable”.
value (str) – The value the cloud variable will be set to.
encode (bool) – Controls whether, if the client has an encoder, the encoder be used. Defaults to True
- Raises
TypeError – If the (possibly encoded) value is not digits
SizeError – If the value is larger than 256 digits
Example Usage:
@client.event async def on_connect(): await client.set_cloud('MyCloudVariableName', '200')
Note that above client.set_cloud is called from the on_connect() coroutine
- async start(token: str | scratchcloud.client.LoginCookie)
A coroutine that starts a client.
Calls all functions needed to connect to scratch in chronological order. Closes self, logs in, connects to the websocket, performs a handshake, and finally, runs the client.
This can be used in place of
run()
if you want more control over the event loop.- Parameters
token (LoginCookie) – the password of the account that will be used to establish a connection
token – the cookie for the account that will be used to establish a connection.
Internal.
- async ws_handshake()
A coroutine that performs a handshake with the websocket connection.
- Raises
errors.MissingCloudVariable – If no cloud variables are found in the project
Internal.
- async ws_send(data: dict)
A coroutine that sends a dictionary to the websocket connection. Assumes that the websocket connection has already been established.
Internal.
- class scratchcloud.client.LoginCookie(csrftoken: str, sessionid: str)
Bases:
object
This is a class that stores login cookie data. It is used by client.CloudClient.
- Parameters
csrftoken (str) – the user’s CSRFToken.
sessionid (str) – the user’s ScratchSessionID.
What is this?
Scratch occasionally blocks new logins from online IDEs. This is most common with the popular IDE, Repl.it. When logging in to scratch normally, Scratch creates a “Session ID” and “CSRF Token” and uses them for your cridentials. You can insert these cridentials directly to scratchcloud to bypass the login process. Anyone with these cridentials can do anything on your account, so make sure to keep them safe!
The LoginCookie object can be used in place of a password for the
client.CloudClient.run()
method.Cookie Example Usage:
- to_cookie_dict() dict
A method that returns the cookie dictionary in a format that scratch likes.
- Return type
dict
- class scratchcloud.client.RawCloudChange(name: str, value: str, id: int, previous_value: str = None, sender: 'CloudClient' | str = None)
Bases:
scratchcloud.client.CloudChange
A subclass of
client.CloudChange
. Value attribute wil never be encoded. Used in client.cloud_cache
scratchcloud.errors module
- exception scratchcloud.errors.DecodeError
Bases:
scratchcloud.errors.ScratchCloudException
Decode Error. Raised when there is an issue with decoding.
- exception scratchcloud.errors.EncodeError
Bases:
scratchcloud.errors.ScratchCloudException
Encode Error. Raised when there is an issue with encoding.
- exception scratchcloud.errors.MissingCloudVariable
Bases:
scratchcloud.errors.ScratchCloudException
Missing Cloud Variable. Raised when specified cloud variables are missing, or when a project doesn’t have cloud variables.
- exception scratchcloud.errors.NotFoundError
Bases:
scratchcloud.errors.ScratchCloudException
Not Found Error. Raised when data from the API is not found.
- exception scratchcloud.errors.ScratchCloudException
Bases:
Exception
Base ScratchCloud exception. Use this to catch all exceptions raised by this library.
- exception scratchcloud.errors.SizeError
Bases:
scratchcloud.errors.ScratchCloudException
Size Error. Raised when a cloud variable payload is too large.
- exception scratchcloud.errors.UnableToValidate
Bases:
scratchcloud.errors.ScratchCloudException
UnableToValidate. Raised when an issue occurs with username validation.