scratchattach package

Submodules

scratchattach.cloud

scratchattach.eventhandlers

scratchattach.eventhandlers._base

class scratchattach.eventhandlers._base.BaseEventHandler[source]

Bases: ABC

__init__()[source]
_abc_impl = <_abc._abc_data object>
_events: defaultdict[str, list[Callable]]
_threaded_events: defaultdict[str, list[Callable]]
abstractmethod _updater()[source]
call_event(event_name, args: list = [])[source]
event(function=None, *, thread=False)[source]

Decorator function. Adds an event.

pause()[source]

Pauses the event handler.

resume()[source]

Resumes the event handler.

start(*, thread=True, ignore_exceptions=True)[source]

Starts the event handler.

Keyword Arguments:
  • thread (bool) – Whether the event handler should be run in a thread.

  • ignore_exceptions (bool) – Whether to catch exceptions that happen in individual events

stop()[source]

Permanently stops the event handler.

scratchattach.eventhandlers.cloud_events

scratchattach.eventhandlers.cloud_recorder

scratchattach.eventhandlers.cloud_requests

scratchattach.eventhandlers.cloud_server

scratchattach.eventhandlers.cloud_storage

scratchattach.eventhandlers.combine

class scratchattach.eventhandlers.combine.MultiEventHandler(*handlers)[source]

Bases: object

__init__(*handlers)[source]
event(function, *args, **kwargs)[source]
pause(*args, **kwargs)[source]
request(function, *args, **kwargs)[source]
resume(*args, **kwargs)[source]
start(*args, **kwargs)[source]
stop(*args, **kwargs)[source]

scratchattach.eventhandlers.filterbot

FilterBot class

class scratchattach.eventhandlers.filterbot.Filterbot(user, *, log_deletions=True)[source]

Bases: MessageEvents

__init__(user, *, log_deletions=True)[source]
_abc_impl = <_abc._abc_data object>
add_ads_filter()[source]
add_f4f_filter()[source]
add_filter(filter_obj)[source]
add_genalpha_nonsense_filter()[source]
add_spam_filter()[source]
on_message(message)[source]
class scratchattach.eventhandlers.filterbot.HardFilter(filter_name='UntitledFilter', *, equals=None, contains=None, author_name=None, project_id=None, profile=None, case_sensitive=False)[source]

Bases: object

__init__(filter_name='UntitledFilter', *, equals=None, contains=None, author_name=None, project_id=None, profile=None, case_sensitive=False)[source]
apply(content, author_name, source_id)[source]
class scratchattach.eventhandlers.filterbot.SoftFilter(score: float, filter_name='UntitledFilter', *, equals=None, contains=None, author_name=None, project_id=None, profile=None, case_sensitive=False)[source]

Bases: HardFilter

__init__(score: float, filter_name='UntitledFilter', *, equals=None, contains=None, author_name=None, project_id=None, profile=None, case_sensitive=False)[source]
class scratchattach.eventhandlers.filterbot.SpamFilter(filter_name='UntitledFilter', *, equals=None, contains=None, author_name=None, project_id=None, profile=None, case_sensitive=False)[source]

Bases: HardFilter

__init__(filter_name='UntitledFilter', *, equals=None, contains=None, author_name=None, project_id=None, profile=None, case_sensitive=False)[source]
apply(content, author_name, source_id)[source]

scratchattach.eventhandlers.message_events

MessageEvents class

class scratchattach.eventhandlers.message_events.MessageEvents(user, *, update_interval=2)[source]

Bases: BaseEventHandler

Class that calls events when you receive messages on your Scratch account. Data fetched from Scratch’s API.

__init__(user, *, update_interval=2)[source]
_abc_impl = <_abc._abc_data object>
_updater()[source]

A process that listens for cloud activity and executes events on cloud activity

scratchattach.other

scratchattach.site

scratchattach.site._base

class scratchattach.site._base.BaseSiteComponent[source]

