22 Commits

Author SHA1 Message Date
minori 7a8b5eafb1 deps: update eslint to 10.0.0
Node.js CI / CI (pull_request) Failing after 21s
Security Scan and Upload / Security & DefectDojo Upload (pull_request) Successful in 1m25s
2026-02-17 07:04:18 -08:00
minori 1e4abfb8db deps: update eslint to 9.39.2
Node.js CI / CI (pull_request) Successful in 23s
Security Scan and Upload / Security & DefectDojo Upload (pull_request) Successful in 1m13s
2026-02-04 08:20:08 -08:00
hikari fd938a2421 docs: update feedback section to use support forum
Node.js CI / CI (push) Successful in 20s
Security Scan and Upload / Security & DefectDojo Upload (push) Successful in 1m15s
2026-01-26 12:32:14 -08:00
naomi 65b0dea112 feat: automated upload of .gitea/workflows/ci.yml
Node.js CI / CI (push) Successful in 21s
Security Scan and Upload / Security & DefectDojo Upload (push) Successful in 57s
2025-12-22 19:42:13 +01:00
naomi 5bc7fdca44 feat: automated upload of .gitea/workflows/ci.yml
Node.js CI / CI (push) Has been cancelled
Security Scan and Upload / Security & DefectDojo Upload (push) Has been cancelled
2025-12-22 19:35:40 +01:00
naomi 8e91337c7d feat: automated upload of .gitea/workflows/ci.yml
Security Scan and Upload / Security & DefectDojo Upload (push) Has been cancelled
Node.js CI / Lint and Test (push) Has been cancelled
2025-12-22 19:25:29 +01:00
naomi eee10906a9 feat: automated upload of .npmrc
Security Scan and Upload / Security & DefectDojo Upload (push) Has been cancelled
Node.js CI / Lint and Test (push) Has been cancelled
2025-12-22 19:16:21 +01:00
naomi 7bc42b5c39 feat: automated upload of .gitea/workflows/security.yml
Node.js CI / Lint and Test (push) Successful in 20s
Security Scan and Upload / Security & DefectDojo Upload (push) Successful in 1m2s
2025-12-18 03:08:15 +01:00
naomi 8cc9186af1 feat: automated upload of .gitea/workflows/security.yml
Node.js CI / Lint and Test (push) Successful in 22s
Security Scan and Upload / Security & DefectDojo Upload (push) Successful in 59s
2025-12-17 23:26:14 +01:00
naomi 404867f77e feat: automated upload of .gitea/workflows/security.yml
Node.js CI / Lint and Test (push) Successful in 22s
Security Scan / Security Audit (push) Failing after 5m3s
2025-12-12 03:37:59 +01:00
naomi 9b2ca482a2 feat: automated upload of .gitea/workflows/security.yml
Node.js CI / Lint and Test (push) Successful in 20s
Security Scan / Trivy Security Scan (push) Failing after 4m47s
2025-12-11 20:12:06 +01:00
naomi e779153d54 feat: add analytics
Node.js CI / Lint and Test (push) Successful in 37s
2025-10-08 15:23:40 -07:00
naomi 12fac9fbd1 fix: sonnet 4 in conversations
Code Analysis / SonarQube (push) Failing after 15s
Node.js CI / Lint and Test (push) Failing after 31s
2025-07-06 15:30:48 -07:00
naomi 7087a64861 feat: add to discord button
Code Analysis / SonarQube (push) Failing after 18s
Node.js CI / Lint and Test (push) Failing after 36s
2025-07-04 18:00:46 -07:00
naomi 02c763336c feat: avatar
Node.js CI / Lint and Test (push) Failing after 49s
Code Analysis / SonarQube (push) Failing after 1m7s
2025-05-22 19:32:32 -07:00
naomi 2b1e54ad2b feat: increase limit for history
Node.js CI / Lint and Test (push) Failing after 45s
Code Analysis / SonarQube (push) Failing after 1m0s
2025-05-22 15:15:25 -07:00
naomi 9eabdc9a29 fix: correct order for removing cleared content
Node.js CI / Lint and Test (push) Failing after 47s
Code Analysis / SonarQube (push) Failing after 1m5s
2025-05-22 15:13:43 -07:00
naomi b6350fbc74 fix: log when no response
Node.js CI / Lint and Test (push) Failing after 43s
Code Analysis / SonarQube (push) Failing after 1m1s
2025-05-22 15:12:13 -07:00
naomi e8e6b596ac fix: error logging
Node.js CI / Lint and Test (push) Failing after 44s
Code Analysis / SonarQube (push) Failing after 1m2s
2025-05-22 15:09:54 -07:00
naomi efc8f904ef feat: add ability to trigger clear message to reset the conversation history (#2)
Node.js CI / Lint and Test (push) Successful in 58s
Code Analysis / SonarQube (push) Failing after 50s
### Explanation

_No response_

### Issue

_No response_

### Attestations

- [ ] I have read and agree to the [Code of Conduct](https://docs.nhcarrigan.com/community/coc/)
- [ ] I have read and agree to the [Community Guidelines](https://docs.nhcarrigan.com/community/guide/).
- [ ] My contribution complies with the [Contributor Covenant](https://docs.nhcarrigan.com/dev/covenant/).

### Dependencies

- [ ] I have pinned the dependencies to a specific patch version.

### Style

- [ ] I have run the linter and resolved any errors.
- [ ] My pull request uses an appropriate title, matching the conventional commit standards.
- [ ] My scope of feat/fix/chore/etc. correctly matches the nature of changes in my pull request.

### Tests

- [ ] My contribution adds new code, and I have added tests to cover it.
- [ ] My contribution modifies existing code, and I have updated the tests to reflect these changes.
- [ ] All new and existing tests pass locally with my changes.
- [ ] Code coverage remains at or above the configured threshold.

### Documentation

_No response_

### Versioning

_No response_

Reviewed-on: #2
Co-authored-by: Naomi Carrigan <commits@nhcarrigan.com>
Co-committed-by: Naomi Carrigan <commits@nhcarrigan.com>
2025-05-22 15:06:49 -07:00
naomi 04b18472ba feat: migrate to claude 4 (#1)
Node.js CI / Lint and Test (push) Successful in 1m4s
Code Analysis / SonarQube (push) Failing after 1m18s
### Explanation

_No response_

### Issue

_No response_

### Attestations

- [ ] I have read and agree to the [Code of Conduct](https://docs.nhcarrigan.com/community/coc/)
- [ ] I have read and agree to the [Community Guidelines](https://docs.nhcarrigan.com/community/guide/).
- [ ] My contribution complies with the [Contributor Covenant](https://docs.nhcarrigan.com/dev/covenant/).

### Dependencies

- [ ] I have pinned the dependencies to a specific patch version.

### Style

- [ ] I have run the linter and resolved any errors.
- [ ] My pull request uses an appropriate title, matching the conventional commit standards.
- [ ] My scope of feat/fix/chore/etc. correctly matches the nature of changes in my pull request.

### Tests

- [ ] My contribution adds new code, and I have added tests to cover it.
- [ ] My contribution modifies existing code, and I have updated the tests to reflect these changes.
- [ ] All new and existing tests pass locally with my changes.
- [ ] Code coverage remains at or above the configured threshold.

### Documentation

_No response_

### Versioning

_No response_

Reviewed-on: #1
Co-authored-by: Naomi Carrigan <commits@nhcarrigan.com>
Co-committed-by: Naomi Carrigan <commits@nhcarrigan.com>
2025-05-22 11:28:25 -07:00
naomi 010967ef55 chore: add sonar workflow
Node.js CI / Lint and Test (push) Successful in 1m17s
Code Analysis / SonarQube (push) Successful in 1m22s
2025-02-26 13:21:24 -08:00
14 changed files with 1035 additions and 520 deletions
+13 -4
View File
@@ -8,23 +8,32 @@ on:
- main
jobs:
lint:
name: Lint and Test
ci:
name: CI
runs-on: ubuntu-latest
steps:
- name: Checkout Source Files
uses: actions/checkout@v4
- name: Use Node.js v22
- name: Use Node.js v24
uses: actions/setup-node@v4
with:
node-version: 22
node-version: 24
- name: Setup pnpm
uses: pnpm/action-setup@v2
with:
version: 10
- name: Ensure Dependencies are Pinned
uses: naomi-lgbt/dependency-pin-check@main
with:
language: javascript
dev-dependencies: true
peer-dependencies: true
optional-dependencies: true
- name: Install Dependencies
run: pnpm install
+177
View File
@@ -0,0 +1,177 @@
name: Security Scan and Upload
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
schedule:
- cron: '0 0 * * 1'
workflow_dispatch:
jobs:
security-audit:
name: Security & DefectDojo Upload
runs-on: ubuntu-latest
continue-on-error: true
steps:
- name: Checkout code
uses: actions/checkout@v4
# --- AUTO-SETUP PROJECT ---
- name: Ensure DefectDojo Product Exists
env:
DD_URL: ${{ secrets.DD_URL }}
DD_TOKEN: ${{ secrets.DD_TOKEN }}
PRODUCT_NAME: ${{ github.repository }}
PRODUCT_TYPE_ID: 1
run: |
sudo apt-get install jq -y > /dev/null
echo "Checking connection to $DD_URL..."
# Check if product exists - capture HTTP code to debug connection issues
RESPONSE=$(curl --write-out "%{http_code}" --silent --output /tmp/response.json \
-H "Authorization: Token $DD_TOKEN" \
"$DD_URL/api/v2/products/?name=$PRODUCT_NAME")
# If response is not 200, print error
if [ "$RESPONSE" != "200" ]; then
echo "::error::Failed to query DefectDojo. HTTP Code: $RESPONSE"
cat /tmp/response.json
exit 1
fi
COUNT=$(cat /tmp/response.json | jq -r '.count')
if [ "$COUNT" = "0" ]; then
echo "Creating product '$PRODUCT_NAME'..."
curl -s -X POST "$DD_URL/api/v2/products/" \
-H "Authorization: Token $DD_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "name": "'"$PRODUCT_NAME"'", "description": "Auto-created by Gitea Actions", "prod_type": '$PRODUCT_TYPE_ID' }'
else
echo "Product '$PRODUCT_NAME' already exists."
fi
# --- 1. TRIVY (Dependencies & Misconfig) ---
- name: Install Trivy
run: |
sudo apt-get install wget apt-transport-https gnupg lsb-release -y
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | sudo apt-key add -
echo "deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main" | sudo tee -a /etc/apt/sources.list.d/trivy.list
sudo apt-get update && sudo apt-get install trivy -y
- name: Run Trivy (FS Scan)
run: |
trivy fs . --scanners vuln,misconfig --format json --output trivy-results.json --exit-code 0
- name: Upload Trivy to DefectDojo
env:
DD_URL: ${{ secrets.DD_URL }}
DD_TOKEN: ${{ secrets.DD_TOKEN }}
run: |
echo "Uploading Trivy results..."
# Generate today's date in YYYY-MM-DD format
TODAY=$(date +%Y-%m-%d)
HTTP_CODE=$(curl --write-out "%{http_code}" --output response.txt --silent -X POST "$DD_URL/api/v2/import-scan/" \
-H "Authorization: Token $DD_TOKEN" \
-F "active=true" \
-F "verified=true" \
-F "scan_type=Trivy Scan" \
-F "engagement_name=CI/CD Pipeline" \
-F "product_name=${{ github.repository }}" \
-F "scan_date=$TODAY" \
-F "auto_create_context=true" \
-F "file=@trivy-results.json")
if [[ "$HTTP_CODE" != "200" && "$HTTP_CODE" != "201" ]]; then
echo "::error::Upload Failed with HTTP $HTTP_CODE"
echo "--- SERVER RESPONSE ---"
cat response.txt
echo "-----------------------"
exit 1
else
echo "Upload Success!"
fi
# --- 2. GITLEAKS (Secrets) ---
- name: Install Gitleaks
run: |
wget -qO gitleaks.tar.gz https://github.com/gitleaks/gitleaks/releases/download/v8.18.0/gitleaks_8.18.0_linux_x64.tar.gz
tar -xzf gitleaks.tar.gz
sudo mv gitleaks /usr/local/bin/ && chmod +x /usr/local/bin/gitleaks
- name: Run Gitleaks
run: gitleaks detect --source . -v --report-path gitleaks-results.json --report-format json --no-git || true
- name: Upload Gitleaks to DefectDojo
env:
DD_URL: ${{ secrets.DD_URL }}
DD_TOKEN: ${{ secrets.DD_TOKEN }}
run: |
echo "Uploading Gitleaks results..."
TODAY=$(date +%Y-%m-%d)
HTTP_CODE=$(curl --write-out "%{http_code}" --output response.txt --silent -X POST "$DD_URL/api/v2/import-scan/" \
-H "Authorization: Token $DD_TOKEN" \
-F "active=true" \
-F "verified=true" \
-F "scan_type=Gitleaks Scan" \
-F "engagement_name=CI/CD Pipeline" \
-F "product_name=${{ github.repository }}" \
-F "scan_date=$TODAY" \
-F "auto_create_context=true" \
-F "file=@gitleaks-results.json")
if [[ "$HTTP_CODE" != "200" && "$HTTP_CODE" != "201" ]]; then
echo "::error::Upload Failed with HTTP $HTTP_CODE"
echo "--- SERVER RESPONSE ---"
cat response.txt
echo "-----------------------"
exit 1
else
echo "Upload Success!"
fi
# --- 3. SEMGREP (SAST) ---
- name: Install Semgrep (via pipx)
run: |
sudo apt-get install pipx -y
pipx install semgrep
# Add pipx binary path to GITHUB_PATH so next steps can see 'semgrep'
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Run Semgrep
run: semgrep scan --config=p/security-audit --config=p/owasp-top-ten --json --output semgrep-results.json . || true
- name: Upload Semgrep to DefectDojo
env:
DD_URL: ${{ secrets.DD_URL }}
DD_TOKEN: ${{ secrets.DD_TOKEN }}
run: |
echo "Uploading Semgrep results..."
TODAY=$(date +%Y-%m-%d)
HTTP_CODE=$(curl --write-out "%{http_code}" --output response.txt --silent -X POST "$DD_URL/api/v2/import-scan/" \
-H "Authorization: Token $DD_TOKEN" \
-F "active=true" \
-F "verified=true" \
-F "scan_type=Semgrep JSON Report" \
-F "engagement_name=CI/CD Pipeline" \
-F "product_name=${{ github.repository }}" \
-F "scan_date=$TODAY" \
-F "auto_create_context=true" \
-F "file=@semgrep-results.json")
if [[ "$HTTP_CODE" != "200" && "$HTTP_CODE" != "201" ]]; then
echo "::error::Upload Failed with HTTP $HTTP_CODE"
echo "--- SERVER RESPONSE ---"
cat response.txt
echo "-----------------------"
exit 1
else
echo "Upload Success!"
fi
+25
View File
@@ -0,0 +1,25 @@
# Package Manager Configuration
# Force pnpm usage - breaks npm/yarn intentionally
node-linker=pnpm
# Security: Disable all lifecycle scripts
ignore-scripts=true
enable-pre-post-scripts=false
# Security: Require packages to be 10+ days old before installation
minimum-release-age=14400
# Security: Verify package integrity hashes
verify-store-integrity=true
# Security: Enforce strict trust policies
trust-policy=strict
# Security: Strict peer dependency resolution
strict-peer-dependencies=true
# Performance: Use symlinks for node_modules
symlink=true
# Lockfile: Ensure lockfile is not modified during install
frozen-lockfile=false
+199
View File
@@ -0,0 +1,199 @@
---
title: Becca Lyria
---
Becca Lyria (hereinafter the "Application") is an AI-powered Discord bot that provides an interactive text-based role-playing game experience through direct messages. The bot utilizes Anthropic's Claude AI to create dynamic, personalized RPG adventures for users.
## 1. User Documentation
This section is for those interacting with a live instance of the Application.
### Overview
Becca Lyria is a user-installable Discord bot that transforms your DMs into an immersive text-based RPG experience. Acting as a wise mage named Becca with a cold and calculating personality, the bot serves as your personal dungeon master, weaving interactive stories that adapt to your choices and actions.
### Getting Started
1. **Installation**: [Add Becca Lyria to your Discord account](https://discord.com/oauth2/authorize?client_id=1343341112437248041)
2. **Subscription**: The bot requires an active subscription to use its features
3. **Start Playing**: Use the `/start` command to begin your adventure
### Available Commands
- **`/start`** - Start a new RPG scenario. Becca will create a fresh adventure and send it to your DMs
- **`/about`** - Learn more about the bot, including version information and useful links
- **`/clear`** - Clear your current adventure history to start fresh
### How to Play
1. Send Becca a `/start` command to begin a new adventure
2. Once the story begins in your DMs, simply respond naturally to continue the narrative
3. The bot maintains conversation history (up to 20 messages) to provide context-aware responses
4. Use `/clear` to reset your adventure history when you want to start over
5. The bot supports free-form text adventures - you can attempt any action you can imagine
### Features
- **AI-Powered Storytelling**: Powered by Claude 3.5 Sonnet for rich, dynamic narratives
- **Conversation Memory**: Maintains context from recent messages for coherent storytelling
- **Free-Form Gameplay**: No restrictive multiple choice options - express your actions naturally
- **Personalized Experience**: The bot adapts to your playstyle and incorporates your Discord display name
- **Privacy-Focused**: All gameplay happens in private DMs
### Subscription Model
Becca Lyria operates on a premium subscription model through Discord's monetization system. Users must have an active subscription to access the bot's RPG features.
## 2. Technical Documentation
This section is for those interested in running their own instance of the Application.
### Architecture Overview
Becca Lyria is built as a modern Discord bot using TypeScript and several key technologies:
**Core Technologies:**
- **Node.js/TypeScript**: Main runtime and development language
- **Discord.js**: Discord API interaction library
- **Anthropic SDK**: Integration with Claude AI models
- **Fastify**: Web server for health monitoring
- **PNPM**: Package management
**AI Integration:**
- **Provider**: Anthropic Claude (claude-3-5-sonnet-latest for conversations, claude-sonnet-4-20250514 for story starts)
- **Context Management**: Maintains up to 20 messages of conversation history
- **Personality System**: Configurable personality traits for consistent character behavior
### Project Structure
```
src/
├── index.ts # Main entry point and Discord client setup
├── commands/ # Slash command definitions
│ ├── about.ts
│ ├── clear.ts
│ └── start.ts
├── config/
│ └── personality.ts # AI personality configuration
├── events/
│ └── message.ts # Direct message event handling
├── modules/ # Command implementation logic
│ ├── about.ts
│ ├── clear.ts
│ └── start.ts
├── server/
│ └── serve.ts # Health monitoring web server
└── utils/ # Utility functions
├── ai.ts # Anthropic client configuration
├── calculateCost.ts # Usage cost tracking
├── isSubscribed.ts # Subscription verification
├── logger.ts # Logging utility
└── replyToError.ts # Error handling
```
### Environment Variables
The application requires several environment variables:
- `DISCORD_TOKEN`: Discord bot token
- `AI_TOKEN`: Anthropic API key
- `LOG_TOKEN`: Logging service token (optional)
### Key Features Implementation
**Subscription System:**
- Integrates with Discord's premium features
- SKU ID: `1343347225698500744`
- Entitlement checking for both interactions and messages
- Special bypass for bot owner (ID: `465650873650118659`)
**Conversation Management:**
- Fetches last 20 messages from DM channel
- Supports history clearing with special `<Clear History>` marker
- Converts message history to Anthropic's message format
- Maintains role context (user vs assistant)
**Error Handling:**
- Comprehensive error logging with custom logger
- Graceful error responses to users
- Unhandled rejection and exception catching
**Cost Tracking:**
- Monitors AI usage with token counting
- Calculates costs based on Anthropic pricing (input: $3/1M tokens, output: $15/1M tokens)
- Logs usage statistics per user
### Development Setup
1. **Prerequisites**: Node.js, PNPM
2. **Installation**: `pnpm install`
3. **Build**: `pnpm run build`
4. **Development**: Configure environment variables in `dev.env`
5. **Production**: Configure environment variables in `prod.env`
6. **Start**: `pnpm start` (requires 1Password CLI for env injection)
### Deployment Considerations
- Web server runs on port 5010 for health checks
- Requires Discord bot permissions for DMs and message content
- Needs stable Anthropic API access
- Logging integration with nhcarrigan logging service
## 3. Legal Documentation
:::note
This section is coming soon!
:::
This section is for expansions to our legal policies specific to the Application.
## 4. Contributing Documentation
This section is for documentation related to contributing to the Application's codebase.
### Development Standards
**Code Quality:**
- TypeScript with strict configuration
- ESLint with @nhcarrigan/eslint-config
- Maximum function length limits enforced
- Comprehensive JSDoc documentation required
**Testing:**
- Vitest framework configured
- Istanbul coverage reporting
- Currently no tests implemented (placeholder exists)
**Licensing:**
- Licensed under Naomi's Public License
- Copyright held by Naomi Carrigan
- See LICENSE.md for full terms
### Contribution Process
1. **Issues**: Report bugs and request features through GitHub issues
2. **Pull Requests**: Fork, develop, and submit PRs for review
3. **Code Review**: All changes require review before merging
4. **Guidelines**: Follow established [contributing guidelines](CONTRIBUTING.md)
5. **Conduct**: Adhere to [Code of Conduct](CODE_OF_CONDUCT.md)
### Development Workflow
**Commands:**
- `pnpm run build`: Compile TypeScript to production JavaScript
- `pnpm run lint`: Run ESLint with zero warnings tolerance
- `pnpm run test`: Run test suite (currently placeholder)
- `pnpm start`: Start production build with environment injection
**Architecture Patterns:**
- Event-driven Discord bot architecture
- Modular command system with separate definition and implementation
- Utility-first approach for common functionality
- Separation of concerns between commands, events, and business logic
### Contact Information
- **Chat Server**: [http://chat.nhcarrigan.com](http://chat.nhcarrigan.com)
- **Email**: contact@nhcarrigan.com
- **Source Code**: [https://git.nhcarrigan.com/nhcarrigan/becca-lyria](https://git.nhcarrigan.com/nhcarrigan/becca-lyria)
- **Documentation**: [https://docs.nhcarrigan.com/](https://docs.nhcarrigan.com/)
+2 -2
View File
@@ -4,11 +4,11 @@ Becca is a user-installable bot that allows you to play a text-based role-playin
## Live Version
[Add her to your account](https://discord.com/oauth2/authorize?client_id=1338596130207957035)!
[Add her to your account](https://discord.com/oauth2/authorize?client_id=1343341112437248041)!
## Feedback and Bugs
If you have feedback or a bug report, please feel free to open an issue!
If you have feedback or a bug report, please [log a ticket on our forum](https://support.nhcarrigan.com).
## Contributing
+3
View File
@@ -0,0 +1,3 @@
DISCORD_TOKEN="op://Environment Variables - Development/Naomi Dev Bot/token"
AI_TOKEN="op://Environment Variables - Development/Naomi Dev Bot/ai token"
LOG_TOKEN="op://Environment Variables - Naomi/Alert Server/api_auth"
+11 -10
View File
@@ -14,18 +14,19 @@
"author": "Naomi Carrigan",
"license": "See license in LICENSE.md",
"devDependencies": {
"@nhcarrigan/eslint-config": "5.1.0",
"@nhcarrigan/eslint-config": "5.2.0",
"@nhcarrigan/typescript-config": "4.0.0",
"@types/node": "22.13.1",
"@vitest/coverage-istanbul": "3.0.5",
"eslint": "9.20.0",
"typescript": "5.7.3",
"vitest": "3.0.5"
"@types/node": "22.15.21",
"@vitest/coverage-istanbul": "3.1.4",
"eslint": "10.0.0",
"typescript": "5.8.3",
"vitest": "3.1.4"
},
"dependencies": {
"@anthropic-ai/sdk": "0.36.3",
"@nhcarrigan/logger": "1.0.0",
"discord.js": "14.18.0",
"fastify": "5.2.1"
"@anthropic-ai/sdk": "0.52.0",
"@nhcarrigan/discord-analytics": "0.0.6",
"@nhcarrigan/logger": "1.1.1",
"discord.js": "14.19.3",
"fastify": "5.3.3"
}
}
+480 -490
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import {
ApplicationIntegrationType,
SlashCommandBuilder,
InteractionContextType,
} from "discord.js";
const command = new SlashCommandBuilder().
setContexts(
InteractionContextType.BotDM,
InteractionContextType.Guild,
InteractionContextType.PrivateChannel,
).
setIntegrationTypes(ApplicationIntegrationType.UserInstall).
setName("clear").
setDescription("Clear your current adventure so you can start a new one!");
// eslint-disable-next-line no-console -- We don't need our logger here as this never runs in production.
console.log(JSON.stringify(command.toJSON()));
+34 -13
View File
@@ -14,13 +14,14 @@ import { personality } from "../config/personality.js";
import { ai } from "../utils/ai.js";
import { calculateCost } from "../utils/calculateCost.js";
import { isSubscribedMessage } from "../utils/isSubscribed.js";
import { logger } from "../utils/logger.js";
import type { MessageParam } from "@anthropic-ai/sdk/resources/index.js";
/**
* Handles the Discord message event.
* @param message - The message payload from Discord.
*/
// eslint-disable-next-line max-lines-per-function -- We're off by one bloody line.
// eslint-disable-next-line max-lines-per-function, max-statements, complexity -- We're off by one bloody line.
export const onMessage = async(message: Message): Promise<void> => {
try {
if (message.channel.type !== ChannelType.DM) {
@@ -33,22 +34,34 @@ export const onMessage = async(message: Message): Promise<void> => {
if (!subbed) {
return;
}
const history = await message.channel.messages.fetch({ limit: 6 });
const context: Array<MessageParam>
= history.reverse().map((messageInner) => {
return {
content: messageInner.content,
role:
messageInner.author.id === message.client.user.id
? "assistant"
: "user",
};
const historyRequest = await message.channel.messages.fetch({ limit: 20 });
const history = [ ...historyRequest.values() ];
const clearMessageIndex = history.findIndex((messageInner) => {
return (
messageInner.content === "<Clear History>"
&& messageInner.author.id === message.client.user.id
);
});
if (clearMessageIndex !== -1) {
// Remove the clear message and everything sent before it, which means everything after in the array because the array is backwards
history.splice(clearMessageIndex, history.length - clearMessageIndex);
}
const context: Array<MessageParam> = history.
reverse().
map((messageInner) => {
return {
content: messageInner.content,
role:
messageInner.author.id === message.client.user.id
? "assistant"
: "user",
};
});
const messages = await ai.messages.create({
// eslint-disable-next-line @typescript-eslint/naming-convention -- Required key format for SDK.
max_tokens: 3000,
max_tokens: 5000,
messages: context,
model: "claude-3-5-sonnet-latest",
model: "claude-sonnet-4-20250514",
system: `${personality} Provide a response to the user that continues the story. The user's name is ${message.author.displayName}`,
temperature: 1,
});
@@ -61,8 +74,16 @@ export const onMessage = async(message: Message): Promise<void> => {
response?.text ?? "There was an error. Please try again later.",
);
if (!response) {
await logger.log("info", `No response from AI, here's the payload: ${JSON.stringify(messages)}`);
}
await calculateCost(messages.usage, message.author.username);
await logger.metric("messages_processed", 1, { user: message.author.id });
} catch (error) {
await logger.error("message event", error instanceof Error
? error
: new Error(String(error)));
const button = new ButtonBuilder().
setLabel("Need help?").
setStyle(ButtonStyle.Link).
+9
View File
@@ -3,9 +3,11 @@
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { DiscordAnalytics } from "@nhcarrigan/discord-analytics";
import { Client, Events, GatewayIntentBits, Partials } from "discord.js";
import { onMessage } from "./events/message.js";
import { about } from "./modules/about.js";
import { clear } from "./modules/clear.js";
import { start } from "./modules/start.js";
import { instantiateServer } from "./server/serve.js";
import { logger } from "./utils/logger.js";
@@ -32,7 +34,10 @@ const client = new Client({
partials: [ Partials.Channel ],
});
const analytics = new DiscordAnalytics(client, logger);
client.on(Events.InteractionCreate, (interaction) => {
void analytics.logGatewayEvent(Events.InteractionCreate, { ...interaction });
if (interaction.isChatInputCommand()) {
switch (interaction.commandName) {
case "about":
@@ -41,6 +46,9 @@ client.on(Events.InteractionCreate, (interaction) => {
case "start":
void start(interaction);
break;
case "clear":
void clear(interaction);
break;
default:
void interaction.reply({
content: `I'm sorry, I don't know the ${interaction.commandName} command.`,
@@ -65,6 +73,7 @@ client.on(Events.EntitlementDelete, (entitlement) => {
client.on(Events.ClientReady, () => {
void logger.log("debug", "Bot is ready.");
analytics.startCron();
});
instantiateServer();
+47
View File
@@ -0,0 +1,47 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import {
MessageFlags,
type ChatInputCommandInteraction,
} from "discord.js";
import { isSubscribedInteraction } from "../utils/isSubscribed.js";
import { logger } from "../utils/logger.js";
import { replyToError } from "../utils/replyToError.js";
/**
* Sends a clear message in the DMs.
* @param interaction -- The interaction payload from Discord.
*/
export const clear = async(
interaction: ChatInputCommandInteraction,
): Promise<void> => {
try {
await interaction.deferReply({ flags: [ MessageFlags.Ephemeral ] });
const subbed = await isSubscribedInteraction(interaction);
if (!subbed) {
return;
}
const sent = await interaction.user.send({
content: "<Clear History>",
}).catch(() => {
return null;
});
await interaction.editReply({
content: sent
? "I have added a clear history marker to your DMs."
// eslint-disable-next-line stylistic/max-len -- This is a long string.
: "I was unable to send you a DM. Please ensure your privacy settings allow direct messages.",
});
} catch (error) {
await replyToError(interaction);
if (error instanceof Error) {
await logger.error("about command", error);
}
}
};
+7 -1
View File
@@ -11,6 +11,7 @@ import {
import { personality } from "../config/personality.js";
import { ai } from "../utils/ai.js";
import { calculateCost } from "../utils/calculateCost.js";
import { isSubscribedInteraction } from "../utils/isSubscribed.js";
import { logger } from "../utils/logger.js";
import { replyToError } from "../utils/replyToError.js";
@@ -24,13 +25,18 @@ export const start = async(
try {
await interaction.deferReply({ flags: [ MessageFlags.Ephemeral ] });
const subbed = await isSubscribedInteraction(interaction);
if (!subbed) {
return;
}
const messages = await ai.messages.create({
// eslint-disable-next-line @typescript-eslint/naming-convention -- Required key format for SDK.
max_tokens: 2000,
messages: [
{ content: "Please start a new story for me.", role: "user" },
],
model: "claude-3-5-sonnet-latest",
model: "claude-sonnet-4-20250514",
system: `${personality} The user has requested to start a new adventure. You should generate the first message for the game. The user's name is ${interaction.user.displayName}`,
});
+4
View File
@@ -19,8 +19,12 @@ const html = `<!DOCTYPE html>
<body>
<main>
<h1>Becca Lyria</h1>
<img src="https://cdn.nhcarrigan.com/new-avatars/becca-full.png" width="250" alt="Becca" />
<section>
<p>Bot to play RPGs on Discord!</p>
<a href="https://discord.com/oauth2/authorize?client_id=1343341112437248041" class="social-button discord-button" style="display: inline-block; background-color: #5865F2; color: white; padding: 10px 20px; text-decoration: none; border-radius: 4px; margin: 5px;">
<i class="fab fa-discord"></i> Add to Discord
</a>
</section>
<section>
<h2>Links</h2>