Skip to content

Commit 09d5008

Browse files
committed
ruff + ty
1 parent 20f3e8a commit 09d5008

9 files changed

Lines changed: 89 additions & 37 deletions

File tree

alembic/env.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,10 @@ def run_migrations_offline() -> None:
3838

3939
def run_migrations_online() -> None:
4040
connectable = engine_from_config(
41-
{**config.get_section(config.config_ini_section, {}), "sqlalchemy.url": _resolve_url()},
41+
{
42+
**config.get_section(config.config_ini_section, {}),
43+
"sqlalchemy.url": _resolve_url(),
44+
},
4245
prefix="sqlalchemy.",
4346
poolclass=pool.NullPool,
4447
)
@@ -57,4 +60,4 @@ def run_migrations_online() -> None:
5760
if context.is_offline_mode():
5861
run_migrations_offline()
5962
else:
60-
run_migrations_online()
63+
run_migrations_online()

alembic/versions/0001_initial_schema.py

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,12 @@ def upgrade() -> None:
3434
"pots",
3535
sa.Column("pot_id", sa.Integer, primary_key=True, autoincrement=True),
3636
sa.Column("guild_id", sa.Text, nullable=False),
37-
sa.Column("is_active", sa.Boolean, nullable=False, server_default=sa.text("TRUE")),
38-
sa.Column("created_at", sa.TIMESTAMP, server_default=sa.text("CURRENT_TIMESTAMP")),
37+
sa.Column(
38+
"is_active", sa.Boolean, nullable=False, server_default=sa.text("TRUE")
39+
),
40+
sa.Column(
41+
"created_at", sa.TIMESTAMP, server_default=sa.text("CURRENT_TIMESTAMP")
42+
),
3943
sa.Column("ended_at", sa.TIMESTAMP, nullable=True),
4044
sa.Column("winner_discord_id", sa.Text, nullable=True),
4145
sa.Column("winning_amount", sa.Integer, nullable=True),
@@ -50,7 +54,9 @@ def upgrade() -> None:
5054
sa.Column("amount", sa.Integer, nullable=False),
5155
sa.Column("status", sa.Text, nullable=False, server_default="pending"),
5256
sa.Column("stackcoin_request_id", sa.Text, nullable=True),
53-
sa.Column("created_at", sa.TIMESTAMP, server_default=sa.text("CURRENT_TIMESTAMP")),
57+
sa.Column(
58+
"created_at", sa.TIMESTAMP, server_default=sa.text("CURRENT_TIMESTAMP")
59+
),
5460
sa.ForeignKeyConstraint(["pot_id"], ["pots.pot_id"]),
5561
)
5662

@@ -66,15 +72,22 @@ def upgrade() -> None:
6672
sa.Column("discord_id", sa.Text, nullable=False),
6773
sa.Column("guild_id", sa.Text, nullable=False),
6874
sa.Column("reason", sa.Text, nullable=False),
69-
sa.Column("banned_at", sa.TIMESTAMP, server_default=sa.text("CURRENT_TIMESTAMP")),
75+
sa.Column(
76+
"banned_at", sa.TIMESTAMP, server_default=sa.text("CURRENT_TIMESTAMP")
77+
),
7078
sa.Column("expires_at", sa.TIMESTAMP, nullable=False),
7179
)
7280

7381
op.create_table(
7482
"auto_enter_users",
7583
sa.Column("discord_id", sa.Text, nullable=False),
7684
sa.Column("guild_id", sa.Text, nullable=False),
77-
sa.Column("enabled_at", sa.Text, nullable=False, server_default=sa.text("datetime('now')")),
85+
sa.Column(
86+
"enabled_at",
87+
sa.Text,
88+
nullable=False,
89+
server_default=sa.text("datetime('now')"),
90+
),
7891
sa.PrimaryKeyConstraint("discord_id", "guild_id"),
7992
)
8093

@@ -88,7 +101,9 @@ def upgrade() -> None:
88101
sqlite_where=sa.text("is_active = TRUE"),
89102
)
90103
op.create_index("idx_pot_entries_pot_id", "pot_entries", ["pot_id"])
91-
op.create_index("idx_pot_entries_request_id", "pot_entries", ["stackcoin_request_id"])
104+
op.create_index(
105+
"idx_pot_entries_request_id", "pot_entries", ["stackcoin_request_id"]
106+
)
92107
op.create_index(
93108
"idx_pot_entries_active_request_id_unique",
94109
"pot_entries",
@@ -98,16 +113,16 @@ def upgrade() -> None:
98113
"stackcoin_request_id IS NOT NULL AND status IN ('pending', 'confirmed')"
99114
),
100115
)
101-
op.create_index("idx_user_bans_lookup", "user_bans", ["discord_id", "guild_id", "expires_at"])
116+
op.create_index(
117+
"idx_user_bans_lookup", "user_bans", ["discord_id", "guild_id", "expires_at"]
118+
)
102119
op.create_index("idx_auto_enter_guild", "auto_enter_users", ["guild_id"])
103120