Bases: ABC, Generic[D]

_abc_impl = <_abc._abc_data object>
_assert_auth()[source]
_cookies: dict[str, str]
_headers: dict[str, str]
_make_linked_object(identificator_id, identificator, Class: type[C], NotFoundException) C[source]

Internal function for making a linked object (authentication kept) based on an identificator (like a project id or username) Class must inherit from BaseSiteComponent

_make_request(method: HTTPMethod | str, url: str, *, cookies: dict[str, str] | None = None, headers: dict[str, str] | None = None, params: dict[str, str] | None = None, data: dict[str, str] | str | None = None, json: Any | None = None) CARequest[source]
_session: session.Session | None
abstractmethod _update_from_dict(data: D) bool[source]

Parses the API response that is fetched in the update-method. Class specific, must be overridden in classes inheriting from this one.

oa_http_session: m_requests.OAHTTPSession | None = None
supply_data_dict(data: D) bool[source]
update()[source]

Updates the attributes of the object by performing an API response. Returns True if the update was successful.

update_api: str
update_function(params=None, **kwargs)

Internal function run on update. Function is a method of the ‘requests’ module/class

updated() Self[source]

scratchattach.site.activity

scratchattach.site.backpack_asset

class scratchattach.site.backpack_asset.BackpackAsset(**entries)[source]

Bases: BaseSiteComponent

Represents an asset from the backpack.

Attributes:

.id:

.type:

The asset type (costume, script etc.)

.mime:

The format in which the content of the backpack asset is saved

.name:

The name of the backpack asset

.filename:

Filename of the file containing the content of the backpack asset

.thumbnail_url:

Link that leads to the asset’s thumbnail (the image shown in the backpack UI)

.download_url:

Link that leads to a file containing the content of the backpack asset

__init__(**entries)[source]
_abc_impl = <_abc._abc_data object>
property _data_bytes: bytes
_update_from_dict(data) bool[source]

Parses the API response that is fetched in the update-method. Class specific, must be overridden in classes inheriting from this one.

property data: dict | list | int | None | str | bytes | float
delete()[source]
download(*, fp: str = '')[source]

Downloads the asset content to the given directory. The given filename is equal to the value saved in the .filename attribute.

Parameters:

fp (str) – The path of the directory the file will be saved in.

property file_ext
property is_json
update()[source]

Updates the attributes of the object by performing an API response. Returns True if the update was successful.

scratchattach.site.cloud_activity

scratchattach.site.comment

scratchattach.site.forum

scratchattach.site.project

scratchattach.site.session

scratchattach.site.studio

scratchattach.site.user

scratchattach.site.classroom

scratchattach.utils

scratchattach.utils.commons

v2 ready: Common functions used by various internal modules

class scratchattach.utils.commons.LockEvent[source]

Bases: object

Can be waited on and triggered. Not to be confused with threading.Event, which has to be reset.

__init__()[source]
_access_locks: allocate_lock
_event: Event
_locks: list[allocate_lock]
on() allocate_lock[source]

Return a lock that will unlock once the event takes place. Return value has to be waited on to wait for the event.

trigger()[source]

Trigger all threads waiting on this event to continue.

wait(blocking: bool = True, timeout: int | float | None = None) bool[source]

Wait for the event.

scratchattach.utils.commons._get_object(identificator_name, identificator, __class: type[C], NotFoundException, session=None) C[source]
scratchattach.utils.commons.api_iterative(url: str, *, limit: int, offset: int, max_req_limit: int = 40, add_params: str = '', _headers: dict | None = None, cookies: dict | None = None)[source]

Function for getting data from one of Scratch’s iterative JSON API endpoints (like /users/<user>/followers, or /users/<user>/projects)

scratchattach.utils.commons.api_iterative_data(fetch_func: Callable[[int, int], list], limit: int, offset: int, max_req_limit: int = 40, unpack: bool = True) list[source]

