Examples

Example 1: Ping Pong

In this example, when someone sends a “ping”, scratchcloud will send back a “pong”.

This example is linked to the project 622779749.

 1from scratchcloud import CloudClient, CloudChange
 2
 3client = CloudClient(username='yuwe', project_id='622779749')
 4
 5@client.event
 6async def on_connect():
 7    print('Started!')
 8
 9@client.event
10async def on_disconnect():
11    print('Stopped!')
12
13@client.cloud_event('REQUEST')
14async def on_request(cloud: CloudChange):
15    print(f'Got ping value of {cloud.value}. Sending pong...')
16    await client.set_cloud('RESPONSE', cloud.value)
17
18client.run('password')

Description:

  • Line 1: Imports scratchcloud

  • Line 3: Creates a new CloudClient object

  • Line 5-11: Sets up print statements when connected and disconnected

  • Line 13-14: Sets up a cloud event function for the cloud variable REQUEST. This is called whenever REQUEST is set in scratch

  • Line 16: Sets the RESPONSE cloud variable to the value of the REQUEST variable

  • Line 18: Run the CloudClient object

Example 2: Hex Hash

In this example, when someone sends data, scratchcloud hashes it.

This example is linked to the project 622792569.

 1from scratchcloud import CloudClient, CloudChange
 2from scratchcloud.ext import BaseCodec
 3from scratchcloud.errors import DecodeError, SizeError
 4
 5from hashlib import md5
 6
 7codec = BaseCodec()
 8
 9client = CloudClient(username='yuwe', project_id='622792569', encoder=codec.encode, decoder=codec.decode)
10
11@client.event
12async def on_connect():
13    print('Connected!')
14
15@client.event
16async def on_disconnect():
17    print('Disconnected!')
18
19@client.cloud_event('REQUEST')
20async def on_request(cloud: CloudChange):
21    hashed_result = md5(cloud.value.encode())
22    hex_result = hashed_result.hexdigest()
23    print(f'Got {cloud.value}. Hashing to {hex_result}...')
24
25    await client.set_cloud('RESPONSE', f'The MD5 hash for \"{cloud.value}\" is {hex_result}')
26
27@client.cloud_event_error('REQUEST')
28async def request_error(error: Exception, cloud: CloudChange):
29    if isinstance(error, DecodeError):
30        await client.set_cloud('RESPONSE', 'there was an error decoding your data')
31    elif isinstance(error, SizeError):
32        await client.set_cloud('RESPONSE', 'the response was too long to be sent')
33    else:
34        raise error
35
36client.run('password')

Description:

  • Line 2: Imports BaseCodec, which will be used for encoding/decoding all data. This allows the CloudClient to send letters instead of numbers

  • Line 3: Imports the DecodeError, which is called when issues with decoding arise, and the SizeError, which is called when a Client.set_cloud payload is too big to send.

  • Line 5: Imports the builtin python md5 hash function

  • Line 7: Creates a new BaseCodec object.

  • Line 9: Creates a CloudClient object with the predefined codec passed into the encoder and decoder parameters. This specifies the CloudClient’s encoding and decoding method.

  • Lines 21-22: Hashes the value received from the REQUEST variable

  • Line 25: Sends the hashed result. A non-digit value can be used because a encoder was specified when creating the CloudClient

  • Lines 27-28: Sets up a cloud event error function for the cloud variable REQUEST. This is called whenever an error is raised in the cloud event REQUEST function

  • Lines 29-34: Handles errors and sends error messages

Example 3: API Users

In this example, when someone sends a scratch username, scratchcloud responds with that user’s information.

This example is linked to the project 622799182.

 1from scratchcloud import CloudClient, CloudChange
 2from scratchcloud.ext import BaseCodec, APIConnection
 3from scratchcloud.errors import DecodeError, NotFoundError, SizeError
 4
 5codec = BaseCodec()
 6
 7client = CloudClient(username='yuwe', project_id='622799182', encoder=codec.encode, decoder=codec.decode)
 8api = APIConnection(client)
 9
10@client.event
11async def on_connect():
12    print('Connected!')
13
14@client.event
15async def on_disconnect():
16    print('Disconnected!')
17
18@client.cloud_event('REQUEST')
19async def on_request(cloud: CloudChange):
20    print(f'Request for user \"{cloud.value}\" received!')
21
22    try:
23        user = await api.fetch_user(cloud.value)
24    except NotFoundError:
25        await client.set_cloud('RESPONSE', f'the user \"{cloud.value}\" could not be found.')
26        return
27
28    username = user.username
29    country = user.country
30    join_date = user.joined.strftime('%B %d, %Y')
31
32    await client.set_cloud('RESPONSE', f'i\'m {username} from {country}! I joined on {join_date}')
33
34@client.cloud_event_error('REQUEST')
35async def request_error(cloud: CloudChange, error: Exception):
36    if isinstance(error, DecodeError):
37        await client.set_cloud('RESPONSE', 'there was an error decoding your data.')
38
39    elif isinstance(error, SizeError):
40        await client.set_cloud('RESPONSE', 'the response was too long to be sent.')
41
42    else:
43        raise error
44
45client.run('password')

Description:

  • Line 2: Imports BaseCodec and APIConnection. An APIConnection object can get scratch user information

  • Line 8: Creates a new APIConnection object

  • Line 23: Fetches a user object using the APIConnection

  • Lines 22-26: Checks to see if there is an issue with fetching a user. If there is, set the RESPONSE cloud variable to an error message and exit

  • Lines 28, 29, 30: Sets username, country, and join_date variables from the User object