104121

105122
def downgrade() -> None:
106123
op.drop_index("idx_auto_enter_guild", table_name="auto_enter_users")
107124
op.drop_index("idx_user_bans_lookup", table_name="user_bans")
108-
op.drop_index(
109-
"idx_pot_entries_active_request_id_unique", table_name="pot_entries"
110-
)
125+
op.drop_index("idx_pot_entries_active_request_id_unique", table_name="pot_entries")
111126
op.drop_index("idx_pot_entries_request_id", table_name="pot_entries")
112127
op.drop_index("idx_pot_entries_pot_id", table_name="pot_entries")
113128
op.drop_index("idx_pots_one_active_per_guild", table_name="pots")
@@ -117,4 +132,4 @@ def downgrade() -> None:
117132
op.drop_table("user_bans")
118133
op.drop_table("gateway_state")
119134
op.drop_table("pot_entries")
120-
op.drop_table("pots")
135+
op.drop_table("pots")

alembic/versions/0002_add_rounds.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,4 @@ def downgrade() -> None:
6060
batch_op.drop_column("entry_round")
6161

6262
with op.batch_alter_table("pots", schema=None) as batch_op:
63-
batch_op.drop_column("current_round")
63+
batch_op.drop_column("current_round")

lucky_pot.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,13 @@ async def _fetch_stackcoin_discord_id_or_die() -> str:
7575
last_exc = RuntimeError("fetch_stackcoin_discord_id returned None")
7676
except stackcoin.StackCoinError as e:
7777
last_exc = e
78-
delay = min(
79-
STACKCOIN_CONNECT_MAX_DELAY,
80-
STACKCOIN_CONNECT_BASE_DELAY * (2 ** (attempt - 1)),
81-
) + random.random()
78+
delay = (
79+
min(
80+
STACKCOIN_CONNECT_MAX_DELAY,
81+
STACKCOIN_CONNECT_BASE_DELAY * (2 ** (attempt - 1)),
82+
)
83+
+ random.random()
84+
)
8285
logger.warning(
8386
f"StackCoin not ready (attempt {attempt}/"
8487
f"{STACKCOIN_CONNECT_MAX_ATTEMPTS}), retrying in {delay:.1f}s: "

luckypot/db.py

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,13 @@
44

55
from loguru import logger
66
from luckypot.config import settings
7-
from luckypot.types import PotEntryRow, PotEntryWithPotRow, PotRow, PotStatus, UserBanRow
7+
from luckypot.types import (
8+
PotEntryRow,
9+
PotEntryWithPotRow,
10+
PotRow,
11+
PotStatus,
12+
UserBanRow,
13+
)
814

915

1016
def get_connection() -> sqlite3.Connection:
@@ -36,7 +42,9 @@ def init_database():
3642
from alembic.config import Config
3743

3844
cfg = Config()
39-
cfg.set_main_option("script_location", str(Path(__file__).parent.parent / "alembic"))
45+
cfg.set_main_option(
46+
"script_location", str(Path(__file__).parent.parent / "alembic")
47+
)
4048
cfg.set_main_option("sqlalchemy.url", f"sqlite:///{db_path}")
4149
command.upgrade(cfg, "head")
4250

@@ -54,14 +62,20 @@ def _is_legacy_db(db_path: Path) -> bool:
5462
return False
5563
conn = sqlite3.connect(str(db_path))
5664
try:
57-
has_alembic = conn.execute(
58-
"SELECT name FROM sqlite_master WHERE type='table' AND name='alembic_version'"
59-
).fetchone() is not None
65+
has_alembic = (
66+
conn.execute(
67+
"SELECT name FROM sqlite_master WHERE type='table' AND name='alembic_version'"
68+
).fetchone()
69+
is not None
70+
)
6071
if has_alembic:
6172
return False
62-
has_pots = conn.execute(
63-
"SELECT name FROM sqlite_master WHERE type='table' AND name='pots'"
64-
).fetchone() is not None
73+
has_pots = (
74+
conn.execute(
75+
"SELECT name FROM sqlite_master WHERE type='table' AND name='pots'"
76+
).fetchone()
77+
is not None
78+
)
6579
return has_pots
6680
finally:
6781
conn.close()
@@ -76,7 +90,9 @@ def _stamp_legacy_db(db_path: Path) -> None:
7690
f"Legacy pre-alembic database detected at {db_path}; stamping to 0001_initial"
7791
)
7892
cfg = Config()
79-
cfg.set_main_option("script_location", str(Path(__file__).parent.parent / "alembic"))
93+
cfg.set_main_option(
94+
"script_location", str(Path(__file__).parent.parent / "alembic")
95+
)
8096
cfg.set_main_option("sqlalchemy.url", f"sqlite:///{db_path}")
8197
command.stamp(cfg, "0001_initial")
8298

