Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions .github/workflows/docker-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: Docker Publish

on:
push:
branches: [ "main" ]
tags: [ 'v*.*.*' ]
pull_request:
branches: [ "main" ]

env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}

jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Log into registry ${{ env.REGISTRY }}
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=semver,pattern={{version}}
type=sha

- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
20 changes: 20 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
FROM node:20-alpine

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
COPY package*.json ./

# Install only production dependencies
RUN npm ci --omit=dev

# Bundle app source
COPY . .

# Expose the health check port from src/app.js
EXPOSE 3000

# Start the bot
CMD [ "npm", "start" ]
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,36 @@ TitanBot offers a complete suite of tools for Discord server management and comm
For a detailed step-by-step setup guide, watch our comprehensive video tutorial:
[**TitanBot Setup Tutorial**](https://www.youtube.com/@TouchDisc)

## 🐳 Docker Deployment (Recommended)

TitanBot is fully containerized for easy deployment.

### Using Docker Compose

1. **Clone the repository:**
```bash
git clone https://github.com/codebymitch/TitanBot.git
cd TitanBot
```

2. **Configure environment variables:**
Create a `.env` file from `.env.example` and fill in your bot details and PostgreSQL credentials.

3. **Start the containers:**
```bash
docker-compose up -d
```

This will start both the bot and a persistent PostgreSQL database.

### Using GitHub Container Registry

The bot is automatically published to GitHub Container Registry on every push to main.

```bash
docker pull ghcr.io/codebymitch/titanbot:main
```

<a name="manual-installation-steps"></a>
## ⚙️ Manual Installation Steps

Expand Down
42 changes: 42 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
services:
bot:
build: .
container_name: titanbot
restart: unless-stopped
environment:
- NODE_ENV=production
- DISCORD_TOKEN=${DISCORD_TOKEN}
- CLIENT_ID=${CLIENT_ID}
- GUILD_ID=${GUILD_ID}
- DATABASE_URL=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
- PORT=3000
depends_on:
db:
condition: service_healthy
networks:
- titan-network

db:
image: postgres:15-alpine
container_name: titanbot-db
restart: unless-stopped
environment:
- POSTGRES_USER=${POSTGRES_USER:-titanbot}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-password}
- POSTGRES_DB=${POSTGRES_DB:-titanbot}
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 10s
timeout: 5s
retries: 5
networks:
- titan-network

networks:
titan-network:
driver: bridge

