Skip to content

Commit ea6436f

Browse files
committed
refactor: sqlalchemy is setup, bot now boots properly again
1 parent 323081f commit ea6436f

File tree

5 files changed

+30
-270
lines changed

5 files changed

+30
-270
lines changed

chiya/bot.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,9 @@
88
from discord.ext import commands
99
from loguru import logger as log
1010

11-
import database
11+
from chiya import database # noqa
1212
from chiya.config import config
1313

14-
1514
bot = commands.Bot(
1615
activity=discord.Activity(type=discord.ActivityType.listening, name=config.bot.status),
1716
case_insensitive=True,
@@ -76,5 +75,4 @@ async def load_cogs():
7675
if sys.platform == "win32":
7776
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
7877

79-
database.Database().setup()
8078
asyncio.run(main())

chiya/cogs/listeners/autoresponder.py

Lines changed: 0 additions & 216 deletions
This file was deleted.

chiya/cogs/listeners/highlight.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
from discord.ext import commands
77
from loguru import logger as log
88

9-
from chiya import database
109
from chiya.config import config
10+
from chiya.database import Highlight, Session
1111
from chiya.utils import embeds
1212

1313

@@ -17,12 +17,10 @@ def __init__(self, bot: commands.Bot) -> None:
1717
self.refresh_highlights()
1818

1919
def refresh_highlights(self):
20-
db = database.Database().get()
21-
self.highlights = [
22-
{"term": highlight["term"], "users": orjson.loads(highlight["users"])}
23-
for highlight in db["highlights"].find()
24-
]
25-
db.close()
20+
with Session() as session:
21+
self.highlights = [
22+
{"term": row.term, "users": orjson.loads(row.users)} for row in session.query(Highlight).all()
23+
]
2624

2725
async def active_members(self, channel: discord.TextChannel) -> set:
2826
"""

chiya/cogs/tasks/reminder.py

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
from datetime import datetime, timezone
1+
import arrow
22
import discord
3-
43
from discord.ext import commands, tasks
54
from loguru import logger as log
65

7-
from chiya import database
6+
from chiya.database import RemindMe, Session
87
from chiya.utils import embeds
98

109

@@ -23,42 +22,39 @@ async def check_for_reminder(self) -> None:
2322
"""
2423
await self.bot.wait_until_ready()
2524

26-
db = database.Database().get()
27-
result = db["remind_me"].find(
28-
sent=False, date_to_remind={"<": datetime.now(tz=timezone.utc).timestamp()}
29-
)
25+
with Session() as session:
26+
result = session.query(RemindMe).filter(RemindMe.date_to_remind < arrow.utcnow().timestamp())
3027

3128
if not result:
32-
return db.close()
29+
return
3330

3431
for reminder in result:
3532
try:
36-
user = await self.bot.fetch_user(reminder["author_id"])
33+
user = await self.bot.fetch_user(reminder.author_id)
3734
except discord.errors.NotFound:
38-
db["remind_me"].update(dict(id=reminder["id"], sent=True), ["id"])
39-
log.warning(
40-
f"Reminder entry with ID {reminder['id']} has an invalid user ID: {reminder['author_id']}."
41-
)
35+
with Session() as session:
36+
result = session.query(RemindMe).filter_by(id=reminder.id).first()
37+
result.sent = True
38+
session.commit()
39+
log.warning(f"Reminder entry with ID {reminder.id} has an invalid user ID: {reminder.author_id}.")
4240
continue
4341

4442
embed = embeds.make_embed(
4543
title="Here is your reminder",
46-
description=reminder["message"],
44+
description=reminder.message,
4745
color="blurple",
4846
)
4947

5048
try:
5149
channel = await user.create_dm()
5250
await channel.send(embed=embed)
5351
except discord.Forbidden:
54-
log.warning(
55-
f"Unable to post or DM {user}'s reminder {reminder['id']=}."
56-
)
57-
58-
db["remind_me"].update(dict(id=reminder["id"], sent=True), ["id"])
52+
log.warning(f"Unable to post or DM {user}'s reminder {reminder.id=}.")
5953

60-
db.commit()
61-
db.close()
54+
with Session() as session:
55+
result = session.query(RemindMe).filter_by(id=reminder.id).first()
56+
result.sent = True
57+
session.commit()
6258

6359

6460
async def setup(bot: commands.Bot) -> None:

chiya/database.py

Lines changed: 7 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,12 @@
66

77

88
Base = declarative_base()
9-
engine = create_engine(config.database.url, connect_args={"check_same_thread": False})
10-
session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
11-
12-
13-
class BaseModel(Base):
14-
__abstract__ = True
15-
16-
def save(self):
17-
session.add(self)
18-
session.commit()
19-
return self
20-
21-
def delete(self):
22-
session.delete(self)
23-
session.commit()
24-
return self
25-
26-
def flush(self):
27-
session.add(self)
28-
session.flush()
29-
return self
309

3110

3211
class ModLog(Base):
3312
__tablename__ = "mod_logs"
3413

35-
id = Column(Integer, primar_key=True)
14+
id = Column(Integer, primary_key=True)
3615
user_id = Column(BigInteger, nullable=False)
3716
mod_id = Column(BigInteger, nullable=False)
3817
timestamp = Column(BigInteger, nullable=False)
@@ -44,7 +23,7 @@ class ModLog(Base):
4423
class RemindMe(Base):
4524
__tablename__ = "remind_me"
4625

47-
id = Column(Integer, primar_key=True)
26+
id = Column(Integer, primary_key=True)
4827
reminder_location = Column(BigInteger, nullable=False)
4928
author_id = Column(BigInteger, nullable=False)
5029
date_to_remind = Column(BigInteger, nullable=False)
@@ -80,3 +59,8 @@ class Highlight(Base):
8059
id = Column(Integer, primary_key=True)
8160
term = Column(Text, nullable=False)
8261
users = Column(Text, nullable=False)
62+
63+
64+
engine = create_engine(config.database.url, connect_args={"check_same_thread": False})
65+
Session = sessionmaker(bind=engine)
66+
Base.metadata.create_all(engine)

0 commit comments

Comments
 (0)