Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 487
bot.py
import asyncio
import html
import logging
import os
import secrets
import sqlite3
import time
from dataclasses import dataclass
from typing import Any
from urllib.parse import urlencode
import aiohttp
import discord
from aiohttp import web
from cryptography.fernet import Fernet, InvalidToken
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("epic-discord-bot")
EPIC_AUTHORIZE_URL = "https://www.epicgames.com/id/authorize"
EPIC_TOKEN_URL = "https://account-public-service-prod03.ol.epicgames.com/account/api/oauth/token"
EPIC_ACCOUNT_URL = "https://account-public-service-prod03.ol.epicgames.com/account/api/public/account"
EPIC_PROFILE_URL = "https://fortnite-public-service-prod11.ol.epicgames.com/fortnite/api/game/v2/profile/{account_id}/client/QueryProfile"
def required_env(name: str) -> str:
value = os.getenv(name)
if not value:
raise RuntimeError(f"Missing required environment variable: {name}")
return value
class AccountStore:
def __init__(self, path: str, cipher: Fernet) -> None:
self.path = path
self.cipher = cipher
with sqlite3.connect(self.path) as connection:
connection.execute(
"""
CREATE TABLE IF NOT EXISTS linked_accounts (
discord_user_id INTEGER PRIMARY KEY,
account_id TEXT NOT NULL,
display_name TEXT NOT NULL,
access_token BLOB NOT NULL,
refresh_token BLOB NOT NULL,
access_expires_at REAL NOT NULL,
updated_at REAL NOT NULL
)
"""
)
def save(
self,
discord_user_id: int,
account_id: str,
display_name: str,
access_token: str,
refresh_token: str,
access_expires_at: float,
) -> None:
encrypted_access = self.cipher.encrypt(access_token.encode("utf-8"))
encrypted_refresh = self.cipher.encrypt(refresh_token.encode("utf-8"))
with sqlite3.connect(self.path) as connection:
connection.execute(
"""
INSERT INTO linked_accounts
(discord_user_id, account_id, display_name, access_token,
refresh_token, access_expires_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(discord_user_id) DO UPDATE SET
account_id = excluded.account_id,
display_name = excluded.display_name,
access_token = excluded.access_token,
refresh_token = excluded.refresh_token,
access_expires_at = excluded.access_expires_at,
updated_at = excluded.updated_at
""",
(
discord_user_id,
account_id,
display_name,
encrypted_access,
encrypted_refresh,
access_expires_at,
time.time(),
),
)
def get(self, discord_user_id: int) -> dict[str, Any] | None:
with sqlite3.connect(self.path) as connection:
connection.row_factory = sqlite3.Row
row = connection.execute(
"SELECT * FROM linked_accounts WHERE discord_user_id = ?",
(discord_user_id,),
).fetchone()
if row is None:
return None
try:
return {
"account_id": row["account_id"],
"display_name": row["display_name"],
"access_token": self.cipher.decrypt(row["access_token"]).decode("utf-8"),
"refresh_token": self.cipher.decrypt(row["refresh_token"]).decode("utf-8"),
"access_expires_at": row["access_expires_at"],
}
except InvalidToken:
logger.error("Could not decrypt tokens for Discord user %s", discord_user_id)
return None
def delete(self, discord_user_id: int) -> None:
with sqlite3.connect(self.path) as connection:
connection.execute("DELETE FROM linked_accounts WHERE discord_user_id = ?", (discord_user_id,))
@dataclass
class OAuthState:
discord_user_id: int
expires_at: float
class OAuthStateStore:
def __init__(self) -> None:
self._states: dict[str, OAuthState] = {}
def create(self, discord_user_id: int) -> str:
self.remove_expired()
state = secrets.token_urlsafe(32)
self._states[state] = OAuthState(discord_user_id, time.time() + 600)
return state
def consume(self, state: str) -> OAuthState | None:
stored = self._states.pop(state, None)
if stored is None or stored.expires_at < time.time():
return None
return stored
def remove_expired(self) -> None:
now = time.time()
self._states = {key: value for key, value in self._states.items() if value.expires_at >= now}
class EpicClient:
def __init__(self, client_id: str, client_secret: str, redirect_uri: str, store: AccountStore) -> None:
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
self.store = store
def authorization_url(self, state: str) -> str:
query = urlencode(
{
"client_id": self.client_id,
"redirect_uri": self.redirect_uri,
"response_type": "code",
"scope": "basic_profile",
"state": state,
}
)
return f"{EPIC_AUTHORIZE_URL}?{query}"
async def exchange_code(self, code: str) -> dict[str, Any]:
async with aiohttp.ClientSession() as session:
async with session.post(
EPIC_TOKEN_URL,
data={"grant_type": "authorization_code", "code": code},
auth=aiohttp.BasicAuth(self.client_id, self.client_secret),
timeout=aiohttp.ClientTimeout(total=20),
) as response:
payload = await response.json(content_type=None)
if response.status >= 400:
raise RuntimeError(f"Epic token exchange failed with HTTP {response.status}")
return payload
async def refresh_access_token(self, user_id: int, account: dict[str, Any]) -> str:
async with aiohttp.ClientSession() as session:
async with session.post(
EPIC_TOKEN_URL,
data={"grant_type": "refresh_token", "refresh_token": account["refresh_token"]},
auth=aiohttp.BasicAuth(self.client_id, self.client_secret),
timeout=aiohttp.ClientTimeout(total=20),
) as response:
payload = await response.json(content_type=None)
if response.status >= 400:
raise RuntimeError(f"Epic token refresh failed with HTTP {response.status}")
access_token = payload["access_token"]
refresh_token = payload.get("refresh_token", account["refresh_token"])
self.store.save(
user_id,
account["account_id"],
account["display_name"],
access_token,
refresh_token,
time.time() + int(payload.get("expires_in", 7200)),
)