volumes:
postgres_data:
File renamed without changes.
129 changes: 66 additions & 63 deletions src/handlers/giveawayButtons.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
saveGiveaway,
isGiveawayEnded
} from '../utils/giveaways.js';
import { Mutex } from '../utils/mutex.js';
import {
selectWinners,
isUserRateLimited,
Expand Down Expand Up @@ -38,77 +39,79 @@ export const giveawayJoinHandler = {

recordUserInteraction(interaction.user.id, interaction.message.id);

const guildGiveaways = await getGuildGiveaways(client, interaction.guildId);
const giveaway = guildGiveaways.find(g => g.messageId === interaction.message.id);

if (!giveaway) {
throw new TitanBotError(
'Giveaway not found in database',
ErrorTypes.VALIDATION,
'This giveaway is no longer active.',
{ messageId: interaction.message.id, guildId: interaction.guildId }
);
}


const endedByTime = isGiveawayEnded(giveaway);
const endedByFlag = giveaway.ended || giveaway.isEnded;

if (endedByTime || endedByFlag) {
return interaction.reply({
embeds: [
errorEmbed(
'Giveaway Ended',
'This giveaway has already ended.'
)
],
flags: MessageFlags.Ephemeral
const lockKey = `giveaway:${interaction.message.id}`;
await Mutex.runExclusive(lockKey, async () => {
const guildGiveaways = await getGuildGiveaways(client, interaction.guildId);
const giveaway = guildGiveaways.find(g => g.messageId === interaction.message.id);

if (!giveaway) {
throw new TitanBotError(
'Giveaway not found in database',
ErrorTypes.VALIDATION,
'This giveaway is no longer active.',
{ messageId: interaction.message.id, guildId: interaction.guildId }
);
}

// Double check end status inside lock
const endedByTime = isGiveawayEnded(giveaway);
const endedByFlag = giveaway.ended || giveaway.isEnded;

if (endedByTime || endedByFlag) {
return interaction.reply({
embeds: [
errorEmbed(
'Giveaway Ended',
'This giveaway has already ended.'
)
],
flags: MessageFlags.Ephemeral
});
}

const participants = giveaway.participants || [];
const userId = interaction.user.id;

// Check if user already joined
if (participants.includes(userId)) {
return interaction.reply({
embeds: [
errorEmbed(
'Already Entered',
'You have already entered this giveaway! 🎉'
)
],
flags: MessageFlags.Ephemeral
});
}

// Atomically update participants
participants.push(userId);
giveaway.participants = participants;

await saveGiveaway(client, interaction.guildId, giveaway);

logger.debug(`User ${interaction.user.tag} joined giveaway ${interaction.message.id}`);

// Send response
const updatedEmbed = createGiveawayEmbed(giveaway, 'active');
const updatedRow = createGiveawayButtons(false);

await interaction.message.edit({
embeds: [updatedEmbed],
components: [updatedRow]
});
}

const participants = giveaway.participants || [];
const userId = interaction.user.id;


if (participants.includes(userId)) {
return interaction.reply({
await interaction.reply({
embeds: [
errorEmbed(
'Already Entered',
'You have already entered this giveaway! 🎉'
successEmbed(
'Success! You have entered the giveaway! 🎉',
`Good luck! There are now ${participants.length} entry/entries.`
)
],
flags: MessageFlags.Ephemeral
});
}


participants.push(userId);
giveaway.participants = participants;

await saveGiveaway(client, interaction.guildId, giveaway);

logger.debug(`User ${interaction.user.tag} joined giveaway ${interaction.message.id}`);


const updatedEmbed = createGiveawayEmbed(giveaway, 'active');
const updatedRow = createGiveawayButtons(false);

await interaction.message.edit({
embeds: [updatedEmbed],
components: [updatedRow]
});

await interaction.reply({
embeds: [
successEmbed(
'Success! You have entered the giveaway! 🎉',
`Good luck! There are now ${participants.length} entry/entries.`
)
],
flags: MessageFlags.Ephemeral
});

} catch (error) {
logger.error('Error in giveaway join handler:', error);
await handleInteractionError(interaction, error, {
Expand Down
25 changes: 21 additions & 4 deletions src/services/economyService.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,27 @@ class EconomyService {
receiverData.wallet = receiverNext;

try {
await Promise.all([
setEconomyData(client, guildId, senderId, senderData),
setEconomyData(client, guildId, receiverId, receiverData)
]);
// Step 1: Deduct from sender
await setEconomyData(client, guildId, senderId, senderData);

try {
// Step 2: Add to receiver
await setEconomyData(client, guildId, receiverId, receiverData);
} catch (receiverError) {
// ROLLBACK: Try to restore sender's money if receiver update fails
logger.error(`[ECONOMY_CRITICAL] Failed to credit receiver ${receiverId}. Attempting rollback for sender ${senderId}...`, receiverError);

senderData.wallet = walletBefore;
try {
await setEconomyData(client, guildId, senderId, senderData);
logger.info(`[ECONOMY_ROLLBACK] Successfully rolled back sender ${senderId} after receiver credit failure.`);
} catch (rollbackError) {
logger.error(`[ECONOMY_FATAL] ROLLBACK FAILED for sender ${senderId}! Data is now inconsistent.`, rollbackError);
// At this point, manual intervention is needed.
}

throw receiverError;
}

logger.info(`[ECONOMY_TRANSACTION] Money transferred`, {
type: 'transfer',
Expand Down
9 changes: 6 additions & 3 deletions src/services/giveawayService.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,9 @@ export function selectWinners(participants, winnerCount) {
return [];
}

// Ensure participants are unique
const uniqueParticipants = [...new Set(participants)];

if (!Number.isInteger(winnerCount) || winnerCount < 1) {
throw new TitanBotError(
'Invalid winner count for selection',
Expand All @@ -281,11 +284,11 @@ export function selectWinners(participants, winnerCount) {
);
}

const requested = Math.min(winnerCount, participants.length);
const requested = Math.min(winnerCount, uniqueParticipants.length);

try {

const shuffled = [...participants];
// Shuffle the unique participants using Fisher-Yates
const shuffled = [...uniqueParticipants];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
Expand Down
Loading
Loading