C

hey i was a discord bot that makes a nice clean look when your looking for a team in fortnite that will link to epic and tracks players pr from 0-100k

Kodari AI
KodariSep 3 at 5:51 pm 1
FortniteTeamFinder
A Discord bot that helps Fortnite players find and form teams with a clean, organized interface. It links users' Epic Games accounts, displays player performance ratings (PR) from 0 to 100k, and provides team-matching functionality. The bot features slash commands for profile setup, team creation, and player search, with embedded messages for a polished look. It tracks and displays PR stats to help players assess potential teammates before joining a squad.

[Generation stopped]

C

hey i was a discord bot that makes a nice clean look when your looking for a team in fortnite that will link to epic and tracks players pr from 0-100k

Kodari AI
KodariSep 3 at 5:56 pm 1
  1. Build a clean Discord.py team-finder bot with slash commands and an interactive setup panel.

  2. Store Epic display names, platforms, PR scores, and LFG posts persistently in SQLite.

  3. Add matching, profiles, leaderboard, PR validation, and secure environment-based configuration.

Built the Fortnite Team Finder Discord bot.

Included:

  • Clean /setup panel with interactive buttons

  • /link for Epic display name and platform

  • /setpr with PR validation from 0โ€“100,000

  • /looking and /notlooking LFG listings

  • /find filtering by mode, region, and PR range

  • /profile and /leaderboard

  • SQLite persistence

  • Secure .env token configuration

  • Discord slash-command syncing for test servers

Files added:

  • bot.py

  • requirements.txt

  • .env.example

  • .gitignore

  • README.md

PR is entered through /setpr because Epic does not provide a simple public endpoint for bots to automatically retrieve competitive PR.

C

ok thank you can u show me a pre view

Kodari AI
KodariSep 3 at 5:57 pm 1

Hereโ€™s a preview of how the Fortnite Team Finder bot could look in Discord:

Plain Text
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ ๐ŸŽฎ Fortnite Team Finder                      โ”‚
โ”‚ Find teammates. Build your squad. Win more.  โ”‚
โ”‚                                              โ”‚
โ”‚ Link your Epic account and set your PR to    โ”‚
โ”‚ help other players find the right teammate.  โ”‚
โ”‚                                              โ”‚
โ”‚ [๐Ÿ”— Link Epic]  [๐Ÿ“Š Set PR]  [๐Ÿ‘ค My Profile] โ”‚
โ”‚ [๐Ÿ”Ž Find Players] [๐Ÿ† Leaderboard]            โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

Player profile

Plain Text
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ ๐Ÿ‘ค Player Profile                            โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Discord: @PlayerName                         โ”‚
โ”‚ Epic: NinjaExample                           โ”‚
โ”‚ Platform: PC                                 โ”‚
โ”‚ PR: 24,850                                   โ”‚
โ”‚ Region: NA-East                              โ”‚
โ”‚                                              โ”‚
โ”‚ Status: ๐ŸŸข Looking for a team                 โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

Looking-for-team post

Plain Text
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ ๐Ÿ”Ž Player Looking for a Team                 โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ @PlayerName                                  โ”‚
โ”‚ Epic: NinjaExample                           โ”‚
โ”‚ PR: 24,850                                   โ”‚
โ”‚ Mode: Ranked / Competitive                   โ”‚
โ”‚ Region: NA-East                              โ”‚
โ”‚ Mic: Yes                                     โ”‚
โ”‚                                              โ”‚
โ”‚ [โž• Invite to Team]                           โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

Leaderboard

Plain Text
๐Ÿ† Fortnite PR Leaderboard

๐Ÿฅ‡ @TopPlayer       100,000 PR
๐Ÿฅˆ @ProBuilder       78,420 PR
๐Ÿฅ‰ @ClutchPlayer     54,110 PR
4๏ธโƒฃ @PlayerName       24,850 PR
5๏ธโƒฃ @NewPlayer         8,300 PR

The bot uses buttons, embeds, and organized profile cards so the server feels clean instead of being filled with messy team-finding messages.

C

make more things for pr

Kodari AI
KodariSep 3 at 5:59 pm 1
  1. Add PR tiers and โ€œnext tierโ€ progress to profile cards.

  2. Track PR update history and show score changes.

  3. Add /prhistory and /comparepr commands, plus document the new PR tools.

Added more PR features:

  • Custom PR tiers: Unranked, Rising, Contender, Elite, Champion, and Legend

  • Progress bar and next-tier goal on profiles

  • Automatic PR update history in SQLite

  • /prhistory to view recent PR changes

  • /comparepr to compare two players

  • /setpr now shows how much PR was gained or lost

  • Updated README documentation

The tiers are custom bot rankings, not official Fortnite ranks.

C

add some for 8,300 pr and below all the way to 0

Kodari AI
KodariSep 3 at 6:00 pm 1

Added PR tiers from 0 through 8,300:

  • 0: Unranked

  • 500: Starter

  • 1,500: Rookie

  • 3,000: Prospect

  • 5,000: Challenger

  • 8,300: Semi-Pro

  • 10,000+: Rising and higher existing tiers

Profiles now show the playerโ€™s tier and how much PR is needed to reach the next one.

C

show me what it would look like in a discord sever

Kodari AI
KodariSep 3 at 6:01 pm 1

Hereโ€™s a mockup of how the Fortnite Team Finder bot could look in a Discord server:

๐ŸŽฎ Team Finder setup panel

Plain Text
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ ๐ŸŽฎ FORTNITE TEAM FINDER                      โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Find the perfect teammates based on PR,      โ”‚
โ”‚ region, platform, and game mode.              โ”‚
โ”‚                                              โ”‚
โ”‚ Link your Epic account and create your       โ”‚
โ”‚ player profile to get started.               โ”‚
โ”‚                                              โ”‚
โ”‚ ๐Ÿ”— Epic Account: Not linked                  โ”‚
โ”‚ ๐Ÿ“Š PR Score: Not set                         โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

[๐Ÿ”— Link Epic] [๐Ÿ“Š Set PR] [๐Ÿ‘ค Profile]
[๐Ÿ”Ž Find Players] [๐Ÿ† Leaderboard]

๐Ÿ‘ค Player profile

Plain Text
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ ๐Ÿ‘ค PLAYER PROFILE                            โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Discord: @PlayerName                         โ”‚
โ”‚ Epic: PlayerExample                          โ”‚
โ”‚ Platform: PC                                 โ”‚
โ”‚ Region: NA-East                              โ”‚
โ”‚                                              โ”‚
โ”‚ ๐Ÿ“Š PR: 8,300                                 โ”‚
โ”‚ ๐Ÿ… Tier: Semi-Pro                            โ”‚
โ”‚                                              โ”‚
โ”‚ Progress to next tier                        โ”‚
โ”‚ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ 100%                    โ”‚
โ”‚                                              โ”‚
โ”‚ Status: ๐ŸŸข Looking for a team                 โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

[๐ŸŸข Looking for Team] [โœ๏ธ Edit Profile]

๐Ÿ”Ž Looking-for-team player

Plain Text
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ ๐Ÿ”Ž PLAYER LOOKING FOR A TEAM                 โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ @PlayerName                                  โ”‚
โ”‚                                              โ”‚
โ”‚ ๐ŸŽฎ Epic: PlayerExample                       โ”‚
โ”‚ ๐Ÿ“Š PR: 8,300                                 โ”‚
โ”‚ ๐Ÿ… Tier: Semi-Pro                            โ”‚
โ”‚ ๐ŸŒŽ Region: NA-East                           โ”‚
โ”‚ ๐Ÿ’ป Platform: PC                              โ”‚
โ”‚ ๐ŸŽฏ Mode: Ranked                              โ”‚
โ”‚ ๐ŸŽ™๏ธ Mic: Yes                                  โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

[โž• Invite to Team] [๐Ÿ‘ค View Profile]

๐Ÿ“Š Lower PR tier display

Plain Text
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ ๐Ÿ“Š PR RANKING                                โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ 0 PR       โ€” Unranked                        โ”‚
โ”‚ 500 PR     โ€” Starter                         โ”‚
โ”‚ 1,500 PR   โ€” Rookie                          โ”‚
โ”‚ 3,000 PR   โ€” Prospect                        โ”‚
โ”‚ 5,000 PR   โ€” Challenger                      โ”‚
โ”‚ 8,300 PR   โ€” Semi-Pro                        โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

๐Ÿ† Leaderboard

