Browse Source

Ajout de la colonne de présence de guilde

master
l4p1n 3 weeks ago
parent
commit
653c540734
Signed by: l4p1n <l4p1n@l4p1n.ch> GPG Key ID: 8A2C2F68B58DC35C
4 changed files with 44 additions and 4 deletions
  1. +27
    -1
      cogs/server_events.py
  2. +5
    -0
      db/migrations/20200123215834_add_is_present_to_servers.sql
  3. +4
    -2
      db/schema.sql
  4. +8
    -1
      lib/database.py

+ 27
- 1
cogs/server_events.py View File

@@ -5,33 +5,51 @@ from discord.ext import commands

from lib.DiscordBot import DiscordBot
from lib import config
from lib import database

from models.config import Config


class ServerEvents(commands.Cog):

SQL_BULK_UPDATE_GUILD_PRESENCE = "UPDATE servers SET is_present = TRUE WHERE id = ANY($1::bigint[])"
SQL_BULK_UPDATE_GUILD_NOPRESENCE = "UPDATE servers SET is_present = FALSE WHERE id <> ALL($1::bigint[])"
SQL_UPDATE_GUILD_PRESENCE = 'UPDATE servers SET is_present = TRUE WHERE id = $1'
SQL_UPDATE_GUILD_NOPRESENCE = 'UPDATE servers SET is_present = FALSE WHERE id = $1'

def __init__(self, bot: DiscordBot):
self.bot = bot
self.logger = logging.getLogger(f'{config.LOGGING_ROOT}.cogs.server-events')
self.logger.info('Initialisation du module')

@commands.Cog.listener()
async def on_ready(self):
...
db = await database.get_database()
self.logger.info('Mise à jour des présences de guild on_ready')
await db.execute(ServerEvents.SQL_BULK_UPDATE_GUILD_PRESENCE, [s.id for s in self.bot.guilds])
await db.execute(ServerEvents.SQL_BULK_UPDATE_GUILD_NOPRESENCE, [s.id for s in self.bot.guilds])

@commands.Cog.listener()
async def on_guild_join(self, guild: discord.Guild):
self.logger.info(f"Guild {guild.name} ({guild.id}) rejoint")
await Config.register_guild(guild.id, guild.name)
await self.bot.update_guild_count_in_activity()
await self._set_presence(guild.id, True)

@commands.Cog.listener()
async def on_guild_remove(self, guild: discord.Guild):
self.logger.info(f"Guild {guild.name} ({guild.id}) quittée")
await self.bot.update_guild_count_in_activity()
await self._set_presence(guild.id, False)

@commands.Cog.listener()
async def on_member_join(self, member: discord.Member):
self.logger.info(f"{member.name} a rejoint {member.guild.name} ({member.guild.id})")
cnf = await Config.get(member.guild.id, member.guild.name)
await self._do_autowelcome_thing(member, cnf)
await self._do_role_assignation(member, cnf)

@commands.Cog.listener()
async def on_memeber_remove(self, member: discord.Member):
self.logger.info(f"{member.name} a quitté {member.guild.name} ({member.guild.id})")
cnf = await Config.get(member.guild.id, member.guild.name)
@@ -124,6 +142,14 @@ class ServerEvents(commands.Cog):
self.logger.error(e)
return

async def _set_presence(self, sid, present):
db = await database.get_database()

if present:
await db.execute(ServerEvents.SQL_UPDATE_GUILD_PRESENCE, sid)
else:
await db.execute(ServerEvents.SQL_UPDATE_GUILD_NOPRESENCE, sid)


def setup(bot: DiscordBot):
bot.add_cog(ServerEvents(bot))

+ 5
- 0
db/migrations/20200123215834_add_is_present_to_servers.sql View File

@@ -0,0 +1,5 @@
-- migrate:up
ALTER TABLE servers ADD COLUMN is_present BOOLEAN NOT NULL DEFAULT FALSE;

-- migrate:down
ALTER TABLE servers DROP COLUMN is_present;

+ 4
- 2
db/schema.sql View File

@@ -220,7 +220,8 @@ ALTER TABLE public.server_stats ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY

CREATE TABLE public.servers (
id bigint NOT NULL,
name character varying
name character varying,
is_present boolean DEFAULT false NOT NULL
);


@@ -412,4 +413,5 @@ INSERT INTO public.schema_migrations (version) VALUES
('20191012160726'),
('20191012211325'),
('20191220155103'),
('20200119134413');
('20200119134413'),
('20200123215834');

+ 8
- 1
lib/database.py View File

@@ -11,16 +11,19 @@ database = None
logger = logging.getLogger('discord-bot.postgres')
event = asyncio.Event()


# Pris depuis https://magicstack.github.io/asyncpg/current/api/index.html#asyncpg.connection.Connection.set_type_codec
def timedelta_decoder(delta: Tuple) -> relativedelta:
return relativedelta(months=delta[0], days=delta[1], microseconds=delta[2])


def timedelta_encoder(delta: relativedelta):
ndelta = delta.normalized()
return (ndelta.years * 12 + ndelta.months,
ndelta.days,
(ndelta.hours * 3600 + ndelta.minutes * 60 + ndelta.seconds) * 1_000_000 + ndelta.microseconds)


async def _setup_connection(con):
await con.set_type_codec(
'interval',
@@ -30,6 +33,7 @@ async def _setup_connection(con):
format='tuple'
)


async def init_database():
global database

@@ -47,14 +51,17 @@ async def init_database():
await asyncio.sleep(1)
event.set()


async def wait_for_db():
await event.wait()
return


async def get_database() -> asyncpg.pool.Pool:
attempts = 1
while attempts < 10:
logger.info(f'Essai {attempts} à retourner un pool')
if attempts > 3:
logger.info(f'Essai {attempts} à retourner un pool')
try:
await event.wait()
assert database is not None


Loading…
Cancel
Save