Iteratively gets data by calling fetch_func with a moving offset and a limit. Once fetch_func returns None, the retrieval is completed.

scratchattach.utils.commons.b62_decode(s: str)[source]
scratchattach.utils.commons.get_class_sort_mode(mode: str) tuple[str, str][source]

Returns the sort mode for the given mode for classes only

scratchattach.utils.commons.parse_object_list(raw, __class: type[C], session=None, primary_key='id') list[C][source]
scratchattach.utils.commons.webscrape_count(raw: str, text_before: str, text_after: str, cls: type[I]) I[source]
scratchattach.utils.commons.webscrape_count(raw: str, text_before: str, text_after: str) int

scratchattach.utils.encoder

class scratchattach.utils.encoder.Encoding[source]

Bases: object

Class that contains tools for encoding / decoding strings. The strings encoded / decoded with these functions can be decoded / encoded with Scratch using this sprite: https://scratch3-assets.1tim.repl.co/Encoder.sprite3

static decode(inp)[source]
Parameters:

inp (str) – The encoded input.

Returns:

The decoded output.

Return type:

str

static encode(inp)[source]
Parameters:

inp (str) – The decoded input.

Returns:

The encoded output.

Return type:

str

static replace_char(old_char, new_char)[source]

Replaces a character in the list that the encoder uses to encode / decode values. You can access this list using scratchattach.encoder.letters

scratchattach.utils.exceptions

exception scratchattach.utils.exceptions.APIError[source]

Bases: Exception

For API errors that can’t be classified into one of the above errors

exception scratchattach.utils.exceptions.BadBlockShape[source]

Bases: Exception

Raised when the block shape cannot allow for the operation

exception scratchattach.utils.exceptions.BadRequest[source]

Bases: Exception

Raised when the Scratch API responds with a “Bad Request” error message. This can have various reasons. Make sure all provided arguments are valid.

exception scratchattach.utils.exceptions.BadScript[source]

Bases: Exception

Raised when the block script cannot allow for the operation

exception scratchattach.utils.exceptions.BadVLBPrimitiveError[source]

Bases: Exception

Raised when a Primitive claiming to be a variable/list/broadcast actually isn’t

exception scratchattach.utils.exceptions.ClassroomAuthenticationWarning[source]

Bases: GetAuthenticationWarning

Warns you to use session.connect_classroom or session.connect_classroom_from_token instead of classroom.get_classroom for actions that require authentication.

exception scratchattach.utils.exceptions.ClassroomNotFound[source]

Bases: Exception

Raised when a non-existent Classroom is requested.

exception scratchattach.utils.exceptions.CloudConnectionError[source]

Bases: Exception

Raised when connecting to Scratch’s cloud server fails. This can have various reasons.

exception scratchattach.utils.exceptions.CommentNotFound[source]

Bases: Exception

exception scratchattach.utils.exceptions.CommentPostFailure[source]

Bases: Exception

Raised when a comment fails to post. This can have various reasons.

exception scratchattach.utils.exceptions.FetchError[source]

Bases: Exception

Raised when getting information from the Scratch API fails. This can have various reasons. Make sure all provided arguments are valid.

exception scratchattach.utils.exceptions.ForumContentNotFound[source]

Bases: Exception

Raised when a non-existent forum topic / post is requested.

exception scratchattach.utils.exceptions.GetAuthenticationWarning[source]

Bases: UserWarning

All authentication warnings.

exception scratchattach.utils.exceptions.InvalidCloudValue[source]

Bases: Exception

Raised when a cloud variable is set to an invalid value.

exception scratchattach.utils.exceptions.InvalidDecodeInput[source]

Bases: Exception

Raised when the built-in decoder scratchattach.encoder.Encoding.decode() receives an invalid input.

exception scratchattach.utils.exceptions.InvalidLanguage[source]

Bases: Exception

Raised when an invalid language/language code/language object is provided, for TTS or Translate

exception scratchattach.utils.exceptions.InvalidStageCount[source]