Plain Text
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ ๐Ÿ† SERVER PR LEADERBOARD                     โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ ๐Ÿฅ‡ @ChampionPlayer โ€” 100,000 PR              โ”‚
โ”‚ ๐Ÿฅˆ @ElitePlayer โ€” 24,850 PR                  โ”‚
โ”‚ ๐Ÿฅ‰ @SemiProPlayer โ€” 8,300 PR                 โ”‚
โ”‚                                              โ”‚
โ”‚ 4๏ธโƒฃ @ChallengerPlayer โ€” 5,000 PR              โ”‚
โ”‚ 5๏ธโƒฃ @RookiePlayer โ€” 1,500 PR                  โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

[โฌ…๏ธ Previous] [โžก๏ธ Next]

๐Ÿ“ˆ PR update message

Plain Text
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ ๐Ÿ“ˆ PR UPDATED                                โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ @PlayerName updated their PR score.          โ”‚
โ”‚                                              โ”‚
โ”‚ Previous PR: 5,000                           โ”‚
โ”‚ New PR: 8,300                                โ”‚
โ”‚ Change: ๐Ÿ“ˆ +3,300 PR                         โ”‚
โ”‚                                              โ”‚
โ”‚ New tier: ๐Ÿ… Semi-Pro                        โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

This would give the server a clean interface with organized player cards instead of a large list of plain text messages.

C

can i test the bot

Kodari AI
KodariSep 3 at 6:02 pm 1

Yes. You can test it locally in your own Discord server.

1. Create the Discord bot

  1. Create an application and open Bot.

  2. Click Reset Token and copy the token.

  3. Keep the token privateโ€”never post it publicly.

  4. Under OAuth2 โ†’ URL Generator, select:

    • bot

    • applications.commands

  5. Give it these permissions:

    • Send Messages

    • Embed Links

    • Use Slash Commands

    • Read Message History

  6. Use the generated URL to invite it to your test server.

2. Configure the project

From the project folder, install the dependencies:

Shell
python -m pip install -r requirements.txt

Copy .env.example to .env:

Shell
# Windows
copy .env.example .env

# macOS/Linux
cp .env.example .env

Edit .env:

Env
DISCORD_TOKEN=your_real_bot_token_here
TEST_GUILD_ID=your_test_server_id
DATABASE_PATH=teamfinder.sqlite3

To get your server ID, enable Developer Mode in Discord, right-click your server, and choose Copy Server ID.

3. Start the bot

Shell
python bot.py

You should see a message showing that the bot is logged in. Since TEST_GUILD_ID is set, slash commands should appear almost immediately.

4. Try these commands in Discord

Plain Text
/setup
/link
/setpr
/profile
/looking
/find
/leaderboard
/prhistory
/comparepr
/notlooking
/unlink

Example test flow:

  1. Run /setup.

  2. Use /link with your Epic display name and platform.

  3. Use /setpr and enter a score such as 8300.

  4. Run /profile to see the Semi-Pro tier.

  5. Run /looking to create a team-finder listing.

  6. Use /find to search for teammates.

The bot stores its data in teamfinder.sqlite3, so profiles remain saved after restarting it.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
f.txt
f(1).txt
f(2).txt
live-builders-counter-ip-shield-CyXxr9U1.png
README.md
requirements.txt
Code
8 737
bot.py
import logging
import os
import sqlite3
from datetime import datetime, timezone
from typing import Optional

import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv


load_dotenv()

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("fortnite-team-finder")

TOKEN = os.getenv("DISCORD_TOKEN")
DATABASE_PATH = os.getenv("DATABASE_PATH", "teamfinder.sqlite3")
TEST_GUILD_ID = os.getenv("TEST_GUILD_ID")
MAX_PR = 100_000


def now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


def format_time(value: Optional[str]) -> str:
    if not value:
        return "Not available"
    try:
        moment = datetime.fromisoformat(value)
        return discord.utils.format_dt(moment, style="R")
    except ValueError:
        return "Not available"


def pr_bar(pr: int, width: int = 12) -> str:
    filled = round((pr / MAX_PR) * width)
    return "โ–ฐ" * filled + "โ–ฑ" * (width - filled)


PR_TIERS = (
    (0, "Unranked"),
    (500, "Starter"),
    (1_500, "Rookie"),
    (3_000, "Prospect"),
    (5_000, "Challenger"),
    (8_300, "Semi-Pro"),
    (10_000, "Rising"),
    (25_000, "Contender"),
    (50_000, "Elite"),
    (75_000, "Champion"),
    (100_000, "Legend"),
)


def pr_tier(pr: int) -> tuple[str, Optional[int]]:
    tier = PR_TIERS[0][1]
    next_threshold: Optional[int] = PR_TIERS[1][0]
    for threshold, name in PR_TIERS:
        if pr >= threshold:
            tier = name
        else:
            next_threshold = threshold
            break
    else:
        next_threshold = None
    return tier, next_threshold


class Database:
    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.executescript(
            """
            CREATE TABLE IF NOT EXISTS players (
                discord_id INTEGER PRIMARY KEY,
                epic_name TEXT NOT NULL,
                platform TEXT NOT NULL,
                pr INTEGER NOT NULL DEFAULT 0,
                pr_updated_at TEXT NOT NULL,
                created_at TEXT NOT NULL
            );

            CREATE TABLE IF NOT EXISTS team_posts (
                guild_id INTEGER NOT NULL,
                discord_id INTEGER NOT NULL,
                mode TEXT NOT NULL,
                region TEXT NOT NULL,
                mic INTEGER NOT NULL DEFAULT 1,
                note TEXT NOT NULL DEFAULT '',
                created_at TEXT NOT NULL,
                PRIMARY KEY (guild_id, discord_id)
            );

            CREATE TABLE IF NOT EXISTS pr_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                discord_id INTEGER NOT NULL,
                pr INTEGER NOT NULL,
                recorded_at TEXT NOT NULL
            );
            """
        )
        self.connection.commit()

    def close(self) -> None:
        self.connection.close()

    def get_player(self, discord_id: int) -> Optional[sqlite3.Row]:
        return self.connection.execute(
            "SELECT * FROM players WHERE discord_id = ?", (discord_id,)
        ).fetchone()

    def save_player(self, discord_id: int, epic_name: str, platform: str) -> None:
        existing = self.get_player(discord_id)
        if existing:
            self.connection.execute(
                "UPDATE players SET epic_name = ?, platform = ? WHERE discord_id = ?",
                (epic_name, platform, discord_id),
            )
        else:
            timestamp = now_iso()
            self.connection.execute(
                """
                INSERT INTO players
                    (discord_id, epic_name, platform, pr, pr_updated_at, created_at)
                VALUES (?, ?, ?, 0, ?, ?)
                """,
                (discord_id, epic_name, platform, timestamp, timestamp),
            )
        self.connection.commit()

    def set_pr(self, discord_id: int, pr: int) -> None:
        timestamp = now_iso()
        self.connection.execute(
            "UPDATE players SET pr = ?, pr_updated_at = ? WHERE discord_id = ?",
            (pr, timestamp, discord_id),
        )
        self.connection.execute(
            "INSERT INTO pr_history (discord_id, pr, recorded_at) VALUES (?, ?, ?)",
            (discord_id, pr, timestamp),
        )
        self.connection.commit()

    def delete_player(self, discord_id: int) -> None:
        self.connection.execute("DELETE FROM players WHERE discord_id = ?", (discord_id,))
        self.connection.execute("DELETE FROM team_posts WHERE discord_id = ?", (discord_id,))
        self.connection.execute("DELETE FROM pr_history WHERE discord_id = ?", (discord_id,))
        self.connection.commit()

    def pr_history(self, discord_id: int, limit: int = 8) -> list[sqlite3.Row]:
        return self.connection.execute(
            """
            SELECT pr, recorded_at
            FROM pr_history
            WHERE discord_id = ?
            ORDER BY id DESC
            LIMIT ?
            """,
            (discord_id, limit),
        ).fetchall()

    def save_post(
        self,
        guild_id: int,
        discord_id: int,
        mode: str,
        region: str,
        mic: bool,
        note: str,
    ) -> None:
        self.connection.execute(
            """
            INSERT INTO team_posts
                (guild_id, discord_id, mode, region, mic, note, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(guild_id, discord_id) DO UPDATE SET
                mode = excluded.mode,
                region = excluded.region,
                mic = excluded.mic,
                note = excluded.note,
                created_at = excluded.created_at
            """,
            (guild_id, discord_id, mode, region, int(mic), note, now_iso()),
        )
        self.connection.commit()

    def delete_post(self, guild_id: int, discord_id: int) -> None:
        self.connection.execute(
            "DELETE FROM team_posts WHERE guild_id = ? AND discord_id = ?",
            (guild_id, discord_id),
        )
        self.connection.commit()