Discuss Scratch

MonkeyBean2
Scratcher
100+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

wvzack wrote:

for some reason my script is outputting (in what i can see) extremely random stuff. This code is setting the file to what it should be ( ) the first time it runs however the second time it is not…. and is set to:
['[', "'", 'w', 'v', 'z', 'a', 'c', 'k', '1', "'", ']', 'wvzack1']
which is very wrong

Here is my code:
... snip because bad word detector ...

Thanks!!!

Hmm it looks like a certain list is somehow getting converted to a string, like so: list(str(myList)), which will make a list of the characters representing the string form of that list.

I recommend using the following opening tag to enable python syntax highlighting in code blocks:
[code=py][/code]

Last edited by MonkeyBean2 (Sept. 15, 2024 03:42:21)



9NAwRfSR-%dWFS$a$g&zBMTj2?;jvS?L5%^X%qpCX|A<*paJ=lU07c)wmt$v{TxL5



scratchGui.timeTravel.year = '2020'
mybearworld
Scratcher
1000+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

wvzack wrote:

(#1020)
for some reason my script is outputting (in what i can see) extremely random stuff. This code is setting the file to what it should be ( ['wvzack1'] ) the first time it runs however the second time it is not…. and is set to:
['[', "'", 'w', 'v', 'z', 'a', 'c', 'k', '1', "'", ']', 'wvzack1']
which is very wrong

Here is my code:
-snip-

Thanks!!!
    # read_file returns a string, so this will return '["wvzack1"]'
    # list() then turns strings into a list of characters, i.e. ["[", '"', "w", "v", "z", "a", "c", "k", "1", '"', "]"]
    # (you probably want json.loads instead)
    usernames_list = list(read_file("usernames.txt"))
    # "wvzack1" is not in the list above...
    if username not in usernames_list:
        # ... so it gets added, now it is ["[", '"', "w", "v", "z", "a", "c", "k", "1", '"', "]", "wvzack1"]
        usernames_list.append(username)
        write_file("usernames.txt", usernames_list)
        write_file_votes(votes_dict)

Signatures are the only place where assets links still work.
A-MARIO-PLAYER
Scratcher
1000+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

need help
Warning: Caught error in request 'search_db' - Full error below
Traceback (most recent call last):
File "/home/ghost/.local/lib/python3.12/site-packages/scratchattach/cloud_requests.py", line 116, in call_request
output = req_obj["on_call"](*arguments) # Calls the request function and saves the function's returned data in the output variable
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ghost/scratchattach_progs/projector.py", line 20, in search_db
cur.execute("SELECT * FROM project WHERE name LIKE '%?%'", (argument1,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.
pretty obvious where this is, but not what it is

moved to @8to16 - this account is an archive





Amp hall of fame
Any posts I made before 2024 are bad posts.
1000th post (no edit)
ban scratch cause you can hack it
i only know 5 digits of pi
quote spam to the extreme
slatch.mit.edu
dying of cringe scratchblocks
Workaround: Summon it





buahauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhau
the laugh is so evil your tiny screen can't comprehend it
Maximouse
Scratcher
1000+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

A-MARIO-PLAYER wrote:

need help
Warning: Caught error in request 'search_db' - Full error below
Traceback (most recent call last):
File "/home/ghost/.local/lib/python3.12/site-packages/scratchattach/cloud_requests.py", line 116, in call_request
output = req_obj["on_call"](*arguments) # Calls the request function and saves the function's returned data in the output variable
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ghost/scratchattach_progs/projector.py", line 20, in search_db
cur.execute("SELECT * FROM project WHERE name LIKE '%?%'", (argument1,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.
pretty obvious where this is, but not what it is
See https://stackoverflow.com/questions/20904209/how-to-execute-select-like-statement-with-a-placeholder-in-sqlite


This is Maximouse's signature. Learn more about signatures.
A-MARIO-PLAYER
Scratcher
1000+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Maximouse wrote:

See https://stackoverflow.com/questions/20904209/how-to-execute-select-like-statement-with-a-placeholder-in-sqlite
thanks
for a moment i had to resort to using f-strings which is sql-injectable and can get my entire project's database killed off

moved to @8to16 - this account is an archive





Amp hall of fame
Any posts I made before 2024 are bad posts.
1000th post (no edit)
ban scratch cause you can hack it
i only know 5 digits of pi
quote spam to the extreme
slatch.mit.edu
dying of cringe scratchblocks
Workaround: Summon it





buahauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhauhau
the laugh is so evil your tiny screen can't comprehend it
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

So I fixed the last error however I ran into a new one that I have no idea how to fix as I dont know much about json. here is my code:
https://traff.co/jitV7en7

password is scratch

Here is the error I am getting I tried looking it up but didn't find anything useful

Traceback (most recent call last):
File "/home/pi/Python_Projects/ByteBank/vote.py", line 38, in <module>
vote("wvzack1", "test")
File "/home/pi/Python_Projects/ByteBank/vote.py", line 29, in vote
amount = int(votes[choice])
KeyError: 'test'

Thanks!!!!

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
mybearworld
Scratcher
1000+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

wvzack wrote:

(#1026)
Traceback (most recent call last):
File "/home/pi/Python_Projects/ByteBank/vote.py", line 38, in <module>
vote("wvzack1", "test")
File "/home/pi/Python_Projects/ByteBank/vote.py", line 29, in vote
amount = int(votes[choice])
KeyError: 'test'
votes doesn't have the key that's in choice. You could make sure it exists by doing something like
if choice not in votes:
    votes[choice] = 0

Signatures are the only place where assets links still work.
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

mybearworld wrote:

wvzack wrote:

(#1026)
Traceback (most recent call last):
File "/home/pi/Python_Projects/ByteBank/vote.py", line 38, in <module>
vote("wvzack1", "test")
File "/home/pi/Python_Projects/ByteBank/vote.py", line 29, in vote
amount = int(votes[choice])
KeyError: 'test'
votes doesn't have the key that's in choice. You could make sure it exists by doing something like
if choice not in votes:
    votes[choice] = 0
I tried this however it is just resetting it to 0 even though it shouldn't.

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

I am trying to make a project that monitors a scratch project so it can record the stats of it (views loves favs remixes) however I have not been able to think of a way to do this efficiently. The project would collect data once per day and save it to some type of file (im thinking with JSON but idk if that's a good choice). Here is what I thought of.
So you have a dictionary that has all the project ids of different projects the code is monitoring as keys, inside of each key in that dictionary you have another dictionary that has every day that it was collecting data. In each of thoughs keys you have a list with 4 items in it: views loves favorites and remixes.

While I think this would maybe work I also think it would take up a lot more power then is needed to make small additions to the data especially if it is getting the stats of a lot of projects at the same time.

Thanks!

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
davidtheplatform
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

wvzack wrote:

I am trying to make a project that monitors a scratch project so it can record the stats of it (views loves favs remixes) however I have not been able to think of a way to do this efficiently. The project would collect data once per day and save it to some type of file (im thinking with JSON but idk if that's a good choice). Here is what I thought of.
So you have a dictionary that has all the project ids of different projects the code is monitoring as keys, inside of each key in that dictionary you have another dictionary that has every day that it was collecting data. In each of thoughs keys you have a list with 4 items in it: views loves favorites and remixes.

While I think this would maybe work I also think it would take up a lot more power then is needed to make small additions to the data especially if it is getting the stats of a lot of projects at the same time.

Thanks!
Some sort of database engine would work well for this. I would recommend SQLite since it comes with python (which I assume you are using) and is really easy to use.
I would have a single table that has columns for the project ID, date, loves, etc… and you can use the WHERE clause to only get the entries for one project.
To put data into the database, you would use the following SQL query:
INSERT INTO logs VALUES(:id, :timestamp, :loves, etc...);
To get all of the data for one project:
SELECT * FROM logs WHERE id=:id ORDER BY timestamp ASC;

Generation 4: the first time you see this copy and paste it on top of your sig in the scratch forums and increase generation by 1. Social experiment.
MonkeyBean2
Scratcher
100+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

davidtheplatform wrote:

wvzack wrote:

I am trying to make a project that monitors a scratch project so it can record the stats of it (views loves favs remixes) however I have not been able to think of a way to do this efficiently. The project would collect data once per day and save it to some type of file (im thinking with JSON but idk if that's a good choice). Here is what I thought of.
So you have a dictionary that has all the project ids of different projects the code is monitoring as keys, inside of each key in that dictionary you have another dictionary that has every day that it was collecting data. In each of thoughs keys you have a list with 4 items in it: views loves favorites and remixes.

While I think this would maybe work I also think it would take up a lot more power then is needed to make small additions to the data especially if it is getting the stats of a lot of projects at the same time.

Thanks!
Some sort of database engine would work well for this. I would recommend SQLite since it comes with python (which I assume you are using) and is really easy to use.
I would have a single table that has columns for the project ID, date, loves, etc… and you can use the WHERE clause to only get the entries for one project.
To put data into the database, you would use the following SQL query:
INSERT INTO logs VALUES(:id, :timestamp, :loves, etc...);
To get all of the data for one project:
SELECT * FROM logs WHERE id=:id ORDER BY timestamp ASC;
While this is probably the better way, a simple CSV type file could be used, where you open it in append mode in python and just append new logs to the end of it, so the whole file doesn't need to be parsed and re-serialized (this will also put less load on the disk/storage device, as you won't be rewriting the entire thing each day).


9NAwRfSR-%dWFS$a$g&zBMTj2?;jvS?L5%^X%qpCX|A<*paJ=lU07c)wmt$v{TxL5



scratchGui.timeTravel.year = '2020'
wvzack
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

MonkeyBean2 wrote:

davidtheplatform wrote:

wvzack wrote:

I am trying to make a project that monitors a scratch project so it can record the stats of it (views loves favs remixes) however I have not been able to think of a way to do this efficiently. The project would collect data once per day and save it to some type of file (im thinking with JSON but idk if that's a good choice). Here is what I thought of.
So you have a dictionary that has all the project ids of different projects the code is monitoring as keys, inside of each key in that dictionary you have another dictionary that has every day that it was collecting data. In each of thoughs keys you have a list with 4 items in it: views loves favorites and remixes.

While I think this would maybe work I also think it would take up a lot more power then is needed to make small additions to the data especially if it is getting the stats of a lot of projects at the same time.

Thanks!
Some sort of database engine would work well for this. I would recommend SQLite since it comes with python (which I assume you are using) and is really easy to use.
I would have a single table that has columns for the project ID, date, loves, etc… and you can use the WHERE clause to only get the entries for one project.
To put data into the database, you would use the following SQL query:
INSERT INTO logs VALUES(:id, :timestamp, :loves, etc...);
To get all of the data for one project:
SELECT * FROM logs WHERE id=:id ORDER BY timestamp ASC;
While this is probably the better way, a simple CSV type file could be used, where you open it in append mode in python and just append new logs to the end of it, so the whole file doesn't need to be parsed and re-serialized (this will also put less load on the disk/storage device, as you won't be rewriting the entire thing each day).
Hmmm I will look into that thanks!

Likes: Programing (python scratch Lua c++ I am bad at c++ a) Aiviation (B787 Queen of the sky F35) Mountain Biking and Messing around with computers (not a gamer at all)
My projects I am most happy with also the few “polished games I have:
davidtheplatform
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

MonkeyBean2 wrote:

davidtheplatform wrote:

wvzack wrote:

I am trying to make a project that monitors a scratch project so it can record the stats of it (views loves favs remixes) however I have not been able to think of a way to do this efficiently. The project would collect data once per day and save it to some type of file (im thinking with JSON but idk if that's a good choice). Here is what I thought of.
So you have a dictionary that has all the project ids of different projects the code is monitoring as keys, inside of each key in that dictionary you have another dictionary that has every day that it was collecting data. In each of thoughs keys you have a list with 4 items in it: views loves favorites and remixes.

While I think this would maybe work I also think it would take up a lot more power then is needed to make small additions to the data especially if it is getting the stats of a lot of projects at the same time.

Thanks!
Some sort of database engine would work well for this. I would recommend SQLite since it comes with python (which I assume you are using) and is really easy to use.
I would have a single table that has columns for the project ID, date, loves, etc… and you can use the WHERE clause to only get the entries for one project.
To put data into the database, you would use the following SQL query:
INSERT INTO logs VALUES(:id, :timestamp, :loves, etc...);
To get all of the data for one project:
SELECT * FROM logs WHERE id=:id ORDER BY timestamp ASC;
While this is probably the better way, a simple CSV type file could be used, where you open it in append mode in python and just append new logs to the end of it, so the whole file doesn't need to be parsed and re-serialized (this will also put less load on the disk/storage device, as you won't be rewriting the entire thing each day).
SQLite doesn't re-serialize the file on every write. It appends new data to the end of the file, similar to how a CSV file would work.

Generation 4: the first time you see this copy and paste it on top of your sig in the scratch forums and increase generation by 1. Social experiment.
Scratchnosekai
Scratcher
100+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

import requests
import scratchattach as scratch3
import time
import os
weather_dict = {
    "thunderstorm": 1,
    "drizzle": 2,
    "rain": 3,
    "snow": 4,
    "clear": 5,
    "clouds": 6,
    "mist": 7,
    "smoke": 8,
    "haze": 9,
    "dust": 16,  
    "fog": 11,
    "sand": 12,
    "ash": 13,
    "squall": 14,
    "tornado": 15
}
api_key = os.getenv('API_KEY')
password = os.getenv('PASSWORD')
city_list = ["nikko", "utsunomiya", "nasu", "takasaki", "minakami", "mito", "hitachi", "tsukuba", "chiba,jp", "narita,jp", "kisarazu", "saitama", "kumagaya", "hanno","hakone","hiratsuka","sumida","shibuya","shinagawa","suginami","koganei","okutama"]
city_dict = {f"{i+1001}": city for i, city in enumerate(city_list)}
city_coords = {
    "yokohama": (35.448, 139.643),
    "kawasaki": (35.521, 139.717)
}
def send_weather(weather):
    if weather in weather_dict:
        return weather_dict[weather]
    else:
        return -1 
session = scratch3.login("Scratchnosekai_2",password)
conn = session.connect_cloud("871346881")
def update_weather(city):
    if city in city_coords:
        lat, lon = city_coords[city]
        url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=metric"
    else:
        url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        weather = data['weather'][0]['main'].lower()
        humidity = data['main']['humidity']
        temperature = data['main']['temp']
        weather_code = send_weather(weather)
        print(f"Weather for {city}: {weather} (code: {weather_code}), Humidity: {humidity}%, Temperature: {temperature}°C")  
        return weather_code, humidity, temperature
    else:
        print(f"Failed to get weather for {city}, status code: {response.status_code}")  
        return 0, 0, 0  
def handle_request():
    while True:
        for i in range(1, 10):
            request_var = f"From_Host_{i}"
            request = scratch3.get_var(conn, request_var)  # Updated line
            print(f"Checking {request_var}: {request}")  
            if request is not None and request != 0:
                city_id = str(request)
                print(f"Request received from {request_var}: {city_id}")  
                if city_id in city_dict:
                    city = city_dict[city_id]
                    print(f"City found: {city}")  
                    weather_code, humidity, temperature = update_weather(city)
                    combined_data = f"{city_id}{weather_code:02d}{humidity:02d}{int(temperature*10):04d}"
                    print(f"Weather code for {city}: {weather_code}, Humidity: {humidity}%, Temperature: {temperature}°C, Combined data: {combined_data}")  
                    scratch3.set_var(conn, "To_Host", combined_data)  # Updated line
                    print(f"Updated To_Host with combined data: {combined_data}")
                    scratch3.set_var(conn, request_var, 0)  # Updated line
                else:
                    scratch3.set_var(conn, "To_Host", f"{city_id}0000000")  # Updated line
                    print(f"Unknown city ID: {city_id}") 
        time.sleep(1) 
handle_request() 
I have created a program like this that returns information when a weather forecast is requested from the Scratch side, but it returns None on the python side, even though I have changed the value of the cloud variable. By the way, what I am using is github actions.

Last edited by Scratchnosekai (Oct. 11, 2024 07:40:32)


MineTurte
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Scratchnosekai wrote:

import requests
import scratchattach as scratch3
import time
import os
weather_dict = {
    "thunderstorm": 1,
    "drizzle": 2,
    "rain": 3,
    "snow": 4,
    "clear": 5,
    "clouds": 6,
    "mist": 7,
    "smoke": 8,
    "haze": 9,
    "dust": 16,  
    "fog": 11,
    "sand": 12,
    "ash": 13,
    "squall": 14,
    "tornado": 15
}
api_key = os.getenv('API_KEY')
password = os.getenv('PASSWORD')
city_list = ["nikko", "utsunomiya", "nasu", "takasaki", "minakami", "mito", "hitachi", "tsukuba", "chiba,jp", "narita,jp", "kisarazu", "saitama", "kumagaya", "hanno","hakone","hiratsuka","sumida","shibuya","shinagawa","suginami","koganei","okutama"]
city_dict = {f"{i+1001}": city for i, city in enumerate(city_list)}
city_coords = {
    "yokohama": (35.448, 139.643),
    "kawasaki": (35.521, 139.717)
}
def send_weather(weather):
    if weather in weather_dict:
        return weather_dict[weather]
    else:
        return -1 
session = scratch3.login("Scratchnosekai_2",password)
conn = session.connect_cloud("871346881")
def update_weather(city):
    if city in city_coords:
        lat, lon = city_coords[city]
        url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=metric"
    else:
        url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        weather = data['weather'][0]['main'].lower()
        humidity = data['main']['humidity']
        temperature = data['main']['temp']
        weather_code = send_weather(weather)
        print(f"Weather for {city}: {weather} (code: {weather_code}), Humidity: {humidity}%, Temperature: {temperature}°C")  
        return weather_code, humidity, temperature
    else:
        print(f"Failed to get weather for {city}, status code: {response.status_code}")  
        return 0, 0, 0  
def handle_request():
    while True:
        for i in range(1, 10):
            request_var = f"From_Host_{i}"
            request = scratch3.get_var(conn, request_var)  # Updated line
            print(f"Checking {request_var}: {request}")  
            if request is not None and request != 0:
                city_id = str(request)
                print(f"Request received from {request_var}: {city_id}")  
                if city_id in city_dict:
                    city = city_dict[city_id]
                    print(f"City found: {city}")  
                    weather_code, humidity, temperature = update_weather(city)
                    combined_data = f"{city_id}{weather_code:02d}{humidity:02d}{int(temperature*10):04d}"
                    print(f"Weather code for {city}: {weather_code}, Humidity: {humidity}%, Temperature: {temperature}°C, Combined data: {combined_data}")  
                    scratch3.set_var(conn, "To_Host", combined_data)  # Updated line
                    print(f"Updated To_Host with combined data: {combined_data}")
                    scratch3.set_var(conn, request_var, 0)  # Updated line
                else:
                    scratch3.set_var(conn, "To_Host", f"{city_id}0000000")  # Updated line
                    print(f"Unknown city ID: {city_id}") 
        time.sleep(1) 
handle_request() 
I have created a program like this that returns information when a weather forecast is requested from the Scratch side, but it returns None on the python side, even though I have changed the value of the cloud variable. By the way, what I am using is github actions.
You are going to have to be a bit more specific. What exactly returns none? Is the cloud variable set to None or what?

Edit: I am bad at reading. Either the cloud variable isn't updating properly (or is bugged), or something was messed up with the python code itself when fetching the cloud variable. Without being able to properly bug test your code, I can't help much more than this. Sorry.


Also I can't tell if you are saying it shows the forecast on scratch but not on the python side?

Last edited by MineTurte (Oct. 11, 2024 14:40:24)



if I helped you out Consider giving me a blockbit donation!
Jupyter Notebook is literally the best programming interface prove me wrong I dare you

█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█



Signature color gradients here
MonkeyBean2
Scratcher
100+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

MineTurte wrote:

Scratchnosekai wrote:

import requests
import scratchattach as scratch3
import time
import os
weather_dict = {
    "thunderstorm": 1,
    "drizzle": 2,
    "rain": 3,
    "snow": 4,
    "clear": 5,
    "clouds": 6,
    "mist": 7,
    "smoke": 8,
    "haze": 9,
    "dust": 16,  
    "fog": 11,
    "sand": 12,
    "ash": 13,
    "squall": 14,
    "tornado": 15
}
api_key = os.getenv('API_KEY')
password = os.getenv('PASSWORD')
city_list = ["nikko", "utsunomiya", "nasu", "takasaki", "minakami", "mito", "hitachi", "tsukuba", "chiba,jp", "narita,jp", "kisarazu", "saitama", "kumagaya", "hanno","hakone","hiratsuka","sumida","shibuya","shinagawa","suginami","koganei","okutama"]
city_dict = {f"{i+1001}": city for i, city in enumerate(city_list)}
city_coords = {
    "yokohama": (35.448, 139.643),
    "kawasaki": (35.521, 139.717)
}
def send_weather(weather):
    if weather in weather_dict:
        return weather_dict[weather]
    else:
        return -1 
session = scratch3.login("Scratchnosekai_2",password)
conn = session.connect_cloud("871346881")
def update_weather(city):
    if city in city_coords:
        lat, lon = city_coords[city]
        url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=metric"
    else:
        url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        weather = data['weather'][0]['main'].lower()
        humidity = data['main']['humidity']
        temperature = data['main']['temp']
        weather_code = send_weather(weather)
        print(f"Weather for {city}: {weather} (code: {weather_code}), Humidity: {humidity}%, Temperature: {temperature}°C")  
        return weather_code, humidity, temperature
    else:
        print(f"Failed to get weather for {city}, status code: {response.status_code}")  
        return 0, 0, 0  
def handle_request():
    while True:
        for i in range(1, 10):
            request_var = f"From_Host_{i}"
            request = scratch3.get_var(conn, request_var)  # Updated line
            print(f"Checking {request_var}: {request}")  
            if request is not None and request != 0:
                city_id = str(request)
                print(f"Request received from {request_var}: {city_id}")  
                if city_id in city_dict:
                    city = city_dict[city_id]
                    print(f"City found: {city}")  
                    weather_code, humidity, temperature = update_weather(city)
                    combined_data = f"{city_id}{weather_code:02d}{humidity:02d}{int(temperature*10):04d}"
                    print(f"Weather code for {city}: {weather_code}, Humidity: {humidity}%, Temperature: {temperature}°C, Combined data: {combined_data}")  
                    scratch3.set_var(conn, "To_Host", combined_data)  # Updated line
                    print(f"Updated To_Host with combined data: {combined_data}")
                    scratch3.set_var(conn, request_var, 0)  # Updated line
                else:
                    scratch3.set_var(conn, "To_Host", f"{city_id}0000000")  # Updated line
                    print(f"Unknown city ID: {city_id}") 
        time.sleep(1) 
handle_request() 
I have created a program like this that returns information when a weather forecast is requested from the Scratch side, but it returns None on the python side, even though I have changed the value of the cloud variable. By the way, what I am using is github actions.
You are going to have to be a bit more specific. What exactly returns none? Is the cloud variable set to None or what?

Edit: I am bad at reading. Either the cloud variable isn't updating properly (or is bugged), or something was messed up with the python code itself when fetching the cloud variable. Without being able to properly bug test your code, I can't help much more than this. Sorry.


Also I can't tell if you are saying it shows the forecast on scratch but not on the python side?
spamming get_var isn't great, depending on how it's implemented in scratch attach it could cause problems. Plus it is also deprecated in the latest version (update scratchattach pls). If it is spamming the cloud logs api in your version of scratchattach it could be 429ing/ratelimiting. I am not exactly sure how get_var worked in older versions.

Also, I'd recommend encoding the city name per-letter, with two digits per letter. (like 000102 for “abc”, make sure to pad the numbers with a zero eg. 01 02 03)
You could also just use cloud requests which do all of that for you.

Last edited by MonkeyBean2 (Oct. 11, 2024 15:25:58)



9NAwRfSR-%dWFS$a$g&zBMTj2?;jvS?L5%^X%qpCX|A<*paJ=lU07c)wmt$v{TxL5



scratchGui.timeTravel.year = '2020'
Scratchnosekai
Scratcher
100+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

MineTurte wrote:

Scratchnosekai wrote:

import requests
import scratchattach as scratch3
import time
import os
weather_dict = {
    "thunderstorm": 1,
    "drizzle": 2,
    "rain": 3,
    "snow": 4,
    "clear": 5,
    "clouds": 6,
    "mist": 7,
    "smoke": 8,
    "haze": 9,
    "dust": 16,  
    "fog": 11,
    "sand": 12,
    "ash": 13,
    "squall": 14,
    "tornado": 15
}
api_key = os.getenv('API_KEY')
password = os.getenv('PASSWORD')
city_list = ["nikko", "utsunomiya", "nasu", "takasaki", "minakami", "mito", "hitachi", "tsukuba", "chiba,jp", "narita,jp", "kisarazu", "saitama", "kumagaya", "hanno","hakone","hiratsuka","sumida","shibuya","shinagawa","suginami","koganei","okutama"]
city_dict = {f"{i+1001}": city for i, city in enumerate(city_list)}
city_coords = {
    "yokohama": (35.448, 139.643),
    "kawasaki": (35.521, 139.717)
}
def send_weather(weather):
    if weather in weather_dict:
        return weather_dict[weather]
    else:
        return -1 
session = scratch3.login("Scratchnosekai_2",password)
conn = session.connect_cloud("871346881")
def update_weather(city):
    if city in city_coords:
        lat, lon = city_coords[city]
        url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=metric"
    else:
        url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        weather = data['weather'][0]['main'].lower()
        humidity = data['main']['humidity']
        temperature = data['main']['temp']
        weather_code = send_weather(weather)
        print(f"Weather for {city}: {weather} (code: {weather_code}), Humidity: {humidity}%, Temperature: {temperature}°C")  
        return weather_code, humidity, temperature
    else:
        print(f"Failed to get weather for {city}, status code: {response.status_code}")  
        return 0, 0, 0  
def handle_request():
    while True:
        for i in range(1, 10):
            request_var = f"From_Host_{i}"
            request = scratch3.get_var(conn, request_var)  # Updated line
            print(f"Checking {request_var}: {request}")  
            if request is not None and request != 0:
                city_id = str(request)
                print(f"Request received from {request_var}: {city_id}")  
                if city_id in city_dict:
                    city = city_dict[city_id]
                    print(f"City found: {city}")  
                    weather_code, humidity, temperature = update_weather(city)
                    combined_data = f"{city_id}{weather_code:02d}{humidity:02d}{int(temperature*10):04d}"
                    print(f"Weather code for {city}: {weather_code}, Humidity: {humidity}%, Temperature: {temperature}°C, Combined data: {combined_data}")  
                    scratch3.set_var(conn, "To_Host", combined_data)  # Updated line
                    print(f"Updated To_Host with combined data: {combined_data}")
                    scratch3.set_var(conn, request_var, 0)  # Updated line
                else:
                    scratch3.set_var(conn, "To_Host", f"{city_id}0000000")  # Updated line
                    print(f"Unknown city ID: {city_id}") 
        time.sleep(1) 
handle_request() 
I have created a program like this that returns information when a weather forecast is requested from the Scratch side, but it returns None on the python side, even though I have changed the value of the cloud variable. By the way, what I am using is github actions.
You are going to have to be a bit more specific. What exactly returns none? Is the cloud variable set to None or what?

Edit: I am bad at reading. Either the cloud variable isn't updating properly (or is bugged), or something was messed up with the python code itself when fetching the cloud variable. Without being able to properly bug test your code, I can't help much more than this. Sorry.


Also I can't tell if you are saying it shows the forecast on scratch but not on the python side?
Sorry, let me elaborate.
Every time Python checks the cloud variable, it shows “From_Host_1:none”, even though the cloud variable on the Scratch side is changed to 1001, or 1005, but no information is sent to To_Host.

Last edited by Scratchnosekai (Oct. 11, 2024 22:16:29)


MineTurte
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Scratchnosekai wrote:

Sorry, let me elaborate.
Every time Python checks the cloud variable, it shows “From_Host_1:none”, even though the cloud variable on the Scratch side is changed to 1001, or 1005, but no information is sent to To_Host.
Sorry for insanely late reply. Seems to me that you just request the var too much. Easy fix.
import time
def sleep(secs): #optional
   time.sleep(secs)
Just put time.sleep(0.5) right after fetching the variable and it should work. Hopefully it will!

Last edited by MineTurte (Oct. 15, 2024 10:04:38)



if I helped you out Consider giving me a blockbit donation!
Jupyter Notebook is literally the best programming interface prove me wrong I dare you

█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█



Signature color gradients here
Dagriffpatchfan
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

I tried setting up a scratchattach server with justablock the linled free server but clicking the verify linl leads to a dead website… whats going on
I thoughtaybe it was the safety restrictions on my internet but using a proxy didnt help

I am (probably) Griffpatch's biggest fan, I mean he did comment on my profile!!!!! Please consider checking out my projects such as my SMB4 remake!
Need an image hosted? Click here
If I wrote something, and then you wrote something back, if I don't respond, feel free to send me the topic link and a reminder on my Profile page
MineTurte
Scratcher
500+ posts

PyHelp - The official Scratch Python help forum | Ask, help, discuss, & more! | +800 posts! |

Dagriffpatchfan wrote:

I tried setting up a scratchattach server with justablock the linled free server but clicking the verify linl leads to a dead website… whats going on
I thoughtaybe it was the safety restrictions on my internet but using a proxy didnt help
I have no clue what justablock or linl is and considering it's a dead website it was either defaced or just… dead. If you have RAM to spare I'd suggest just using shell, terminal, or whatever your computer uses to run a python file with your code in it (and put everything in a “while True:” loop if you don't plan on using something like Crontab, which runs scripts automatically at the specified intervals (limited though as smallest interval is 1 min)). That is the free option. Of course you can use something like replit but replit is now paid for so… yeah.

Last edited by MineTurte (Yesterday 16:34:05)



if I helped you out Consider giving me a blockbit donation!
Jupyter Notebook is literally the best programming interface prove me wrong I dare you

█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█❖█



Signature color gradients here

Powered by DjangoBB