Bases: Exception

Raised when a project has too many or too few Stage sprites

exception scratchattach.utils.exceptions.InvalidTTSGender[source]

Bases: Exception

Raised when an invalid TTS gender is provided.

exception scratchattach.utils.exceptions.InvalidUpdateWarning[source]

Bases: UserWarning

Warns you that something cannot be updated.

exception scratchattach.utils.exceptions.InvalidVLBName[source]

Bases: Exception

Raised when an invalid VLB name is provided (not variable, list or broadcast)

exception scratchattach.utils.exceptions.LoginDataWarning[source]

Bases: UserWarning

Warns you not to accidentally share your login data.

exception scratchattach.utils.exceptions.LoginFailure[source]

Bases: Exception

Raised when the Scratch server doesn’t respond with a session id.

This could be caused by an invalid username / password. Another cause could be that your IP address was banned from logging in to Scratch. If you’re using an online IDE (like replit), try running the code on your computer.

exception scratchattach.utils.exceptions.ProjectAuthenticationWarning[source]

Bases: GetAuthenticationWarning

Warns you to use session.connect_project instead of project.get_project for actions that require authentication.

exception scratchattach.utils.exceptions.ProjectNotFound[source]

Bases: Exception

Raised when a non-existent project is requested.

exception scratchattach.utils.exceptions.RateLimitedError[source]

Bases: Exception

Indicates a ratelimit enforced by scratchattach

exception scratchattach.utils.exceptions.RequestNotFound[source]

Bases: Exception

Cloud Requests: Raised when a non-existent cloud request is edited using scratchattach.cloud_requests.CloudRequests.edit_request().

exception scratchattach.utils.exceptions.Response429[source]

Bases: Exception

Raised when the Scratch API responds with a 429 error. This means that your network was ratelimited or blocked by Scratch. If you’re using an online IDE (like replit.com), try running the code on your computer.

exception scratchattach.utils.exceptions.ScrapeError[source]

Bases: Exception

Raised when something goes wrong while web-scraping a page with bs4.

exception scratchattach.utils.exceptions.StudioAuthenticationWarning[source]

Bases: GetAuthenticationWarning

Warns you to use session.connect_studio instead of studio.get_studio for actions that require authentication.

exception scratchattach.utils.exceptions.StudioNotFound[source]

Bases: Exception

Raised when a non-existent studio is requested.

exception scratchattach.utils.exceptions.Unauthenticated(message='')[source]

Bases: Exception

Raised when a method that requires a login / session is called on an object that wasn’t created with a session.

If you create Project, Studio, or User objects using scratchattach.get_project(), scratchattach.get_studio(), or scratchattach.get_user(), they cannot be used for actions that require authentication. Instead, use the following methods to ensure the objects are connected to an authenticated session:

  • scratchattach.Session.connect_project()

  • scratchattach.Session.connect_user()

  • scratchattach.Session.connect_studio()

This also applies to cloud variables, forum topics, and forum posts.

__init__(message='')[source]
exception scratchattach.utils.exceptions.Unauthorized(message='')[source]

Bases: Exception

Raised when an action is performed that the user associated with the session that the object was created with is not allowed to do.

Example: Changing the “about me” of other users will raise this error.

__init__(message='')[source]
exception scratchattach.utils.exceptions.UnclosedJSONError[source]

Bases: Exception

Raised when a JSON string is never closed.

exception scratchattach.utils.exceptions.UnlinkedVLB[source]

Bases: Exception

Raised when a Primitive cannot be linked to variable/list/broadcast because the provided ID does not have an associated variable/list/broadcast

exception scratchattach.utils.exceptions.UserAuthenticationWarning[source]

Bases: GetAuthenticationWarning

Warns you to use session.connect_user instead of user.get_user for actions that require authentication.

exception scratchattach.utils.exceptions.UserNotFound[source]

Bases: Exception

Raised when a non-existent user is requested.

