Skip to content

Codixverse/Go-GiveawayBot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go Giveaway Bot

A powerful Discord bot built with Go for managing giveaways with MongoDB persistence. Start, manage, and reroll giveaways effortlessly with automatic winner selection and reply-based announcements.

Repository: https://github.com/iimazin11/Go-GiveawayBot

🚀 Features

  • Create Giveaways - Start giveaways with custom prizes, winner count, and flexible duration
  • Button-Based Entry - Users join via emoji button (🎉), no reactions needed
  • Automatic End Times - Giveaways auto-end with goroutines at specified times
  • Startup Reconciliation - Missed giveaways from downtime are auto-ended on restart
  • Winner Selection - Random winner selection with customizable count
  • Reroll Support - Select new winners for ended giveaways
  • Paginated List - View all giveaways with pagination (5 per page, newest first)
  • MongoDB Persistence - All data stored reliably in MongoDB
  • Reply Announcements - Winner messages reply directly to giveaway embed
  • Permission Checks - MANAGE_GUILD permission required for admin commands

📋 Quick Start

Prerequisites

  • Go 1.25+
  • MongoDB Atlas account (free tier works)
  • Discord bot token
  • Administrator role in your Discord server

Installation

  1. Clone the repository

    git clone https://github.com/iimazin11/Go-GiveawayBot.git
    cd "Go-GiveawayBot"
  2. Install dependencies

    go mod download
  3. Create .env file in the project root:

    TOKEN=your_discord_bot_token
    MONGO=mongodb+srv://username:[email protected]/GiveawayGo?retryWrites=true&w=majority
    
  4. Run the bot

    go run .

The bot will connect to Discord and MongoDB. You should see: Bot is online: Go App#XXXX

🎮 Commands

/gstart - Start a Giveaway

/gstart prize:"iPhone 15" winners:1 duration:"1d"

Parameters:

  • prize (required) - Prize description
  • winners (required) - Number of winners to select
  • duration (required) - Duration format: 1s, 30m, 2h, 1d

Duration Examples:

  • 1s = 1 second
  • 30m = 30 minutes
  • 2h = 2 hours
  • 1d = 1 day

After creation, users click the 🎉 button to join. The giveaway automatically ends at the specified time.

/gend - End a Giveaway

/gend giveaway_id:message_id_or_database_id

Parameters:

  • giveaway_id (required) - Message ID or database ID of the giveaway

Manually ends a giveaway, selects winners randomly, and posts winner announcement as a reply to the giveaway embed.

/greroll - Reroll Winners

/greroll giveaway_id:message_id_or_database_id

Parameters:

  • giveaway_id (required) - Message ID or database ID of the ended giveaway

Selects new random winners and posts reroll announcement with format:

@admin rerolled the giveaway! Congratulations @winner1, @winner2! [↗](message_link)

/glist - List All Giveaways

/glist

Displays all server giveaways paginated (5 per page), sorted by newest first. Use Previous/Next buttons to navigate through pages.

📁 Project Structure

Go Bot/
├── main.go                    # Bot initialization
├── go.mod                     # Go module dependencies
├── .env                       # Configuration (TOKEN, MONGO)
├── README.md                  # This file
├── db/
│   └── db.go                 # MongoDB connection
├── models/
│   └── giveaway.go           # Giveaway data structure
├── commands/
│   ├── general/
│   │   ├── commands.go       # Command registry
│   │   └── ping.go           # Ping command
│   └── giveaway/
│       ├── commands.go       # Giveaway command registry
│       ├── start.go          # /gstart implementation
│       ├── end.go            # /gend implementation
│       ├── reroll.go         # /greroll implementation
│       ├── list.go           # /glist implementation
│       ├── handlers.go       # Button handlers & AutoEndGiveaway
│       ├── pagination.go     # List pagination handlers
│       └── reconcile.go      # Startup reconciliation
└── events/
    ├── ready.go              # Bot ready event
    ├── interactionCreate.go  # Command & button routing
    └── messageReactionAdd.go # Reaction handler (no-op)

🔧 Configuration

Environment Variables (.env)

# Discord Bot Token (get from Discord Developer Portal)
TOKEN=your_bot_token_here

# MongoDB Connection String
MONGO=mongodb+srv://username:[email protected]/GiveawayGo?retryWrites=true&w=majority

MongoDB Setup

  1. Create account at MongoDB Atlas
  2. Create a free M0 cluster
  3. Add Network Access - whitelist your IP or use 0.0.0.0/0
  4. Create database user with password
  5. Get connection string and replace <password> with your password
  6. Add to .env as MONGO value

Discord Bot Setup

  1. Go to Discord Developer Portal
  2. Click "New Application"
  3. Go to "Bot" section and "Add Bot"
  4. Copy token and add to .env as TOKEN
  5. In "OAuth2" → "URL Generator":
    • Select scopes: bot, applications.commands
    • Select permissions: Send Messages, Read Message History, Manage Messages, Embed Links
  6. Copy generated URL, open in browser, and invite bot to your server

📊 How It Works

