Package: scratch3
Scratchattach is a modern and object oriented library for the Scratch website.
Automate actions and interact with your Scratch projects through cloud variables.Some functions require logging in to Scratch.You also need to have the coding language Python installed on your computer.Download Python here if you don't have it:https://www.python.org/downloads/The project is maintained by TimMcCool:https://scratch.mit.edu/users/TimMcCool/InstallationTo install the library, run the following command in your command prompt
/ shell:pip install scratchattachORAdd this to your Python code:importosos.system("pip install scratchattach")Logging inscratch3.SessionLogging in with username / password:importscratchattachasscratch3session=scratch3.login("username","password")login()returns aSessionobject that saves your loginLogging in with a sessionId:importscratchattachasscratch3session=scratch3.Session("sessionId")Attributes:session.session_id#Returns the associated session idsession.xtokensession.email#Returns the email adress associated with the accountsession.new_scratcher#Returns True if the associated account is a New Scratchersession.mute_statussession.banned#Returns True if the associated account is bannedCloud variablesscratch3.CloudConnectionscratch3.TwCloudConnectionConnect to the Scratch cloud:With aSessionobject:conn=session.connect_cloud(project_id="project_id")Directly with a sessionId (cookie connect):conn=scratch3.CloudConnection(project_id="project_id",username="username",session_id="sessionId")Connect to the TurboWarp cloud:Does not require a session.conn=scratch3.TwCloudConnection(project_id="project_id",username="username",cloud_host="<wss://clouddata.turbowarp.org")Set a cloud var:New Scratchers can set Scratch cloud variables too.conn.set_var("variable","value")#the variable name is specifiedwithoutthecloudemojiGet a Scratch cloud var from the clouddata logs:Does not require a connection / session.value=scratch3.get_var("project_id","variable")variables=scratch3.get_cloud("project_id")#Returns a dict with all cloud var valueslogs=scratch3.get_cloud_logs("project_id")#Returns the cloud logs as listGet a TurboWarp cloud var from the websocket:(new in v0.4.7)Requires a connection to TurboWarp's cloud (aTwCloudConnectionobject).value=conn.get_var("variable")Encoding / Decodingscratch3.EncodingTo send text to your Scratch project, you can use the built in encoder.
To decode sent texts in Scratch, download this sprite and add it to your Scratch project:https://scratch3-assets.1tim.repl.co/Encoder.sprite3fromscratchattachimportEncodingEncoding.encode("input")#will return the encoded textEncoding.decode("encoded")#will decode an encoded textCloud eventsscratch3.CloudEventsscratch3.TwCloudEventsCloud events allow reacting to cloud events in real time. If a Scratcher
sets / creates / deletes a cloud var on the given project, an
event will be called.They do not require a session.How to use with Scratch:importscratchattachasscratch3events=scratch3.CloudEvents("project_id")@events.eventdefon_set(event):#Called when a cloud var is setprint(f"{event.user}set the variable{event.var}to the valuee{event.value}at{event.timestamp}")@events.eventdefon_del(event):print(f"{event.user}deleted variable{event.var}")@events.eventdefon_create(event):print(f"{event.user}created variable{event.var}")@events.event#Called when the event listener is readydefon_ready():print("Event listener ready!")events.start()#Make sure this is ALWAYS at the bottom of your Python file!How to use with TurboWarp:(new in v0.4.7)importscratchattachasscratch3events=scratch3.TwCloudEvents("project_id")...Cloud requestsscratch3.CloudRequestsCloud requests make it possible to access data like message counts, user
stats and more from Scratch projects. They use cloud variables to
transmit dataAdd Cloud requests to your Scratch project:Download this project file to your computer:https://scratch3-assets.1tim.repl.co/CloudRequests_Template.sb3Then, go to the Scratch website, create a new project and upload the project file from above.How to use:Copy this code to your Python editor:importscratchattachasscratch3session=scratch3.login("username","password")#replace with your dataconn=session.connect_cloud(project_id="project_id")#replace with your project idclient=scratch3.CloudRequests(conn,ignore_exceptions=True)@client.requestdefping():#called when client receives requestprint("Ping request received")return"pong"#sends back 'pong' to the Scratch project@client.eventdefon_ready():print("Request handler is ready")client.run()#Make sure this is ALWAYS at the bottom of your Python file!In theCloud Requestssprite, you will find this block:When active, it will send a "ping" request to the Python client. This will call theping()function. The data returned by the function will be sent back to the project.Notes:No length limitationfor the returned data! (If the response is too long to fit into one cloud var, it will be split to multiple cloud vars)It can handle multiple requests being sent at the same timeYou can freely choose the names of your requestsYou can also return listsExample 1: Script that loads your message countScratch code:Python code (add this to the code from above, but make sureclient.run()stays at the bottom of the file):@client.requestdefmessage_count(argument1):print(f"Message count requested for user{argument1}")user=scratch3.get_user(argument1)returnuser.message_count()Example 2: Script that loads someone's statsScratch code:Python code:@client.requestdeffoo(argument1):print(f"Data requested for user{argument1}")user=scratch3.get_user(argument1)stats=user.stats()return_data=[]return_data.append(f"Total loves:{stats['loves']}")return_data.append(f"Total favorites:{stats['favorites']}")return_data.append(f"Total views:{stats['views']}")returnreturn_dataMake sure to credit @TimMcCool on Scratch if you use the Scratch sprite!Uncredited use will automatically be reported to the Scratch Team.Usersscratch3.UserGet a user:user=session.connect_user("username")Get the user that you are logged in with:session.get_linked_user()You can also get users without logging in:user=scratch3.get_user("username")Attributes:user.join_dateuser.about_meuser.wiwo#Returns the user's 'What I'm working on' sectionuser.country#Returns the country from the user profileuser.icon_url#Returns the link to the user's pfp (90x90)user.id#Returns the id of the useruser.scratchteam#Retuns True if the user is in the Scratch team# ----- ----- #user.update()#Updates the above dataFunctions:user.message_count()user.featured_data()#Returns info on the user's featured project as dictuser.follower_count()user.following_count()user.project_count()user.favorites_count()#Returns the amount of projects the user has favoriteduser.followers(limit=40,offset=0)#Returns the followers as list of scratch3.User objectsuser.following(limit=40,offset=0)#Returns the people the user is following as list of scratch3.User objectsuser.projects(limit=None,offset=0)#Returns the projects the user has shared as list of scratch3.Project objectsuser.favorites(limit=None,offset=0)#Returns the projects the user has favorited as list of scratch3.Project objectsuser.follow()user.unfollow()user.is_following("scratcher")#Returns True if user is following the specified Scratcheruser.is_followed_by("scratcher")#Returns True if user is followed by the specified Scratcheruser.comments(limit=20,page=1)#Returns the user's profile commentsuser.post_comment("comment content",parent_id="",commentee_id="")#Posts a comment on the user's profile. Requires logging in. Returns the info of the posted commented.user.reply_comment("comment content",parent_id="parent_id")#Replies to a specified profile comment. Requires logging in. Returns the info of the posted commented.user.delete_comment(comment_id="comment_id")user.report_comment(comment_id="comment_id")user.toggle_commenting()user.set_bio(text)#Changes the 'About me' of the useruser.set_wiwo(text)user.stats()#Returns the user's statistics as dict. Fetched from ScratchDBuser.ranks()#Returns the user's ranks as dict. Fetched from ScratchDB'''New in v0.5.0:'''user.studio_count()#Returns the amount of studios the user is curatinguser.studio_following_count()Projectsscratch3.ProjectGet a project:project=session.connect_project("project_id")You can also get projects without logging in:project=scratch3.get_project("project_id")Attributes:project.id#Returns the project idproject.url#Returns the project urlproject.author#Returns the username of the authorproject.comments_allowed#Returns True if comments are enabledproject.instructionsproject.notes#Returns the 'Notes and Credits' sectionproject.created#Returns the date of the project creationproject.last_modified#Returns the date when the project was modified the last timeproject.share_dateproject.thumbnail_urlproject.remix_parentproject.remix_rootproject.loves#Returns the love countproject.favorites#Returns the project's favorite countproject.remix_count#Returns the number of remixesproject.views#Returns the view countproject.project_token# ----- ----- #project.update()#Updates the above dataFunctions:project.get_author()#Returns the author as scratch3.User objectproject.ranks()#Returns the project's ranks. Fetched from ScratchDBproject.comments(limit=40,offset=0)#Fetches all project comments except for comment repliesproject.get_comment_replies(comment_id="comment_id",limit=40,offset=0)#Fetches the replies to a specific commentproject.post_comment(content="comment content",parent_id="",commentee_id="")#Returns the info of the posted commented.project.reply_comment(content="comment content",parent_id="parent_id")#Returns the info of the posted commented.project.delete_comment(comment_id="comment_id")project.report_comment(comment_id="comment_id")project.love()project.unlove()project.favorite()project.unfavorite()project.post_view()project.set_title("new title")project.set_instructions("new instructions")project.set_notes("new notes and credits")#Sets the notes and credits section of the projectproject.set_thumbnail("filename")#File must be .png and fit Scratch's thumbnail guidelines project.share() project.unshare()project.turn_off_commenting()project.turn_on_commenting()project.toggle_commenting()project.remixes(limit=None,offset=0)#Returns the remixes as list of scratch3.Projectproject.studios(limit=None,offset=0)#Returns the studios the project is in as list of dictsproject.download(filename="project_name.sb3",dir="")#Downloads the project to your computer. The downloaded file will only work in the online editor.project.get_raw_json()#Returns the json of the project content as dictproject.get_creator_agent()#Returns the user-agent of the user who created the project (with information about their browser and OS)Create a project:(New in v0.5.0)Warning: Spam-creating projects is against Scratch's Terms of Use.project=session.create_project()#Returns the created project as scratch3.Project objectUnshared projectsscratch3.PartialProjectWhen connecting / getting a project that you can't access, aPartialProjectobject is returned instead.Most attributes and most functions don't work for such projects. However, these still work:project.remixes(limit=None,offset=0)project.download(filename="project_name.sb3",dir="/")project.get_raw_json()project.get_creator_agent()Studiosscratch3.Studio(New in v0.5.0)Get a studio:project=session.connect_studio("studio_id")You can also get studios without logging in:project=scratch3.get_studio("studio_id")Attributes:studio.idstudio.titlestudio.descriptionstudio.host_id#The user id of the studio hoststudio.open_to_all#Whether everyone is allowed to add projectsstudio.comments_allowedstudio.image_urlstudio.createdstudio.modifiedstudio.follower_countstudio.manager_countstudio.project_count# ----- ----- #project.update()#Updates the above dataFunctions:studio.follow()studio.unfollow()studio.comments(limit=40,offset=0)#Fetches all project comments except for comment repliesstudio.get_comment_replies(comment_id="comment_id",limit=40,offset=0)#Fetches the replies to a specific commentstudio.post_comment(content="comment content",parent_id="",commentee_id="")#Returns the info of the posted commented.studio.reply_comment(content="comment content",parent_id="parent_id")#Returns the info of the posted commented.studio.projects(limit=40,offset=0)studio.curators(limit=24,offset=0)#Returns the curators as list of users (scratch3.User)studio.managers(limit=24,offset=0)Search / Explore pageDoesn't require a sessionSearch:session.search_projects(query="query",mode="trending",language="en",limit=40,offset=0)scratch3.search_projects(query="query",mode="trending",language="en",limit=40,offset=0)#Doesn't require logging inscratch3.search_studios(query="query",mode="trending",language="en",limit=40,offset=0)scratch3.search_comments(query="query")#This will return matching profile comments from all across Scratch. It is based on ScratchDataGet the explore page:session.explore_projects(query="*",mode="trending",language="en",limit=40,offset=0)scratch3.explore_projects(query="*",mode="trending",language="en",limit=40,offset=0)#Doesn't require logging inscratch3.explore_studios(query="*",mode="trending",language="en",limit=40,offset=0)Messages / My stuff pageFunctions:session.get_mystuff_projects("all",page=1,sort_by="")#Returns the projects from your "My stuff" page as listsession.messages(limit=40,offset=0)#Returns your messages as dictsession.clear_messages()#Marks your messages as readsession.get_message_count()#Returns your message count"What's happening" section / Your feedFunctions:session.get_feed(limit=20,offset=0)#Returns your "What's happening" section from the Scratch front page as listsession.loved_by_followed_users(limit=40,offset=0)#Returns the projects loved by users you are following as listFeatured projects / NewsDoesn't require a sessionscratch3.get_news(limit=10,offset=0)#Returns the news from the Scratch front page as listscratch3.featured_projects()#Returns the featured projects from the Scratch homepage as listscratch3.featured_studios()scratch3.top_loved()scratch3.top_remixed()scratch3.newest_projects()#Returns a list with the newest Scratch projects. This list is not present on the Scratch home page, but the API still provides it.scratch3.design_studio_projects()ContributorsAlmost all code by TimMcCool
(https://scratch.mit.edu/users/TimMcCool/)Siddhesh (creator of scratchconnect) for some help and the profile
comments APIDatOneLefty for ScratchDB which is used to fetch stats and ranksLynx for ScratchData (https://sd.sly-little-fox.ru/api/v1/search?q=)Source code available on GitHubSupportIf you need help with your code, leave a comment on TimMcCool's Scratch
profile:https://scratch.mit.edu/users/TimMcCool/