exception scratchattach.utils.exceptions.WebsocketServerError[source]

Bases: Exception

Raised when the self-hosted cloud websocket server fails to start.

exception scratchattach.utils.exceptions.XTokenError[source]

Bases: Exception

Raised when an action can’t be performed because there is no XToken available.

This error can occur if the xtoken couldn’t be fetched when the session was created. Some actions (like loving projects) require providing this token.

scratchattach.utils.requests

class scratchattach.utils.requests.AnyHTTPResponse[source]

Bases: ABC

_abc_impl = <_abc._abc_data object>
content: bytes
headers: dict[str, str]
json() Any[source]
request_method: HTTPMethod
status_code: int
text: str
class scratchattach.utils.requests.AsyncRequests[source]

Bases: OAHTTPSession

_abc_impl = <_abc._abc_data object>
async async_request(method, url, *, cookies=None, headers=None, params=None, data=None, json=None)[source]
client_session: ClientSession
sync_request(method, url, *, cookies=None, headers=None, params=None, data=None, json=None)[source]
class scratchattach.utils.requests.HTTPMethod(value)[source]

Bases: Enum

DELETE = 4
GET = 1
HEAD = 5
OPTIONS = 6
PATCH = 7
POST = 2
PUT = 3
TRACE = 8
classmethod of(name: str) HTTPMethod[source]
class scratchattach.utils.requests.HTTPResponse(*, request_method: 'HTTPMethod', status_code: 'int', content: 'bytes', text: 'str', headers: 'dict[str, str]')[source]

Bases: AnyHTTPResponse

__init__(*, request_method: HTTPMethod, status_code: int, content: bytes, text: str, headers: dict[str, str]) None
_abc_impl = <_abc._abc_data object>
content: bytes
headers: dict[str, str]
request_method: HTTPMethod
status_code: int
text: str
class scratchattach.utils.requests.OAHTTPSession[source]

Bases: ABC

_abc_impl = <_abc._abc_data object>
abstractmethod async async_request(method: HTTPMethod, url: str, *, cookies: dict[str, str] | None = None, headers: dict[str, str] | None = None, params: dict[str, str] | None = None, data: dict[str, str] | str | None = None, json: Any | None = None) AnyHTTPResponse[source]
check_response(r: AnyHTTPResponse)[source]
error_handling: bool = True
no_error_handling() Iterator[None][source]
request(method: HTTPMethod | str, url: str, *, cookies: dict[str, str] | None = None, headers: dict[str, str] | None = None, params: dict[str, str] | None = None, data: dict[str, str] | str | None = None, json: Any | None = None) CARequest[source]
abstractmethod sync_request(method: HTTPMethod, url: str, *, cookies: dict[str, str] | None = None, headers: dict[str, str] | None = None, params: dict[str, str] | None = None, data: dict[str, str] | str | None = None, json: Any | None = None) AnyHTTPResponse[source]
yes_error_handling() Iterator[None][source]
class scratchattach.utils.requests.Requests[source]

Bases: Session

Centralized HTTP request handler (for better error handling and proxies)

check_response(r: Response)[source]
delete(*args, **kwargs)[source]

Sends a DELETE request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

error_handling: bool = True
get(*args, **kwargs)[source]

Sends a GET request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

no_error_handling() Iterator[None][source]
post(*args, **kwargs)[source]

Sends a POST request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • json – (optional) json to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

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

Sends a PUT request. Returns Response object.

Parameters:
  • url – URL for the new Request object.

  • data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.

  • **kwargs – Optional arguments that request takes.

Return type:

requests.Response

yes_error_handling() Iterator[None][source]
class scratchattach.utils.requests.SyncRequests[source]

Bases: OAHTTPSession

_abc_impl = <_abc._abc_data object>
async async_request(method, url, *, cookies=None, headers=None, params=None, data=None, json=None)[source]
sync_request(method, url, *, cookies=None, headers=None, params=None, data=None, json=None)[source]