Sid72020123 / scratchconnect

Python Library to connect Scratch API and much more.
https://sid72020123.github.io/scratchconnect/
MIT License
25 stars 14 forks source link

SSL error when using events #39

Closed dotargz closed 2 years ago

dotargz commented 2 years ago

i get Exception raised in callback <function run at 0x00000231ABA931C0> for event "change" - Traceback (most recent call last): File "C:\Users\*\AppData\Local\Programs\Python\Python310\lib\site-packages\pyemitter.py", line 176, in __call_sync return sock.send(data) File "C:\Users\*\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1205, in send return self._sslobj.write(data) ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:2396)

after a few seconds of my program running.

i have the update fequency set to 3 if that matters

dotargz commented 2 years ago

also, how do i stay logged in on scratch when the server is running?

Sid72020123 commented 2 years ago

No. You need an alt account for that. You can also change cloud variables with "New Scratcher" status using ScratchConnect! Also add a try except in which you can connect the cloud varaibles again when you get that error...

Sid72020123 commented 2 years ago

I think I will update the library's code to fix this...

Sid72020123 commented 2 years ago

Can you share the code for this? Remove all the sensitive data and share the code here if you want to?

dotargz commented 2 years ago
import scratchconnect
import time
import os
import requests

cloud = scratchconnect.ScratchConnect("SparkSystem32", os.environ['PASSWORD'])
project = cloud.connect_project(project_id=677859358)
variables = project.connect_cloud_variables()

event = variables.start_event(
    update_time=3)

@variables.event.on('change')
def run(**data):
    cloud = scratchconnect.ScratchConnect("SparkSystem32", os.environ['PASSWORD'])
    project = cloud.connect_project(project_id=677859358)
    variables = project.connect_cloud_variables()
    event_type = data['action']
    if event_type == 'set_var':
        if (data['variable_name'] == "☁ TO_HOST_1"):
            if (int(time.time()) - int(data['timestamp']/1000) > 15):
                print("[INFO] Data too old, ignoring...")
                return False
            else:
                print("[INFO] Data young enough, processing...")
                if (variables.decode(data['value']) == "START"):
                    print("[INFO] Connection request received...")
                    encoded_handshake = variables.encode("CONNECTED:V1")
                    sethandshake = variables.set_cloud_variable(variable_name="☁ TO_CLIENT_1", value=encoded_handshake)
                    if sethandshake:
                        print ("[INFO] Connection request received & sent successfully")
                        return True
                    else:
                        print("[ERR] Something went wrong...")
                        return False
                elif (variables.decode(data['value']).startswith("GET:TRILLEX$")):
                  usertocheck = variables.decode(data['value']).split('$')[1]
                  print(f"[INFO] Trillex request received... ({usertocheck})")
                  r =requests.get(f'https://trillex.rehost.xyz/balance?id={usertocheck}')
                  if ((r.json())["status"]) == 200:
                    texttoencode = (r.json())["balance"]
                    encoded_balance = variables.encode(texttoencode)
                    setbal = variables.set_cloud_variable(variable_name="☁ TO_CLIENT_1", value=encoded_balance)
                    if setbal:
                      print(f"[INFO] Trillex request received & sent successfully... ({usertocheck})")
                      return True
                    else:
                      print("[ERR] Something went wrong...")
                      return False
                  else:
                    print("[ERR] Something went wrong, sending error..")
                    texttoencode = "0.00 (NOT_FOUND)"
                    encoded_balance = variables.encode(texttoencode)
                    setbal = variables.set_cloud_variable(variable_name="☁ TO_CLIENT_1", value=encoded_balance)
                else:
                    print("[INFO] not inital handshake, ignoring for now...")
                    return False
        else:
            print("[INFO] Not for server to respond to, ignoring")
            return False
dotargz commented 2 years ago

although it only happens sometimes.

Sid72020123 commented 2 years ago

Check if this works:

import scratchconnect
import time
import os
import requests

cloud = scratchconnect.ScratchConnect("SparkSystem32", os.environ['PASSWORD'])
project = cloud.connect_project(project_id=677859358)
variables = project.connect_cloud_variables()

event = variables.start_event(
    update_time=3)

@variables.event.on('change')
def run(**data):
    variables = project.connect_cloud_variables()
    event_type = data['action']
    if event_type == 'set_var':
        if (data['variable_name'] == "☁ TO_HOST_1"):
            if (int(time.time()) - int(data['timestamp']/1000) > 15):
                print("[INFO] Data too old, ignoring...")
                return False
            else:
                print("[INFO] Data young enough, processing...")
                if (variables.decode(data['value']) == "START"):
                    print("[INFO] Connection request received...")
                    encoded_handshake = variables.encode("CONNECTED:V1")
                    sethandshake = variables.set_cloud_variable(variable_name="☁ TO_CLIENT_1", value=encoded_handshake)
                    if sethandshake:
                        print ("[INFO] Connection request received & sent successfully")
                        return True
                    else:
                        print("[ERR] Something went wrong...")
                        return False
                elif (variables.decode(data['value']).startswith("GET:TRILLEX$")):
                  usertocheck = variables.decode(data['value']).split('$')[1]
                  print(f"[INFO] Trillex request received... ({usertocheck})")
                  r =requests.get(f'https://trillex.rehost.xyz/balance?id={usertocheck}')
                  if ((r.json())["status"]) == 200:
                    texttoencode = (r.json())["balance"]
                    encoded_balance = variables.encode(texttoencode)
                    setbal = variables.set_cloud_variable(variable_name="☁ TO_CLIENT_1", value=encoded_balance)
                    if setbal:
                      print(f"[INFO] Trillex request received & sent successfully... ({usertocheck})")
                      return True
                    else:
                      print("[ERR] Something went wrong...")
                      return False
                  else:
                    print("[ERR] Something went wrong, sending error..")
                    texttoencode = "0.00 (NOT_FOUND)"
                    encoded_balance = variables.encode(texttoencode)
                    setbal = variables.set_cloud_variable(variable_name="☁ TO_CLIENT_1", value=encoded_balance)
                else:
                    print("[INFO] not inital handshake, ignoring for now...")
                    return False
        else:
            print("[INFO] Not for server to respond to, ignoring")
            return False
Sid72020123 commented 2 years ago

although it only happens sometimes.

Yes. It should happen because the Scratch server sometimes closes the websocket connection... But, does you program stop when the error occurs or it continues when it gets next request? You can use try/except it it stops...

dotargz commented 2 years ago

yes currently i have a script that just restarts the file if it crashes

Sid72020123 commented 2 years ago

Ok. So is the issue fixed? I will add a new exception handle for this error, so it won't happen again...

Sid72020123 commented 2 years ago

ScratchConnect is Updated to v3.1! It includes auto-connect when a Broken Pipe or SSL Error comes!