diff --git a/alembic/versions/c09a64cac3cb_add_deleted_column_to_channel_model.py b/alembic/versions/c09a64cac3cb_add_deleted_column_to_channel_model.py new file mode 100644 index 0000000..24f255b --- /dev/null +++ b/alembic/versions/c09a64cac3cb_add_deleted_column_to_channel_model.py @@ -0,0 +1,28 @@ +""" +Add deleted column to channel model. + +Revision ID: c09a64cac3cb +Revises: 03655ce2097b +Create Date: 2024-04-07 22:58:53.186355 + +""" + +import sqlalchemy as sa + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "c09a64cac3cb" +down_revision = "03655ce2097b" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """Apply the current migration.""" + op.add_column("channels", sa.Column("deleted", sa.Boolean(), nullable=False, server_default="False", default=False)) + + +def downgrade() -> None: + """Revert the current migration.""" + op.drop_column("channels", "deleted") diff --git a/metricity/exts/event_listeners/guild_listeners.py b/metricity/exts/event_listeners/guild_listeners.py index d31aa8a..0d25cb2 100644 --- a/metricity/exts/event_listeners/guild_listeners.py +++ b/metricity/exts/event_listeners/guild_listeners.py @@ -153,11 +153,22 @@ async def sync_channels(self, guild: discord.Guild) -> None: name=channel.name, category_id=category_id, is_staff=is_staff, + deleted=False, )) await sess.commit() - log.info("Channel synchronisation process complete, synchronising threads") + log.info("Channel synchronisation process complete, synchronising deleted channels") + + async with async_session() as sess: + await sess.execute( + update(models.Channel) + .where(~models.Channel.id.in_([str(channel.id) for channel in guild.channels])) + .values(deleted=True), + ) + await sess.commit() + + log.info("Deleted channel synchronisation process complete, synchronising threads") async with async_session() as sess: for thread in guild.threads: @@ -189,6 +200,14 @@ async def on_guild_channel_create(self, channel: discord.abc.GuildChannel) -> No await self.sync_channels(channel.guild) + @commands.Cog.listener() + async def on_guild_channel_delete(self, channel: discord.abc.GuildChannel) -> None: + """Set the deleted flag to true when a channel is deleted.""" + if channel.guild.id != BotConfig.guild_id: + return + + await self.sync_channels(channel.guild) + @commands.Cog.listener() async def on_guild_channel_update( self, diff --git a/metricity/models.py b/metricity/models.py index dfb4102..dad6e84 100644 --- a/metricity/models.py +++ b/metricity/models.py @@ -30,6 +30,7 @@ class Channel(Base): name: Mapped[str] category_id: Mapped[str | None] = mapped_column(ForeignKey("categories.id", ondelete="CASCADE")) is_staff: Mapped[bool] + deleted: Mapped[bool] = mapped_column(default=False) class Thread(Base):