From e95565c084927f9c720aea1312f7edc86a128c0b Mon Sep 17 00:00:00 2001 From: Maxwell Jeffress Date: Sat, 27 Dec 2025 17:21:40 +1100 Subject: [PATCH] add source files --- barry.py | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ bot.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 barry.py create mode 100644 bot.py diff --git a/barry.py b/barry.py new file mode 100644 index 0000000..67d7842 --- /dev/null +++ b/barry.py @@ -0,0 +1,49 @@ +import re +import random + +regex = re.compile("[^a-zA-Z ]") + +class Token: + def __init__(self): + self.completions: list[str] = [] + def __repr__(self): + return self.completions.__repr__() + def add_completion(self, word: str): + self.completions.append(word) + +class Model: + def __init__(self): + self.tokens: dict[str, Token] = {} + def predict(self, previous: str) -> str | None: + if previous in self.tokens: + completion = self.tokens[previous].completions + return random.choice(completion) + else: + return None + +def tokenise(instr: str): + return re.split(r" |\n", regex.sub("", instr).lower()) + +def train(data: str): + model = Model() + spldata = tokenise(data) + for i in range(0, len(spldata) - 1): + word = spldata[i] + next_word = spldata[i + 1] + if not word in model.tokens: + model.tokens[word] = Token() + model.tokens[word].add_completion(next_word) + return model + +def prompt(prompt: str, model: Model) -> str: + words = tokenise(prompt) + output: str = "" + currentWord = words[-1] + for _ in range(1, 200): + currentWord = model.predict(currentWord) + if currentWord == None: + break + output += currentWord + " " + + return output + diff --git a/bot.py b/bot.py new file mode 100644 index 0000000..fb9c581 --- /dev/null +++ b/bot.py @@ -0,0 +1,28 @@ +import barry +import discord +from discord import app_commands +import os + +intents = discord.Intents.default() +client = discord.Client(intents=intents) +tree = app_commands.CommandTree(client) + +with open("training.txt") as t: + training = t.read() + +model = barry.train(training) + +@tree.command(name="ask", description="Ask Barry a question") +async def ask(interaction: discord.Interaction, question: str): + _ = await interaction.response.send_message(barry.prompt(question, model)) + +@client.event +async def on_ready(): + await tree.sync() + print(f"logged in as {client.user}") +key = os.getenv("BARRY_TOKEN", None) +if key == None: + print("Set BARRY_TOKEN to the Discord token before continuing") + exit(1) +client.run(key) +