Giveaway Lifecycle

  1. Creation - Admin uses /gstart command

    • Giveaway created in MongoDB with status: "active"
    • Embed posted to channel with 🎉 button
    • Auto-end goroutine scheduled for end time
  2. Active Phase - Users click 🎉 button to join

    • User ID added to participants array in database
    • Embed updated with current entry count
    • User can click again to get leave option
  3. End Time - Bot automatically ends giveaway or admin uses /gend

    • Random winners selected from participants
    • Giveaway status changed to "ended"
    • Embed updated with ended color (#2F3136) and disabled button
    • Winner announcement posted as reply to embed
  4. Reroll - Admin uses /greroll on ended giveaway

    • New random winners selected
    • Reroll announcement posted as reply with format: @admin rerolled! Congratulations @winners! [↗](link)

Startup Reconciliation

When bot starts, ReconcileEndedGiveaways() automatically:

  • Queries database for active giveaways with endTime ≤ now
  • Calls AutoEndGiveaway() for each missed giveaway
  • Selects winners and posts announcements
  • Updates MongoDB with final state

This ensures no giveaways are lost if bot goes offline.

🎨 Embed Design

Active Giveaway

  • Color: #5865F2 (Discord Blurple)
  • Button: 🎉 emoji (Primary button)
  • Shows: Prize, Winners count, Entries count, End time

Ended Giveaway

  • Color: #2F3136 (Discord Dark Gray)
  • Button: 🎉 Ended (Secondary button, disabled)
  • Shows: Winners mentioned, Entries count, End time

🔐 Permissions

All giveaway commands require MANAGE_GUILD permission:

  • /gstart - Admins only
  • /gend - Admins only
  • /greroll - Admins only
  • /glist - Admins only
  • Join/Leave Buttons - Anyone

📚 Database Schema

{
  _id: ObjectId,
  prize: String,
  winners: Number,
  startTime: Date,
  endTime: Date,
  participants: [String],        // User IDs
  selectedWinners: [String],     // User IDs
  status: String,                // "active" or "ended"
  createdBy: String,             // User ID
  guildId: String,
  channelId: String,
  messageId: String,
  giveawayId: String
}

⚙️ Duration Parsing

Durations use format: <number><unit>

Format Meaning
1s 1 second
30m 30 minutes
2h 2 hours
1d 1 day
7d 7 days

Examples:

  • 1m = 1 minute
  • 15m = 15 minutes
  • 12h = 12 hours
  • 14d = 14 days

🐛 Troubleshooting

Bot Token Error

Error: "TOKEN not found in .env"

Solution:

  1. Verify .env file exists in project root directory
  2. Check TOKEN value is correct from Discord Developer Portal
  3. No spaces before/after the = sign
  4. Restart bot

MongoDB Connection Error

Error: "Error connecting to MongoDB"

Solutions:

  1. Verify MONGO URI in .env is correct
  2. Check IP whitelist in MongoDB Atlas (Security → Network Access)
  3. Verify database user password (encode special chars with URL encoding)
  4. Ensure cluster is running in Atlas dashboard

Commands Not Showing

Problem: Slash commands not visible in Discord

Solutions:

  1. Verify bot has applications.commands scope
  2. Restart bot with Ctrl+C then run again
  3. Type / in Discord and wait 2 seconds
  4. Check bot invite URL has correct permissions

Button Not Working

Problem: 🎉 button doesn't respond

Solutions:

  1. Ensure bot has "Send Messages" permission
  2. Check bot is running (check console)
  3. Message wasn't deleted
  4. Create new giveaway with /gstart

Giveaway Doesn't Auto-End

Problem: Giveaway passes end time but doesn't automatically end

Solutions:

  1. If bot was offline, restart bot to trigger reconciliation
  2. Manually end with /gend command_id
  3. Check MongoDB connection is active

📈 Performance

  • Supports 100+ concurrent giveaways
  • MongoDB Atlas free tier sufficient for small/medium servers
  • One goroutine per active giveaway
  • Efficient database indexing on timestamps

🚀 Deployment

Local Testing

go build -o gobot.exe
./gobot.exe

Production (Linux/VPS)

go build -o gobot
nohup ./gobot > bot.log 2>&1 &

Docker (Optional)

FROM golang:1.25
WORKDIR /app
COPY . .
RUN go build -o gobot
CMD ["./gobot"]

💡 Tips

  1. Test First - Create a test giveaway with 1 minute duration
  2. Monitor Logs - Check console output for errors
  3. Keep Bot Running - 24/7 uptime ensures auto-end works
  4. Verify Permissions - Admin must have MANAGE_GUILD permission
  5. Check Whitelist - MongoDB IP whitelist is a common issue

🤝 Contributing

See CONTRIBUTING.md for guidelines on:

  • Setting up development environment
  • Code style and standards
  • Submitting pull requests
  • Reporting issues

📄 License

MIT License - See LICENSE file


Getting Help

  1. Check logs - Error messages in console indicate the issue
  2. Verify .env - Most problems stem from incorrect TOKEN or MONGO
  3. Test connectivity - Ensure bot token and MongoDB URI are valid
  4. Restart bot - Often solves transient issues
  5. Check permissions - Verify bot has required Discord permissions

Quick Commands Reference

Command Usage Example
Start /gstart prize:"" winners:# duration:"" /gstart prize:"PS5" winners:2 duration:"1d"
End /gend giveaway_id: /gend giveaway_id:1097364528592633856
Reroll /greroll giveaway_id: /greroll giveaway_id:1097364528592633856
List /glist /glist

Built with ❤️ in Go

Repository: https://github.com/iimazin11/Go-GiveawayBot

About

This a Discord Giveaway Bot Made By Go Lang

Topics

Resources

License

Stars

Watchers

Forks

Languages