voidtheoryttv

i need a bot that tracks when people clock in and out like a time car and i need it to have buttons where people can click to clock in and out but i also need to have a couple buttons added where it say fto, gang, and swat and to track those times and put them on a spreadsheet or something

Kodari AI
KodariSep 18 at 1:58 am 1
TimeClockTracker
A Discord bot for tracking employee clock in/out times with interactive buttons. Users click Clock In or Clock Out to record their shifts, plus dedicated FTO, Gang, and SWAT buttons to track specialized duty times. All timestamps are logged to a CSV spreadsheet file for easy review and export. Includes command to view individual time logs and total hours worked.

Created a complete Discord time-clock bot with:

  • Persistent Clock In and Clock Out buttons

  • Assignment buttons for FTO, Gang, and SWAT

  • Automatic time tracking when switching assignments

  • SQLite database storage

  • /my_hours weekly summary command

  • /export_timesheet CSV export compatible with Excel and Google Sheets

  • /setup_timeclock command for posting the panel

  • .env token configuration

  • Setup documentation and dependency files

voidtheoryttv

okay so how do i set it up

Kodari AI
KodariSep 18 at 2:03 am 1

1. Install Python

Install Python 3.10 or newer from python.org.

During Windows installation, check “Add Python to PATH.”

Verify it:

Shell
python --version

2. Open the bot folder

Open Terminal, PowerShell, or Command Prompt in the folder containing:

  • bot.py

  • requirements.txt

  • .env.example

Example:

Shell
cd path/to/TimeClockTracker

3. Install dependencies

Shell
pip install -r requirements.txt

If pip does not work, use:

Shell
python -m pip install -r requirements.txt

4. Create the Discord bot

  1. Click New Application.

  2. Name the application.

  3. Open the Bot tab.

  4. Click Add Bot.

  5. Click Reset Token and copy the token.

Keep the token private. Anyone with it can control your bot.

5. Invite the bot to your server

In the Developer Portal:

  1. Open OAuth2 → URL Generator.

  2. Select these scopes:

    • bot

    • applications.commands

  3. Select these bot permissions:

    • View Channels

    • Send Messages

    • Embed Links

    • Attach Files

    • Read Message History

  4. Copy the generated URL.

  5. Open the URL and select your Discord server.

You will need permission to manage the server in order to invite the bot.

6. Configure the token

Create a copy of .env.example named .env.

On Windows PowerShell:

Powershell
Copy-Item .env.example .env

On macOS/Linux:

Shell
cp .env.example .env

Open .env and replace the placeholder:

Env
DISCORD_TOKEN=your_actual_bot_token_here
DATABASE_PATH=timeclock.db
DISPLAY_TIMEZONE=UTC

For example, to display times using Eastern Time:

Env
DISPLAY_TIMEZONE=America/New_York

Do not upload .env to GitHub or share it.

7. Start the bot

Shell
python bot.py

You should see a message showing that the bot is logged in.

The bot must remain running for the buttons and commands to work.

8. Post the time-clock panel

In your Discord server, run:

Plain Text
/setup_timeclock

The command is restricted to members with Manage Server permission.

The panel will contain buttons for:

  • Clock In

  • Clock Out

  • General

  • FTO

  • Gang

  • SWAT

Users must clock in before selecting an assignment. Switching assignments closes the previous time segment and starts tracking the new one.

9. View and export hours

Users can run:

Plain Text
/my_hours

Server managers can run:

Plain Text
/export_timesheet

The bot will upload a timesheet.csv file. You can open that file with:

  • Microsoft Excel

  • Google Sheets

  • LibreOffice Calc

The database is automatically created as:

Plain Text
timeclock.db

Keep that file backed up because it contains the recorded time data.

voidtheoryttv

im very new to this so idk how to do any of this

Kodari AI
KodariSep 18 at 2:05 am 1

No problem — we’ll do this one small step at a time. I’ll assume you’re using Windows. If you’re on Mac, tell me and I’ll adjust the instructions.

Step 1: Install Python

  1. Click Download Python.

  2. Open the downloaded installer.

  3. Before clicking anything else, check:

    Add Python.exe to PATH

  4. Click Install Now.

  5. When it finishes, restart your computer.

Step 2: Find the bot folder

You should have a folder containing files similar to:

Plain Text
bot.py
requirements.txt
.env.example
README.md

Put that folder somewhere easy to find, such as your Desktop.

For example:

Plain Text
Desktop
└── TimeClockTracker
    ├── bot.py
    ├── requirements.txt
    └── .env.example

Step 3: Open the folder in PowerShell

  1. Open the TimeClockTracker folder.

  2. Click an empty area inside the folder.

  3. Hold Shift and right-click.

  4. Choose Open PowerShell window here or Open in Terminal.

A black or blue window should appear.

Type this command and press Enter:

Powershell
python --version

You should see something like:

Plain Text
Python 3.12.4

If you see an error saying Python is not recognized, send me that error before continuing.

Step 4: Install the bot’s requirements

In the same PowerShell window, type:

Powershell
python -m pip install -r requirements.txt

Wait for it to finish. Some warnings are okay, but do not continue if you see a red error.

Step 5: Create your Discord bot

  1. Sign in with your Discord account.

  2. Click New Application.

  3. Give it a name, such as Time Clock.

  4. Click Create.

  5. Select Bot on the left.

  6. Click Add Bot.

  7. Click Reset Token.

  8. Copy the token somewhere temporarily.

Do not send the token to me or anyone else. It is like the bot’s password.

Step 6: Create the bot’s settings file

Inside your bot folder:

  1. Right-click .env.example.

  2. Choose Copy.

  3. Right-click an empty area and choose Paste.

  4. Rename the copy to:

Plain Text
.env

Make sure it is not named:

Plain Text
.env.txt

Open .env with Notepad. It should look similar to:

Env
DISCORD_TOKEN=your_actual_bot_token_here
DATABASE_PATH=timeclock.db
DISPLAY_TIMEZONE=UTC

Replace only the token part:

Env
DISCORD_TOKEN=paste_your_token_here

For example:

Env
DISCORD_TOKEN=abc123_your_real_token
DATABASE_PATH=timeclock.db
DISPLAY_TIMEZONE=America/New_York

Do not add quotation marks around the token.

Step 7: Invite the bot to your server

In the Discord Developer Portal:

  1. Select your application.

  2. Go to OAuth2 → URL Generator.

  3. Check:

    • bot

    • applications.commands

  4. Under bot permissions, check:

    • View Channels

    • Send Messages

    • Embed Links

    • Attach Files

    • Read Message History

  5. Copy the generated URL at the bottom.

  6. Open it in your browser.

  7. Choose your Discord server.

  8. Click Continue and Authorize.

You need to own the server or have permission to manage it.

Step 8: Start the bot

Go back to the PowerShell window inside the bot folder and run:

Powershell
python bot.py

If everything works, you should see a message saying the bot is logged in or ready.

Leave this window open. The bot will stop working if you close it.

Step 9: Post the clock-in panel

In your Discord server, type:

Plain Text
/setup_timeclock

The bot should post buttons for:

  • Clock In

  • Clock Out

  • General

  • FTO

  • Gang

  • SWAT

Users can then use those buttons to record their work time.

Start with Step 1. After installing Python, run:

Powershell
python --version

Then tell me exactly what appears on your screen, and I’ll guide you through the next step.

voidtheoryttv

this is what i see when i went to start the bot on step 8

1 image attached
Kodari AI
KodariSep 18 at 2:24 am 1

That error means the bot token is incorrect or expired. Your Python installation and bot code are working; Discord is rejecting the login token.

Fix it

1. Create a new token

  1. Open your Time Clock application.

  2. Click Bot on the left.

  3. Click Reset Token.

  4. Confirm it, then click Copy.

Do not send the token to me.

2. Update your .env file

In your CLOCKBOT folder, right-click the .env file and choose Open with → Notepad.

It should look like this:

Env
DISCORD_TOKEN=paste_the_new_token_here
DATABASE_PATH=timeclock.db
DISPLAY_TIMEZONE=UTC

Replace only the text after DISCORD_TOKEN=.

Important:

  • Do not use quotation marks.

  • Do not include spaces before or after the token.

  • Do not paste the Application ID, Public Key, or Client Secret.

  • Copy the token from the Bot page.

  • Make sure the file is named exactly .env, not .env.txt.

For example:

Env
DISCORD_TOKEN=abc123xyz456
DATABASE_PATH=timeclock.db
DISPLAY_TIMEZONE=UTC

3. Start the bot again

Save and close Notepad. In PowerShell, run:

Powershell
python bot.py

If it works, the bot should show that it is logged in or ready.

If you still get the same error, check whether the file is accidentally named .env.txt:

  1. Open the CLOCKBOT folder.

  2. Click View → Show → File name extensions.

  3. Confirm the filename is exactly:

Plain Text
.env

Also make sure there is only one line beginning with DISCORD_TOKEN=.

voidtheoryttv

okay it worked

Kodari AI
KodariSep 18 at 2:27 am 1

Great! The bot is now online.

Next step: post the clock-in panel

  1. Go to your Discord server.

  2. Choose the channel where you want the time-clock buttons.

  3. Type:

Plain Text
/setup_timeclock
  1. Press Enter.

The bot should post a panel with buttons for:

  • Clock In

  • Clock Out

  • General

  • FTO

  • Gang

  • SWAT

Test it

  1. Click Clock In.

  2. Click FTO, Gang, or SWAT to track that assignment.

  3. When finished, click Clock Out.

