Python Playwright automation for booking badminton courts on Southampton Sport Gladstone Go.
- Target date = current
Europe/Londondate + 8 days - Primary wave:
account Ctargets17:00, whileaccount Aandaccount Btarget separate Courts at18:00; this aims for one17:00slot plus two18:00slots account Aandaccount Cuse Court order1 → 2 → 3 → 4;account Buses2 → 1 → 3 → 4and skips the exact18:00Court already selected by A- If the primary wave is incomplete, an unbooked account dynamically fills an
adjacent time. The scheduler first preserves a consecutive two-hour block,
then prefers a third
19:00slot over16:00, and finally uses the remaining configured fallback hours - If every configured fallback fails, each unbooked account expands from the
18:00anchor in the fixed order16:00 → 20:00 → 15:00 → 21:00until it succeeds or exhausts every Court. With multiple accounts, continuity and a second Court in the same hour take priority within this extended pool - Isolated
15:00,20:00, and21:00slots remain allowed final-resort bookings - All enabled accounts share time-and-Court claims so concurrent primary and fallback attempts do not race one another for the same slot
- When enabled preferences overlap, stable account-index order gives A first choice, then B, C, D, and subsequent positions
- Stop after the first slot that reaches
Booking Confirmed! - If the site explicitly rejects creation of its temporary slot reservation, release that internal slot claim, refresh and revalidate the target date, then continue to the next preferred Court
DRY_RUN=truenever clicks the final confirmation button- A transient stuck session is closed and re-created with a fresh login, with no more than three total session attempts per account
- The full booking wave starts at midnight. At
08:00and16:00, scheduled retry waves skip account slots already confirmed for that target date and run only the remaining enabled accounts. Earlier confirmations continue to guide time continuity and exact-Court coordination during those retries - Successful live checks detect when an account owner's previously recorded
booking date disappears from
My bookings. That email-and-date pair becomes a persistent cancellation opt-out, so every later automatic run skips only that account on that date. Failed logins and unavailable checks never create an opt-out
The script does not bypass CAPTCHA, MFA, verification pages, forbidden pages, or rate limits.
A downloaded clone does not include local secrets or machine setup:
.env.venv/logs/screenshots/- local
cron - local
systemdinstallation
Each user must complete local setup on their own Ubuntu machine.
Clone the repo:
git clone <YOUR_GITHUB_REPO_URL> badminton cd badminton
Create the environment and install dependencies:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python -m playwright install --with-deps chromiumIf Ubuntu says venv is missing:
sudo apt-get update
sudo apt-get install -y python3-venv
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python -m playwright install --with-deps chromiumCreate .env:
cp .env.example .env
Recommended production .env:
BOOKING_URL=https://soton.gladstonego.cloud/account GYM_USERNAME=[email protected] GYM_PASSWORD=your-password PRIMARY_BOOKING_ENABLED=true PRIMARY_BOOKING_TIME=18:00 TIMEZONE=Europe/London HEADLESS=true DRY_RUN=false TARGET_DATE_OVERRIDE= DEBUG_PAUSE_SECONDS= PREFERRED_TIMES=15:00,16:00,17:00,18:00,19:00,20:00,21:00 PREFERRED_COURTS=1,2,3,4 BOOKING_FALLBACK_TIMES=19:00,16:00,15:00 SECONDARY_BOOKING_ENABLED=false SECONDARY_GYM_USERNAME= SECONDARY_GYM_PASSWORD= SECONDARY_PREFERRED_TIMES=15:00,16:00,17:00,18:00,19:00,20:00,21:00 SECONDARY_PREFERRED_COURTS=2,1,3,4 SECONDARY_PRIMARY_BOOKING_TIME=18:00 TERTIARY_BOOKING_ENABLED=false TERTIARY_GYM_USERNAME= TERTIARY_GYM_PASSWORD= TERTIARY_PREFERRED_TIMES=15:00,16:00,17:00,18:00,19:00,20:00,21:00 TERTIARY_PREFERRED_COURTS=1,2,3,4 TERTIARY_PRIMARY_BOOKING_TIME=17:00 BOOKING_EMAIL_ENABLED=false BOOKING_EMAIL_REFERENCE_SCRIPT=/home/<YOUR_USERNAME>/send_ip_email.py
Keep credentials only in .env. Leave TARGET_DATE_OVERRIDE and DEBUG_PAUSE_SECONDS empty in production.
TIMEZONE: keepEurope/Londonin productionHEADLESS=true: run without a visible browserDRY_RUN=true: safe test mode, never confirms a bookingPREFERRED_TIMES: comma-separated search window times foraccount APREFERRED_COURTS: comma-separated court priority foraccount APRIMARY_BOOKING_ENABLED=false: disableaccount Awithout making it mandatoryPRIMARY_BOOKING_TIME,SECONDARY_PRIMARY_BOOKING_TIME,TERTIARY_PRIMARY_BOOKING_TIME: per-account first-choice hoursBOOKING_FALLBACK_TIMES: enabled fallback-hour pool and tie-break orderSECONDARY_BOOKING_ENABLED=true: enable an optional second booking account in parallelSECONDARY_GYM_USERNAME/SECONDARY_GYM_PASSWORD: credentials for the optional second accountSECONDARY_PREFERRED_TIMES: comma-separated search window times foraccount BSECONDARY_PREFERRED_COURTS: comma-separated court priority foraccount BTERTIARY_BOOKING_ENABLED=true: enableaccount Cin parallelTERTIARY_GYM_USERNAME/TERTIARY_GYM_PASSWORD: credentials foraccount CTERTIARY_PREFERRED_TIMES: comma-separated search window times foraccount CTERTIARY_PREFERRED_COURTS: comma-separated court priority foraccount CBOOKING_ACCOUNT_SLOT_COUNT: number of stable account positions currently shown by the control page. The page manages this automatically; account D and later positions use privateACCOUNT_D_*,ACCOUNT_E_*, and subsequent settings.BOOKING_EMAIL_ENABLED=true: enable the HTML booking report sent by the separate daily 14:00 London-time jobBOOKING_EMAIL_REFERENCE_SCRIPT: optional path to the existing IP email script; its sender, Gmail app password, and recipient are read without executing the scriptBOOKING_EMAIL_FROM,BOOKING_EMAIL_APP_PASSWORD,BOOKING_EMAIL_APP_PASSWORD_FILE,BOOKING_EMAIL_TO: optional explicit SMTP settings that take precedence over the reference script; the password-file option keeps the secret outside.env, and multiple recipients are comma-separatedBOOKING_EMAIL_TEST_TO: exactly one private recipient for manual report tests; test mode fails closed if this is empty or contains multiple addresses and never falls back toBOOKING_EMAIL_TOBOOKING_CANCELLATION_REMINDER_ENABLED=true: enable calendar invitations during the final one-hour free-cancellation window
Start the loopback-only control page:
source .venv/bin/activate
python booking_admin.py --print-urlOpen the private URL printed by the command. The page can:
- add account positions with the trailing plus button, up to the local safety limit, without renumbering existing positions;
- log out any account slot, immediately disabling it for future booking runs while moving its credentials into a private, monitor-only retention file;
- test replacement credentials against the Southampton Sport login and save them to an empty account slot only after a successful login;
- change each account's primary time;
- drag each account's Court priority into a new order;
- tick and drag the coordinated fallback-hour pool; and
- show the effective logic for the currently active account count.
Account indexes are stable. Logging out a middle position leaves its login card in place and does not rename later accounts. Logging out the final position removes only that trailing card; the plus button recreates the next index when a new participant joins. Booking logic, live verification, report ownership labels, and private cancellation reminders all use the same dynamic position list.
The server binds to 127.0.0.1 by default, never displays saved account
passwords, and atomically writes the local .env. Public deployments can be
protected with python booking_admin.py --set-password followed by the
--require-password runtime flag; the password hash is stored only in the
ignored .booking_admin_password file.
Do not expose the loopback port directly to a public or campus network. Changes
apply to the next booking run; an already running midnight browser session is not
modified. A path-based reverse proxy can set --base-path /another-name; the
default serves from the domain root.
At 13:55 Europe/London, booking_live.py logs in to every active account and
every monitor-only former account, then reads the badminton entries under
My bookings / Upcoming bookings. Logging out never leaves the account eligible
for a new booking. Its credentials are kept in the ignored, mode-0600
.retired_booking_accounts.json file for at least seven days and, when later,
until a successful live check confirms that all of its slots have ended. A failed
website or login check never triggers credential deletion. The verified snapshot
is stored locally in live_booking_state.json and is used by both the public web
table and the separate 14:00 daily report. Verified website data replaces the
corresponding future entries reconstructed from logs/, so a booking cancelled on
the website disappears from the summary. If one account or the school website
cannot be checked, that account falls back to its local records without blocking
the other accounts, and the summary includes an English unverified notice.
The daily email is sent at 14:00 Europe/London, not at the end of the midnight
booking run. Its opening section lists the slots that can be played on the report
date, while its table shows the schedule from the current date through the latest
attempted or confirmed booking date. Its normal table covers 15:00 through 19:00;
additional hours such as 20:00 or 21:00 are included when present in the live
website result.
Consecutive booked cells are light green and isolated booked cells are light
yellow. A target date where no account secured a slot remains visible, with an em
dash in every empty time cell. Keep booking logs if you want historical attempts
and fallback bookings to remain in the table.
Optional local corrections can be stored in manual_bookings.json. This runtime
data file is intentionally excluded from Git so personal booking history is not
published with the source code.
Each booked slot is displayed as plain Court N text. The report does not add a
calendar link, hidden event metadata, or calendar attachment to booked cells.
booking_cancellation_reminder.py scans confirmed bookings once per minute. At
five hours before a booked slot, it checks that account's Upcoming bookings again.
An entry that has already been cancelled is not reminded. At five hours before a
still-existing slot, it sends the booking owner a private RFC 5545 meeting
invitation titled Badminton Cancellation DDL (1h left). The transparent event
runs until four hours before the slot, so it represents the final one-hour
cancellation window without marking the recipient as busy. A successful booking
freezes the account email in its booking record; later account replacement or an
invalid unrelated legacy account cannot redirect or block that reminder. Legacy
records without a frozen owner use the currently configured account email only as
a fallback. Even when two accounts book different Courts at the same hour, each
receives a separate invitation containing only its own Court. The daily report
recipient list is never used for cancellation reminders. A local state file
prevents duplicates. If the website is temporarily unavailable, the reminder uses
the local record and explicitly says that it is unverified. If the computer was
offline at the five-hour point, the script catches up only while the four-hour
deadline has not passed.
The same rules apply to every target weekday. In the primary wave C targets
17:00, while A gets first choice at 18:00 and B targets a different 18:00
Court. B waits only for A's Court selection, not for A's full confirmation page.
If that ideal shape cannot be completed, unbooked accounts first use the editable
coordinated fallback pool to preserve a consecutive pair. Once that configured
pool is exhausted, they continue with the fixed 18:00-anchor expansion
16:00 → 20:00 → 15:00 → 21:00. A single account follows that order exactly.
With multiple accounts, the coordinator may choose an adjacent hour or a second
Court in the same hour ahead of the raw tie-break order. Shared claims prevent two
accounts from selecting the same time-and-Court slot.
The available-spaces result must match the requested date twice: the script only
clicks the exact dated result and then verifies the calendar URL's activityDate
in Europe/London before inspecting or clicking any slot. Logs include
millisecond timestamps. Full-page button/text diagnostics run after all preferred
times are exhausted (or during DRY_RUN), not before a successful production
booking attempt.
The preferred-time settings control the search window used before opening available
spaces. Configure enabled accounts with the complete 15:00 through 21:00
window; the coordinator, rather than the order of that comma-separated value,
chooses each account's primary and fallback attempts.
If the site adds a selected slot to the basket but does not reach the normal success page, the script preserves the original Court choice and completes the site's zero-price Basket → Checkout → Confirm flow. It verifies that the basket contains exactly one item matching the attempted Court and time before confirming. If the checkout becomes stuck, the account closes that browser session, logs in again, and reopens the unfinished basket before searching for another slot. If the basket item has expired or disappeared, the account resumes the incomplete phase in its normal Court order. This recovery remains bounded to three total sessions.
If Gladstone explicitly returns ACTIVITY-CALENDAR.ERRORS.CREATE-LEASE only after
the current final click, and a second state check finds neither a confirmation nor
an expected basket item, the script treats that submission as rejected. It releases
only that account's exact-slot claim, refreshes the calendar, revalidates the target
date, and continues in the configured Court and fallback-time order. A stale error
left by an earlier SPA action is not treated as a new rejection.
For page timeouts, stuck zero-price checkout controls, or other transient browser failures, the failed page and browser context are closed and the account logs in again. Each account gets at most three total sessions. CAPTCHA, rate limiting, and explicit login rejection still stop immediately rather than triggering repeated login attempts.
Dry run:
source .venv/bin/activate
DRY_RUN=true HEADLESS=false python book_badminton.pyReal run:
source .venv/bin/activate
HEADLESS=true DRY_RUN=false python book_badminton.pysource .venv/bin/activate
python -m pytest -q
python -m py_compile book_badminton.py booking_admin.py booking_daily_report.py booking_cancellation_reminder.py booking_live.py booking_retired.pyRecommended: cron
crontab -e
Add:
CRON_TZ=Europe/London 59 23 * * * /usr/bin/flock -n /tmp/badminton-booking.lock /bin/bash -lc 'sleep 30; cd /home/<YOUR_USERNAME>/badminton && /home/<YOUR_USERNAME>/badminton/.venv/bin/python -u /home/<YOUR_USERNAME>/badminton/book_badminton.py >> /home/<YOUR_USERNAME>/badminton/logs/cron-run.log 2>&1' 59 7,15 * * * /usr/bin/flock -n /tmp/badminton-booking.lock /bin/bash -lc 'sleep 30; cd /home/<YOUR_USERNAME>/badminton && /home/<YOUR_USERNAME>/badminton/.venv/bin/python -u /home/<YOUR_USERNAME>/badminton/book_badminton.py --retry-missing --prewarm-retry >> /home/<YOUR_USERNAME>/badminton/logs/cron-run.log 2>&1' 5 0 * * * /usr/bin/flock -n /tmp/badminton-live-booking.lock /bin/bash -lc 'cd /home/<YOUR_USERNAME>/badminton && /home/<YOUR_USERNAME>/badminton/.venv/bin/python -u /home/<YOUR_USERNAME>/badminton/booking_live.py >> /home/<YOUR_USERNAME>/badminton/logs/live-booking.log 2>&1' 55 7,13,15,23 * * * /usr/bin/flock -n /tmp/badminton-live-booking.lock /bin/bash -lc 'cd /home/<YOUR_USERNAME>/badminton && /home/<YOUR_USERNAME>/badminton/.venv/bin/python -u /home/<YOUR_USERNAME>/badminton/booking_live.py >> /home/<YOUR_USERNAME>/badminton/logs/live-booking.log 2>&1' 0 14 * * * /usr/bin/flock -n /tmp/badminton-booking-report.lock /bin/bash -lc 'cd /home/<YOUR_USERNAME>/badminton && /home/<YOUR_USERNAME>/badminton/.venv/bin/python -u /home/<YOUR_USERNAME>/badminton/booking_daily_report.py >> /home/<YOUR_USERNAME>/badminton/logs/booking-report.log 2>&1' * * * * * /usr/bin/flock -n /tmp/badminton-cancellation-reminder.lock /bin/bash -lc 'cd /home/<YOUR_USERNAME>/badminton && /home/<YOUR_USERNAME>/badminton/.venv/bin/python -u /home/<YOUR_USERNAME>/badminton/booking_cancellation_reminder.py >> /home/<YOUR_USERNAME>/badminton/logs/cancellation-reminder.log 2>&1'
This starts every day at 23:59:30 London time, prewarms all enabled account sessions,
and submits the first searches at midnight. At 07:59:30 and 15:59:30, the
retry command reads durable confirmations from the local booking logs, skips
successful account slots, logs in only the missing accounts, preloads their target
Court pages, and refreshes at exactly 08:00 or 16:00. If preloading is not
available, the established search flow remains the automatic fallback.
The read-only live-verification job refreshes every account's complete My bookings
list at 00:05, 07:55, 13:55, 15:55, and 23:55. The post-midnight check
updates the dashboard after the new booking wave, the pre-wave checks detect owner
cancellations, and the 13:55 result feeds the separate summary report at 14:00.
Each job has its own lock to prevent overlapping runs.
To send a manual report test only to the single address in
BOOKING_EMAIL_TEST_TO, run:
.venv/bin/python booking_daily_report.py --test
Check it:
crontab -l
Alternative: systemd
Templates are in deploy/.
sed -i "s|<YOUR_USERNAME>|$USER|g" deploy/badminton-booking.service sed -i "s|<YOUR_USERNAME>|$USER|g" deploy/badminton-booking-retry.service sudo cp deploy/badminton-booking.service /etc/systemd/system/ sudo cp deploy/badminton-booking.timer /etc/systemd/system/ sudo cp deploy/badminton-booking-retry.service /etc/systemd/system/ sudo cp deploy/badminton-booking-retry.timer /etc/systemd/system/ sudo systemctl daemon-reload sudo systemctl enable --now badminton-booking.timer badminton-booking-retry.timer
The primary timer runs every day at 00:00:00 Europe/London; the retry timer runs
at 08:00 and 16:00 Europe/London.
- Logs are written under
logs/ - Screenshots are written under
screenshots/ - The browser is closed at the end of every run
Useful commands:
tail -f logs/cron-run.log
ls -lt logs | headIf using systemd:
journalctl -u badminton-booking.service -n 200 journalctl -u badminton-booking.service -f
This repo does not depend on any specific AI tool. A local assistant such as Claude, Codex, or another AI tool should be able to deploy it by following this order:
- inspect the repo
- create
.venv - install
requirements.txt - run
python -m playwright install --with-deps chromium - create
.envfrom.env.example - verify with
pytestandpy_compile - configure either
cronorsystemd
- book_badminton.py: main script
- booking_daily_report.py: 14:00 daily report sender and isolated test-email entry point
- booking_cancellation_reminder.py: five-hour cancellation reminder sender
- booking_live.py: read-only
Upcoming bookingsverification and local snapshot writer - booking_retired.py: private seven-day former-account retention and cleanup state
- .env.example: environment template
- requirements.txt: Python dependencies
- tests/test_booking_helpers.py: unit tests
- tests/test_booking_daily_report.py: report scheduling and test-recipient isolation tests
- tests/test_booking_cancellation_reminder.py: reminder timing and calendar-invite tests
- tests/test_booking_live.py: live parsing, reconciliation, fallback, and state-file tests
- tests/test_booking_retired.py: monitor-only retention, privacy-mode, and validation tests
- deploy/badminton-booking.service: optional
systemdservice template - deploy/badminton-booking.timer: optional
systemdtimer template
Do not execute recorded_flow.py in production. Use it only as selector reference.
If selectors drift, capture a fresh Playwright recording:
source .venv/bin/activate
python -m playwright codegen https://soton.gladstonego.cloud/accountThen compare the new flow against the helper functions in book_badminton.py.