Skip to content

Commit 8e2cfac

Browse files
committed
Improve chatbot response handling and initial prompt, fix chatbot and BlockBit scratch login.
1 parent afabbe8 commit 8e2cfac

6 files changed

Lines changed: 23 additions & 29 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Hide Python cache files
22
*/__pycache__/
33
__pycache__/
4+
# Hide environment variables
45
*.env

chatbot.py

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,6 @@
1010
api_key="sk=1234",
1111
)
1212

13-
# Initial message
14-
completion = client.chat.completions.create(
15-
model="gpt-4-turb",
16-
messages=[
17-
{
18-
"role": "system",
19-
"content": "You are a helpful scratch.mit.edu assistant called FluffyBot",
20-
}
21-
],
22-
)
23-
2413

2514
# Function to simplify AI calling
2615
def answer(query: str, username: str):
@@ -33,31 +22,28 @@ def answer(query: str, username: str):
3322
- username: By what name the AI will call the user
3423
"""
3524
global index
36-
global completion
3725
print("Answering...")
3826

39-
completion = client.chat.completions.create(
27+
resp = client.chat.completions.create(
4028
model="gpt-4-turbo",
4129
messages=[
4230
{
4331
"role": "system",
44-
"content": "You are a helpful scratch.mit.edu assistant called ScratchOn. You cannot swear or do anything inappropriate. Never say anything bad about someone or something. Your language must be appropriate for 7-12 year olds. Always refer to yourself as ScratchOn. Either refer to the user by their username, or don't refer to them at all. Keep your answers short and concise.",
32+
"content": "You are a helpful scratch.mit.edu assistant and user called ScratchOn. You cannot swear or do anything inappropriate. Never say anything bad about someone or something. Your language must be appropriate for 7-12 year olds. Always refer to yourself as ScratchOn, or _Scratch-On_ as your scratch username. Either refer to the user by their username, or don't refer to them at all. Keep your answers short and concise, up to 500 characters. Do not use regular emojis, only use Scratch-style emojis like :), _:D_, or XD. Speak like a scratch.mit.edu user would, using simple words and phrases a 12 years old would use.",
4533
},
46-
{"role": f"Scratcher called {username}", "content": query},
34+
{"role": "user", "content": f"{username}: {query}"},
4735
],
4836
)
4937

50-
result = completion.choices[0].message.content
38+
result = resp.choices[0].message.content
5139

5240
print("Answered !")
5341
return result
5442

5543

5644
# Setup scratch connection
5745
with open("ScratchOn_private/password.txt") as f:
58-
session = sa.login(
59-
username="-FluffyBot-", password=f.readlines()[0]
60-
) # TODO: Create new scratch account for ScratchOn
46+
session = sa.login(username="_Scratch-On_", password=f.readlines()[0])
6147

6248
profile = session.connect_linked_user()
6349
events = session.connect_message_events()
@@ -69,15 +55,15 @@ def answer(query: str, username: str):
6955
def on_message(message):
7056
print("Message detected")
7157

72-
time.sleep(10)
58+
time.sleep(60) # Wait 1 minute before replying to prevent comment glitches
7359

7460
comment = profile.comments(page=1, limit=1)[0]
7561

7662
comment.reply(
7763
content=answer(query=message.comment_fragment, username=message.actor_username)
7864
)
7965
"""
80-
session.connect_user() gets the FluffyBot profile,
66+
session.connect_user() gets the ScratchOn profile,
8167
comment_by_id finds the message based on infos provided by the event handler,
8268
reply() sends a reply by sending the message to the AI setted up earlier.
8369
"""

commands/currency_commands.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from config import bot, scratch_orange
1515
from services import request_search, get_latest_response
1616

17+
1718
@bot.tree.command(
1819
name="blockbit_search",
1920
description="Search a Scratch user and get their BlockBit balance.",
@@ -52,9 +53,12 @@ async def blockbit_search(interact: discord.Interaction, username: str):
5253
)
5354
)
5455

56+
5557
"""
5658
Error Handling During Search
5759
"""
60+
61+
5862
@blockbit_search.error
5963
async def search_error(
6064
interact: discord.Interaction, error: app_commands.AppCommandError

commands/search_commands.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,11 @@ async def randomprojects(interact: discord.Interaction, number: int):
2121
await interact.response.defer()
2222

2323
message = ""
24-
max_project_id = scratch.total_site_stats().get('PROJECT_COUNT')
24+
max_project_id = scratch.total_site_stats().get("PROJECT_COUNT")
2525
for i in range(number):
2626
while True:
2727
try:
28-
project = scratch.get_project(
29-
random.randint(1, max_project_id)
30-
)
28+
project = scratch.get_project(random.randint(1, max_project_id))
3129
except scratch.utils.exceptions.ProjectNotFound:
3230
continue
3331
break

services/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
from .scratchblocks import render_blocks_image
66
from .blockbits import get_latest_response, request_search
77

8-
__all__ = ["render_blocks_image", "get_latest_response", "request_search"]
8+
__all__ = ["render_blocks_image", "get_latest_response", "request_search"]

services/blockbits.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,14 @@
1010

1111

1212
# Login to Scratch
13-
session = sa.login("USERNAME", "PASSWORD")
13+
with open("ScratchOn_private/password.txt") as f:
14+
session = sa.login(username="_Scratch-On_", password=f.readlines()[0])
1415

1516
# Connect to the Blockbit project's cloud variables
1617
cloud = session.connect_cloud(669020072)
1718
latest_value = 1
19+
20+
1821
def request_search(username: str):
1922
"""
2023
Send a request to Scratch asking for a user's balance or data.
@@ -23,9 +26,10 @@ def request_search(username: str):
2326
"""
2427
cloud.set_var("TO_HOST", Encoding.encode(f"search&{username}"))
2528

29+
2630
async def get_response():
2731
global latest_value
28-
async with websockets.connect('wss://clouddata.scratch.mit.edu') as ws:
32+
async with websockets.connect("wss://clouddata.scratch.mit.edu") as ws:
2933
await ws.send(json.dumps({"method": "handshake", "project_id": 669020072}))
3034
while True:
3135
message = json.loads(await ws.recv())
@@ -36,11 +40,12 @@ async def get_response():
3640
last_var = list(variables.values())[-1]
3741
latest_value = last_var
3842

43+
3944
def get_latest_response() -> int | str | None:
4045
"""
4146
Get the most recent response sent back by the Scratch project.
4247
4348
If the response is a number, return it as an int. Otherwise, return it as a string.
4449
"""
4550
get_response()
46-
return float(latest_value) if latest_value is not None else None
51+
return float(latest_value) if latest_value is not None else None

0 commit comments

Comments
 (0)