luckypot/discord/commands.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ async def invoke(self, ctx: lightbulb.Context) -> None:
182182
# Always check preauth status even if already opted in,
183183
# because the user may have revoked their preauth since.
184184
from luckypot import stk as stk_mod
185+
185186
stk_user = await stk_mod.get_user_by_discord_id(discord_id)
186187
if stk_user:
187188
preauths = await stk_mod.get_preauths(user_id=stk_user["id"])
@@ -199,7 +200,9 @@ async def invoke(self, ctx: lightbulb.Context) -> None:
199200
window_hours=24,
200201
)
201202
if result:
202-
container = ui.build_auto_enter_opted_in_preauth_requested()
203+
container = (
204+
ui.build_auto_enter_opted_in_preauth_requested()
205+
)
203206
else:
204207
container = ui.build_auto_enter_opted_in()
205208
else:

luckypot/discord/ui.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,9 @@ def build_pot_status(status: PotStatus) -> ContainerComponentBuilder:
102102
return container
103103

104104

105-
def build_pot_history(history: list[PotRow], page: int = 1) -> ContainerComponentBuilder:
105+
def build_pot_history(
106+
history: list[PotRow], page: int = 1
107+
) -> ContainerComponentBuilder:
106108
"""Build the pot history display."""
107109
container = ContainerComponentBuilder(accent_color=BRAND_COLOR)
108110
header = "📜 Pot History" if page == 1 else f"📜 Pot History - Page {page}"

luckypot/game.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,9 @@ async def process_pot_win(
291291
)
292292
retry_conn = db.get_connection()
293293
try:
294-
db.end_pot(retry_conn, pot["pot_id"], winner_id, winning_amount, win_type)
294+
db.end_pot(
295+
retry_conn, pot["pot_id"], winner_id, winning_amount, win_type
296+
)
295297
except Exception:
296298
db.reopen_pot_after_failed_payout(retry_conn, pot["pot_id"])
297299
raise
@@ -585,7 +587,9 @@ async def on_request_accepted(
585587
)
586588
elif entry["status"] == "pending":
587589
if not db.confirm_pending_entry(conn, entry_id):
588-
logger.warning(f"Entry {entry_id} was no longer pending at confirm time")
590+
logger.warning(
591+
f"Entry {entry_id} was no longer pending at confirm time"
592+
)
589593
return
590594
logger.info(f"Entry {entry_id} confirmed for discord_id={discord_id}")
591595
instant_win = await maybe_process_instant_win(
@@ -602,10 +606,8 @@ async def on_request_accepted(
602606
if pot:
603607
participants = db.get_pot_participants(conn, pot["pot_id"])
604608
total_pot = sum(p["amount"] for p in participants)
605-
await announce(
606-
guild_id,
607-
f"<@{discord_id}> entered the pot! The pot is now at {total_pot} STK. Use `/enter-pot` to enter!",
608-
user_mentions=False,
609+
await announce_fn(
610+
f"<@{discord_id}> entered the pot! The pot is now at {total_pot} STK. Use `/enter-pot` to enter!"
609611
)
610612
else:
611613
logger.warning(

luckypot/stk.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,13 @@ async def get_user_by_discord_id(discord_id: str) -> StackCoinUser | None:
7070
if not users:
7171
return None
7272
user = users[0]
73-
return {"id": user.id, "username": user.username, "balance": user.balance}
73+
if user.id is None:
74+
logger.error(f"StackCoin user for discord_id={discord_id} had no id")
75+
return None
76+
return cast(
77+
StackCoinUser,
78+
{"id": user.id, "username": user.username, "balance": user.balance},
79+
)
7480
except stackcoin.StackCoinError as e:
7581
logger.error(f"Failed to look up user by discord_id={discord_id}: {e}")
7682
return None
@@ -135,7 +141,9 @@ async def create_preauth(
135141
async def get_preauths(user_id: int | None = None) -> list[StackCoinPreauth]:
136142
"""List preauths for this bot."""
137143
try:
138-
return cast(list[StackCoinPreauth], await get_client().get_preauths(user_id=user_id))
144+
return cast(
145+
list[StackCoinPreauth], await get_client().get_preauths(user_id=user_id)
146+
)
139147
except stackcoin.StackCoinError as e:
140148
logger.error(f"Failed to get preauths: {e}")
141149
return []

0 commit comments

Comments
 (0)