def register(self) -> NoReturn: """ Insert the member in table, with optionals attributes """ database.execute( insert(Member).values(id=self.member.id, name=self.member.name)) self.__model = self._fetch() # Update the model
async def send_guild_choice(self, ctx): """ Generate a welcome message to choice a role in order to manage permissions """ await ctx.message.delete() message = await self.send_choice(ctx, "guild_choice") stmt = update(Special).where(name="guild_choice").values( message_id=message.id) database.execute(stmt)
async def update_message_ref(fieldname, message: discord.Message): """ Update id of agenda or planning message in database """ ex_message_id = database.execute( select(Special).where(Special.name == fieldname)).scalar_one database.execute( update(Special).values(message_id=message.id, name=fieldname)) try: ex_message = await message.channel.fetch_message(ex_message_id) except (discord.NotFound, discord.HTTPException): return await ex_message.delete()
def insert(self) -> NoReturn: """ Inserts a message row in messages table """ channel = ("DMChannel" if isinstance(self.message.channel, discord.DMChannel) else self.message.channel.name) database.execute( insert(Message).values( author_id=self.message.author.id, channel=channel, date=datetime.datetime.now(), content=self.message.content, ))
async def reaction_guild_choice(self, payload): """ Update top role or send a DM message to the user to choice his sub roles """ stmt = select(Special).where(name="guild_choice") choice_msg_id = database.execute(stmt).message_id if choice_msg_id != payload.message_id or self.bot.user.id == payload.user_id: return # exit if it's not for the guild_choice message guild = GuildController(payload.guild) member = guild.get_member(payload.member) try: role_name = self.reacts_pairs["guild_choice"][payload.emoji.name] await member.remove_roles(member.top_role) await member.add_roles(member.get_role_by_name(role_name)) except KeyError: await member.dm_channel.send( f"{member.mention} Cette réaction est invalide") except AttributeError: logging.error( f"The user {member.name} was not registered in members table") else: fieldname = self.FIELDNAMES.get(member.top_role.name) message = await self.send_choice(member, fieldname) member.choice_msg_id = message.id
def _fetch(self) -> Optional[Member]: """ Fetch from the database and returns the member if exists """ try: return database.execute( select(Member).where(Member.id == self.member.id)).scalar_one except sqlalchemy.exc.NoResultFound: return None
async def new_procedure(self, ctx): await ctx.message.delete() try: if self.table == "planning": await self.gen_question("Quelle matière voulez-vous ajouter ?", check_matter) await self.gen_question( "A quelle date le cours aura lieu ? (Ex : JJ/MM)", check_date) await self.gen_question("A quelle heure ? (Ex: 10h; 10h/12h…)", check_hours) await self.gen_question( 'Voulez-vous ajouter des infos supplémentaires? ' '("votre contenu" ou "non")', check_description, timeout=120, ) else: await self.gen_question("Quelle matière voulez-vous ajouter ?", check_matter) await self.gen_question( "Quelle est la date limite du devoir ? (Ex : JJ/MM)", check_date, ) await self.gen_question( "Indiquez quels sont les devoirs à faire (obligatoire):", check_description, timeout=120, ) except asyncio.TimeoutError: await ctx.author.send( f"{ctx.author.mention} Vous avez mis trop de temps à répondre" f" ou vos réponses n'étaient pas correct. {self.custom_response}" ) else: model = Agenda if self.table == 'agenda' else Planning database.execute(insert(model).values(**self.answers)) await self.update_data() finally: for msg in self.traces: try: await msg.delete() except discord.errors.NotFound: pass
async def remove_procedure(self, ctx): await ctx.message.delete() try: msg1 = await ctx.channel.send( "Quelle matière voulez-vous supprimer?") self.traces.append(msg1) resp1 = await self.bot.wait_for("message", timeout=60, check=check_matter) await msg1.delete() await resp1.delete() msg2 = await ctx.channel.send("De quel jour? (Ex: JJ/MM)") self.traces.append(msg2) resp2 = await self.bot.wait_for("message", timeout=120, check=check_date) await msg2.delete() await resp2.delete() except asyncio.TimeoutError: await self.author.send( f"{self.author.mention} Vous avez mis trop de temps à répondre " f"ou vos réponses n'étaient pas correct. {self.custom_response}" ) else: model = Agenda if self.table == 'agenda' else Planning database.execute( delete(model).where(model.matter == self.answers["matter"], model.date == self.answers["date"])) await self.update_data() finally: for msg in self.traces: try: await msg.delete() except discord.errors.NotFound: pass
async def decisive_reaction(self, payload): """ Send result to all users when the owner add a reaction """ channel = self.bot.get_channel(payload.channel_id) if (payload.user_id != channel.guild.owner_id or "suggestion" not in channel.name): return message = await channel.fetch_message(payload.message_id) if str(payload.emoji) == "✅": database.execute( insert(Suggestion).values(author=message.author.name, description=message.content)) for reaction in message.reactions: if str(reaction.emoji) == "✅": async for user in reaction.users(): await self.send_dm_suggestion_state( user, str(payload.emoji), message) await self.send_dm_suggestion_state(message.author, str(payload.emoji), message) await message.delete()
async def update_data(self): """ Fetch the database to get the list of rows ordered by date """ model = Agenda if self.table == 'agenda' else Planning result = database.execute( select(model).where( model.class_name == self.table_class, model.date >= datetime.datetime.now())).scalar_one next_date, message = None, "" for row in result: date = row["date"] if date != next_date: next_date = date day = DAYS[date.weekday()] month = MONTHS[int(f"{date:%m}") - 1] message += f"\n__Pour le **{day}** {date:%d} {month}:__\n" description = (f"*({row['description']})*" if bool(row["description"]) else "") if self.table == "planning": message += f"- \t {row['matter']}: " message += ( f"**{row['starthour']}**-**{row['endhour']}** {description}\n" ) else: message += f"\n**{row['matter']}**: {row['description']}\n" title = "Cours à venir:" if self.table == "planning" else "Devoirs à faire:" embed = discord.Embed(color=0x22CCFF, title=title, description=message) embed.set_thumbnail(url=STATIC_DIR / "img/book.jpg") new_msg = await self.channel.send(embed=embed) await update_message_ref(f"{self.table}_{self.table_class}", new_msg)
def update(self, **kwargs): """ Accept keyword arguments only matching with a column in members table """ database.execute( update(Member).where(Member.id == self.member.id).values(**kwargs))