The bot will save the times automatically. Keep the PowerShell window open while the bot is being used.

To view your hours, use:

Plain Text
/my_hours

To export everyone’s times as a spreadsheet file, a server manager can use:

Plain Text
/export_timesheet
voidtheoryttv

okay i need it to where when someone clocks in and out it gets put on a spreadsheet and not like this

1 image attached
Kodari AI
KodariSep 18 at 2:33 am 2

I’ll change the bot from generating a downloadable CSV to automatically adding each completed clock-in/out record to a real Google Sheet. I’ll first check the current bot structure, then update the code and setup steps.

Implementation plan:

  1. Add a Google Sheets connector that creates the worksheet header and appends one readable row for every completed assignment segment.

  2. Connect clock-out and FTO/Gang/SWAT switches to that connector without blocking Discord.

  3. Add Google configuration fields and protect the credentials file.

  4. Update the beginner setup guide so the bot writes directly to a Google Sheet instead of only producing a CSV download.

I changed the bot so completed time segments are automatically added as rows to a real Google Sheet.

It will record:

  • Employee name

  • Discord user ID

  • Assignment

  • Clock-in time

  • Clock-out time

  • Total hours

  • Duration

  • Discord server

It adds a row when someone:

  • Clicks Clock Out

  • Switches from General to FTO, Gang, or SWAT

  • Switches between assignments

What you need to do

1. Update the bot files

Replace the old project files with the updated files I provided.

Then open PowerShell in the bot folder and run:

Powershell
python -m pip install -r requirements.txt

2. Create a Google Sheet

Go to:

Create a blank spreadsheet.

Copy the spreadsheet ID from the URL. For example:

Plain Text
https://docs.google.com/spreadsheets/d/ABC123456/edit

The spreadsheet ID is:

Plain Text
ABC123456

3. Create Google access for the bot

  1. Create a project.

  2. Search for Google Sheets API.

  3. Click Enable.

  4. Go to IAM & Admin → Service Accounts.

  5. Click Create Service Account.

  6. Name it time-clock-bot.

  7. Open the service account after creating it.

  8. Select Keys → Add Key → Create new key → JSON.

  9. Download the JSON file.

  10. Rename it:

Plain Text
service-account.json
  1. Place it in the same folder as bot.py.

Do not send this file to anyone.

4. Share the spreadsheet with the bot

Open service-account.json with Notepad.

Find the line that looks like:

JSON
"client_email": "time-clock-bot@some-project.iam.gserviceaccount.com"

Copy that email address.

Open your Google Sheet, click Share, paste that email address, and give it Editor access.

5. Update .env

Open your .env file and make it look like this:

Env
DISCORD_TOKEN=your_discord_bot_token
DATABASE_PATH=timeclock.db
DISPLAY_TIMEZONE=America/New_York
GOOGLE_SERVICE_ACCOUNT_FILE=service-account.json
GOOGLE_SHEET_ID=your_google_sheet_id
GOOGLE_WORKSHEET_NAME=Time Entries

Replace:

Plain Text
your_google_sheet_id

with the ID copied from your spreadsheet URL.

6. Restart the bot

Stop the bot with:

Plain Text
Ctrl + C

Then start it again:

Powershell
python bot.py

The bot will automatically create a worksheet tab called Time Entries with column headings.

The existing /export_timesheet command is still available as a backup, but new clock records will now be added directly to Google Sheets.

voidtheoryttv

wheres the new files you made

Kodari AI
KodariSep 18 at 2:34 am 1

The updated files are in the same bot project folder you used before—your CLOCKBOT folder. The files that were changed are:

Plain Text
CLOCKBOT
├── bot.py
├── requirements.txt
├── .env.example
├── .gitignore
└── README.md

However, the Google file was not created automatically. You still need to download and add this file yourself:

Plain Text
service-account.json

It must be placed beside bot.py:

Plain Text
CLOCKBOT
├── bot.py
├── requirements.txt
├── .env
├── service-account.json
└── timeclock.db

If you open your CLOCKBOT folder and the files still show the old version, the updated files were not transferred to your computer. In that case, tell me what files you currently see in the folder, and I’ll help you update them manually.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 545
bot.py
import csv
import asyncio
import io
import logging
import os
import sqlite3
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

import discord
import gspread
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
from gspread.exceptions import WorksheetNotFound


load_dotenv()

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("timeclock")


def utc_now() -> datetime:
    return datetime.now(timezone.utc)


def to_iso(value: datetime) -> str:
    return value.astimezone(timezone.utc).isoformat()


def from_iso(value: str) -> datetime:
    return datetime.fromisoformat(value).astimezone(timezone.utc)


def format_duration(seconds: float) -> str:
    total_minutes = max(0, int(seconds // 60))
    return f"{total_minutes // 60}h {total_minutes % 60:02d}m"


SHEET_HEADERS = [
    "Server",
    "Server ID",
    "Employee",
    "Discord User ID",
    "Assignment",
    "Clock In",
    "Clock Out",
    "Hours",
    "Duration",
]


class GoogleSheetsLogger:
    def __init__(
        self,
        credentials_file: str,
        spreadsheet_id: str,
        worksheet_name: str,
        display_timezone: ZoneInfo,
    ):
        if not credentials_file or not spreadsheet_id:
            raise RuntimeError(
                "Google Sheets is not configured. Set GOOGLE_SERVICE_ACCOUNT_FILE "
                "and GOOGLE_SHEET_ID in .env."
            )
        self.display_timezone = display_timezone
        try:
            client = gspread.service_account(filename=credentials_file)
            spreadsheet = client.open_by_key(spreadsheet_id)
            try:
                worksheet = spreadsheet.worksheet(worksheet_name)
            except WorksheetNotFound:
                worksheet = spreadsheet.add_worksheet(
                    title=worksheet_name, rows=1000, cols=len(SHEET_HEADERS)
                )
            if not worksheet.row_values(1):
                worksheet.append_row(SHEET_HEADERS, value_input_option="USER_ENTERED")
        except Exception as exc:
            raise RuntimeError(
                "Could not connect to Google Sheets. Check the service account file, "
                "sheet ID, and that the sheet is shared with the service account email."
            ) from exc
        self.worksheet = worksheet

    def append_session(
        self, server_name: str, server_id: int, session, ended: datetime
    ) -> None:
        started = from_iso(session["started_at"])
        seconds = max(0, (ended - started).total_seconds())
        start_display = started.astimezone(self.display_timezone).strftime(
            "%Y-%m-%d %H:%M:%S %Z"
        )
        end_display = ended.astimezone(self.display_timezone).strftime(
            "%Y-%m-%d %H:%M:%S %Z"
        )
        self.worksheet.append_row(
            [
                server_name,
                str(server_id),
                session["user_name"],
                str(session["user_id"]),
                session["assignment"],
                start_display,
                end_display,
                f"{seconds / 3600:.2f}",
                format_duration(seconds),
            ],
            value_input_option="USER_ENTERED",
        )


class TimeClockDatabase:
    def __init__(self, path: str):
        self.connection = sqlite3.connect(path)
        self.connection.row_factory = sqlite3.Row
        self.connection.execute("PRAGMA journal_mode=WAL")
        self.connection.execute(
            """
            CREATE TABLE IF NOT EXISTS sessions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                guild_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                user_name TEXT NOT NULL,
                assignment TEXT NOT NULL,
                started_at TEXT NOT NULL,
                ended_at TEXT
            )
            """
        )
        self.connection.execute(
            "CREATE INDEX IF NOT EXISTS idx_active_user ON sessions(guild_id, user_id, ended_at)"
        )
        self.connection.commit()

    def active_session(self, guild_id: int, user_id: int):
        return self.connection.execute(
            """
            SELECT * FROM sessions
            WHERE guild_id = ? AND user_id = ? AND ended_at IS NULL
            ORDER BY id DESC LIMIT 1
            """,
            (guild_id, user_id),
        ).fetchone()

    def clock_in(self, guild_id: int, user_id: int, user_name: str):
        if self.active_session(guild_id, user_id):
            return None
        now = utc_now()
        self.connection.execute(
            """
            INSERT INTO sessions
                (guild_id, user_id, user_name, assignment, started_at)
            VALUES (?, ?, ?, 'General', ?)
            """,
            (guild_id, user_id, user_name, to_iso(now)),
        )
        self.connection.commit()
        return now

    def clock_out(self, guild_id: int, user_id: int):
        session = self.active_session(guild_id, user_id)
        if not session:
            return None
        now = utc_now()
        self.connection.execute(
            "UPDATE sessions SET ended_at = ? WHERE id = ?",
            (to_iso(now), session["id"]),
        )
        self.connection.commit()
        return session, now

    def switch_assignment(
        self, guild_id: int, user_id: int, user_name: str, assignment: str
    ):
        current = self.active_session(guild_id, user_id)
        if not current:
            return None
        now = utc_now()
        self.connection.execute(
            "UPDATE sessions SET ended_at = ? WHERE id = ?",
            (to_iso(now), current["id"]),
        )
        self.connection.execute(
            """
            INSERT INTO sessions
                (guild_id, user_id, user_name, assignment, started_at)
            VALUES (?, ?, ?, ?, ?)
            """,
            (guild_id, user_id, user_name, assignment, to_iso(now)),
        )
        self.connection.commit()
        return current, now

    def user_summary(self, guild_id: int, user_id: int, since: datetime):
        rows = self.connection.execute(
            """