First push of updated NPC-Gen code
This commit is contained in:
parent
bfe4791ea7
commit
c141426908
5 changed files with 219 additions and 106 deletions
169
Generator.py
169
Generator.py
|
|
@ -4,156 +4,115 @@ from dotenv import load_dotenv
|
||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
import random
|
import random
|
||||||
|
from faker import Faker
|
||||||
|
fake = Faker()
|
||||||
|
|
||||||
|
|
||||||
class NpcGenerator:
|
class NpcGenerator:
|
||||||
"""
|
"""
|
||||||
This class is made to create random NPCs into a specific kanka campaign
|
Generates random NPCs and creates them in a specified Kanka campaign.
|
||||||
"""
|
|
||||||
|
|
||||||
apiToken = None
|
|
||||||
apiBaseUrl = None
|
|
||||||
headers = None
|
|
||||||
campaign_id = None
|
|
||||||
dataPath = None
|
|
||||||
|
|
||||||
"""
|
|
||||||
When instancing the class, the variables from the .env files are loaded and the following class variables are set:
|
|
||||||
apiToken, dataPath, apiBaseUrl and headers
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
self.apiToken = os.getenv("APITOKEN")
|
|
||||||
|
self.apiToken = f"Bearer {os.getenv('APITOKEN')}"
|
||||||
self.dataPath = os.getenv("DATA_PATH")
|
self.dataPath = os.getenv("DATA_PATH")
|
||||||
self.apiBaseUrl = os.getenv("API_URL")
|
self.apiBaseUrl = os.getenv("API_URL")
|
||||||
self.headers = {
|
self.headers = {
|
||||||
'Authorization': self.apiToken,
|
'Authorization': f"{self.apiToken}",
|
||||||
'Accept': 'application/json',
|
'Accept': 'application/json',
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
}
|
}
|
||||||
|
self.campaign_id = None
|
||||||
|
|
||||||
def get_campaigns(self):
|
def get_campaigns(self):
|
||||||
"""
|
response = requests.get(f"{self.apiBaseUrl}campaigns", headers=self.headers)
|
||||||
This method will get a list of all the campaigns created on the account belonging to the owner of the Token
|
response.raise_for_status()
|
||||||
via a HTTP get request and returns a JSON
|
return response.json()
|
||||||
:return: JSON
|
|
||||||
"""
|
|
||||||
campaigns = requests.get("{}campaigns".format(self.apiBaseUrl), headers=self.headers)
|
|
||||||
return json.loads(campaigns.content)
|
|
||||||
|
|
||||||
def set_campaign_id(self, campaign_name):
|
def set_campaign_id(self, campaign_name: str):
|
||||||
"""
|
|
||||||
This method will parse the JSON generated by get_campaigns and set the campaignId with the id of the campaign
|
|
||||||
specified in the campaign_name parameter. If no campaign can be found with that name, it will raise an error
|
|
||||||
:type campaign_name: str
|
|
||||||
"""
|
|
||||||
campaigns = self.get_campaigns()
|
campaigns = self.get_campaigns()
|
||||||
|
for campaign in campaigns.get('data', []):
|
||||||
for campaign in campaigns['data']:
|
if campaign.get('name') == campaign_name:
|
||||||
if campaign['name'] == campaign_name:
|
print(f"Found the campaign that you are looking for with id: {campaign['id']}")
|
||||||
print("Found the campaign that you are looking for with id:{}".format(campaign['id']))
|
|
||||||
self.campaign_id = campaign['id']
|
self.campaign_id = campaign['id']
|
||||||
|
return
|
||||||
|
sys.exit("ERROR: No campaign with that name found!")
|
||||||
|
|
||||||
if self.campaign_id is None:
|
def load_character_details(self) -> dict:
|
||||||
sys.exit("ERROR: No campaign with that name found!")
|
def load_json(filename):
|
||||||
|
with open(os.path.join(self.dataPath, filename), 'r', encoding='utf-8') as f:
|
||||||
|
return json.load(f)
|
||||||
|
|
||||||
def load_charater_details(self):
|
return {
|
||||||
"""
|
'appearance_options': load_json('appearance.json'),
|
||||||
This method will load the three specified files from the location specified in dataPath and returns a dict
|
'personality_options': load_json('personalities.json'),
|
||||||
containing json objects
|
'title_options': load_json('titles.json')
|
||||||
@:returns data: dict
|
|
||||||
"""
|
|
||||||
appearance_options = json.load(open('{}appearance.json'.format(self.dataPath)))
|
|
||||||
personality_options = json.load(open('{}personalities.json'.format(self.dataPath)))
|
|
||||||
title_options = json.load(open('{}titles.json'.format(self.dataPath)))
|
|
||||||
|
|
||||||
data = {
|
|
||||||
'appearance_options': appearance_options,
|
|
||||||
'personality_options': personality_options,
|
|
||||||
'title_options': title_options
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return data
|
# def generate_npc_name(self, sex: str) -> str:
|
||||||
|
# option = "boy_names" if sex == "Male" else "girl_names"
|
||||||
|
# url = f"http://names.drycodes.com/1?nameOptions={option}&format=text&separator=space"
|
||||||
|
# response = requests.get(url)
|
||||||
|
# response.raise_for_status()
|
||||||
|
# return response.text.strip()
|
||||||
|
|
||||||
def genrate_npc_name(self, sex):
|
|
||||||
"""
|
def generate_npc_name(self, sex: str) -> str:
|
||||||
Will get a name via http request from drycodes.com based on the sex specified
|
if sex == "Male":
|
||||||
:type sex: str
|
return fake.name_male()
|
||||||
:return name: str
|
|
||||||
"""
|
|
||||||
if sex is "Male":
|
|
||||||
get_male_name = requests.get(
|
|
||||||
'http://names.drycodes.com/1?nameOptions=boy_names&format=text&separator=space')
|
|
||||||
name = get_male_name.text
|
|
||||||
else:
|
else:
|
||||||
get_female_name = requests.get(
|
return fake.name_female()
|
||||||
'http://names.drycodes.com/1?nameOptions=girl_names&format=text&separator=space')
|
|
||||||
name = get_female_name.text
|
|
||||||
|
|
||||||
return name
|
|
||||||
|
|
||||||
def generate_npcs(self, times):
|
def generate_npcs(self, count: int) -> list:
|
||||||
"""
|
data = self.load_character_details()
|
||||||
Will generate a list of dicts, each dict representing a character. The character details are populated
|
|
||||||
from the data retrieved by load_character_details. The number of characters is decided by the times parameter
|
|
||||||
:type times: int
|
|
||||||
:return npcs: list
|
|
||||||
"""
|
|
||||||
npcs = []
|
npcs = []
|
||||||
|
|
||||||
data = self.load_charater_details()
|
for _ in range(count):
|
||||||
|
|
||||||
for x in range(times):
|
|
||||||
sex = random.choice(['Male', 'Female'])
|
sex = random.choice(['Male', 'Female'])
|
||||||
name = self.genrate_npc_name(sex)
|
name = self.generate_npc_name(sex)
|
||||||
|
|
||||||
character = {
|
npc = {
|
||||||
'name': name,
|
'name': name,
|
||||||
'title': random.choice(data['title_options']['data']),
|
'title': random.choice(data['title_options']['data']),
|
||||||
'age': str(random.randrange(14, 100)),
|
'age': str(random.randint(14, 99)),
|
||||||
'sex': sex,
|
'sex': sex,
|
||||||
'type': 'random_npc',
|
'type': 'random_npc',
|
||||||
'is_private': 'true',
|
'is_private': True,
|
||||||
'personality_name': ['Goals', 'Fears'],
|
'personality_name': ['Goals', 'Fears'],
|
||||||
'personality_entry': [random.choice(data['personality_options']['goals']),
|
'personality_entry': [
|
||||||
random.choice(data['personality_options']['fears'])],
|
random.choice(data['personality_options']['goals']),
|
||||||
|
random.choice(data['personality_options']['fears'])
|
||||||
|
],
|
||||||
'appearance_name': ['Hair', 'Eyes', 'Height', 'Marks', 'Body Type'],
|
'appearance_name': ['Hair', 'Eyes', 'Height', 'Marks', 'Body Type'],
|
||||||
'appearance_entry': [random.choice(data['appearance_options']['hair_type']),
|
'appearance_entry': [
|
||||||
random.choice(data['appearance_options']['eyes']),
|
random.choice(data['appearance_options']['hair_type']),
|
||||||
str(round(random.uniform(4.1, 6.9), 1)) + " feet",
|
random.choice(data['appearance_options']['eyes']),
|
||||||
random.choice(data['appearance_options']['marks']),
|
f"{round(random.uniform(4.1, 6.9), 1)} feet",
|
||||||
random.choice(data['appearance_options']['body_type'])]
|
random.choice(data['appearance_options']['marks']),
|
||||||
|
random.choice(data['appearance_options']['body_type'])
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
npcs.append(npc)
|
||||||
npcs.append(character)
|
|
||||||
|
|
||||||
return npcs
|
return npcs
|
||||||
|
|
||||||
def create_npcs(self, campaign_name=str, times=1):
|
def create_npcs(self, campaign_name: str, count: int = 1):
|
||||||
"""
|
|
||||||
Will search for the specified campaign, generate the npcs and then create then on kanka via http post requests.
|
|
||||||
Please note that kanka has a limit of 30 calls per minute at this time
|
|
||||||
:type times: int
|
|
||||||
:type campaign_name: str
|
|
||||||
"""
|
|
||||||
self.set_campaign_id(campaign_name)
|
self.set_campaign_id(campaign_name)
|
||||||
|
npcs = self.generate_npcs(count)
|
||||||
npcs = self.generate_npcs(times)
|
|
||||||
|
|
||||||
for npc in npcs:
|
for npc in npcs:
|
||||||
|
print(f"Posting character '{npc['name']}' to Kanka")
|
||||||
print('Posting character to kanka')
|
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
"{}campaigns/{}/characters".format(self.apiBaseUrl, self.campaign_id),
|
f"{self.apiBaseUrl}campaigns/{self.campaign_id}/characters",
|
||||||
data=json.dumps(npc),
|
json=npc, # modern requests usage
|
||||||
headers=self.headers)
|
headers=self.headers
|
||||||
|
)
|
||||||
|
|
||||||
if response.status_code is 201:
|
if response.status_code == 201:
|
||||||
print("Character named {} was created successfully!".format(npc['name']))
|
print(f"✅ Character '{npc['name']}' created successfully.")
|
||||||
else:
|
else:
|
||||||
print(
|
print(f"❌ Failed to create character '{npc['name']}': {response.status_code} - {response.text}")
|
||||||
"Character was not created because kanka threw an error, got status code {} with error {} ".format(
|
|
||||||
response.status_code, response.text))
|
|
||||||
|
|
|
||||||
BIN
__pycache__/Generator.cpython-313.pyc
Normal file
BIN
__pycache__/Generator.cpython-313.pyc
Normal file
Binary file not shown.
80
npc-gen-final.py
Normal file
80
npc-gen-final.py
Normal file
|
|
@ -0,0 +1,80 @@
|
||||||
|
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
from Generator import NpcGenerator
|
||||||
|
|
||||||
|
|
||||||
|
def validate_api_token():
|
||||||
|
token = os.getenv("APITOKEN")
|
||||||
|
if not token:
|
||||||
|
sys.exit("❌ Error: API token is missing. Make sure APITOKEN=<token> is set in your .env file.")
|
||||||
|
token = token.strip('"').strip("'")
|
||||||
|
os.environ["APITOKEN"] = token
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def select_campaign(generator):
|
||||||
|
campaigns = generator.get_campaigns().get("data", [])
|
||||||
|
if not campaigns:
|
||||||
|
sys.exit("❌ No campaigns found.")
|
||||||
|
|
||||||
|
print("\nAvailable campaigns:")
|
||||||
|
for idx, campaign in enumerate(campaigns):
|
||||||
|
print(f" [{idx}] {campaign['name']} (ID: {campaign['id']})")
|
||||||
|
print(" [x] Exit")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
choice = input("\nEnter the number of the campaign to use (or 'x' to cancel): ").strip().lower()
|
||||||
|
if choice == 'x':
|
||||||
|
print("Exiting.")
|
||||||
|
sys.exit(0)
|
||||||
|
try:
|
||||||
|
index = int(choice)
|
||||||
|
if 0 <= index < len(campaigns):
|
||||||
|
return campaigns[index]['name']
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
print("Invalid choice. Try again.")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description="Generate random NPCs in a Kanka campaign.")
|
||||||
|
parser.add_argument("--host", help="Set API base URL (e.g., https://kanka.example.com/api/1.0/)")
|
||||||
|
parser.add_argument("--campaign", help="Specify campaign name directly")
|
||||||
|
parser.add_argument("--count", type=int, help="Number of NPCs to generate", default=None)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# Normalize host input if provided
|
||||||
|
if args.host:
|
||||||
|
host = args.host.strip()
|
||||||
|
if not host.startswith("http://") and not host.startswith("https://"):
|
||||||
|
host = "https://" + host
|
||||||
|
if not host.endswith("/api/1.0/"):
|
||||||
|
host = host.rstrip("/") + "/api/1.0/"
|
||||||
|
os.environ["API_URL"] = host
|
||||||
|
|
||||||
|
validate_api_token()
|
||||||
|
generator = NpcGenerator()
|
||||||
|
|
||||||
|
campaign_name = args.campaign or select_campaign(generator)
|
||||||
|
|
||||||
|
count = args.count
|
||||||
|
if count is None:
|
||||||
|
try:
|
||||||
|
count = int(input("Enter number of NPCs to generate: "))
|
||||||
|
except ValueError:
|
||||||
|
sys.exit("❌ Invalid number entered.")
|
||||||
|
|
||||||
|
generator.create_npcs(campaign_name, count)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
67
npc-gen.py
Normal file
67
npc-gen.py
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from Generator import NpcGenerator
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
def validate_api_token():
|
||||||
|
token = os.getenv("APITOKEN")
|
||||||
|
if not token or len(token) < 30:
|
||||||
|
sys.exit("❌ Error: API token is missing or looks invalid. Make sure APITOKEN=<token> is set in your .env file.")
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def select_campaign(generator):
|
||||||
|
campaigns = generator.get_campaigns().get("data", [])
|
||||||
|
if not campaigns:
|
||||||
|
sys.exit("❌ No campaigns found.")
|
||||||
|
|
||||||
|
print("\nAvailable campaigns:")
|
||||||
|
for idx, campaign in enumerate(campaigns):
|
||||||
|
print(f" [{idx}] {campaign['name']} (ID: {campaign['id']})")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
choice = int(input("\nEnter the number of the campaign to use: "))
|
||||||
|
if 0 <= choice < len(campaigns):
|
||||||
|
return campaigns[choice]['name']
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
print("Invalid choice. Try again.")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description="Generate random NPCs in a Kanka campaign.")
|
||||||
|
parser.add_argument("--host", help="Set API base URL (e.g., https://kanka.example.com/api/1.0/)")
|
||||||
|
parser.add_argument("--campaign", help="Specify campaign name directly")
|
||||||
|
parser.add_argument("--count", type=int, help="Number of NPCs to generate", default=None)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# Set host override if provided
|
||||||
|
if args.host:
|
||||||
|
os.environ["API_URL"] = args.host
|
||||||
|
|
||||||
|
validate_api_token()
|
||||||
|
generator = NpcGenerator()
|
||||||
|
|
||||||
|
# Determine campaign name
|
||||||
|
campaign_name = args.campaign or select_campaign(generator)
|
||||||
|
|
||||||
|
# Determine NPC count
|
||||||
|
count = args.count
|
||||||
|
if count is None:
|
||||||
|
try:
|
||||||
|
count = int(input("Enter number of NPCs to generate: "))
|
||||||
|
except ValueError:
|
||||||
|
sys.exit("❌ Invalid number entered.")
|
||||||
|
|
||||||
|
generator.create_npcs(campaign_name, count)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
@ -1,2 +1,9 @@
|
||||||
|
certifi==2025.4.26
|
||||||
|
chardet==3.0.4
|
||||||
|
charset-normalizer==3.4.2
|
||||||
|
Faker==37.1.0
|
||||||
|
idna==2.10
|
||||||
python-dotenv==0.12.0
|
python-dotenv==0.12.0
|
||||||
requests==2.23.0
|
requests==2.32.3
|
||||||
|
tzdata==2025.2
|
||||||
|
urllib3==1.26.20
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue