def __init__(self, bot: commands.Bot): super(Auditlog, self).__init__(bot, __file__) self.audit_repo = AuditLogRepo() self.guild_repo = GuildRepo() self.user_repo = UserRepo() self.clear_audit_log_task.start()
def __create_player(user: Union[discord.Member, discord.User]) -> Player: if not UserRepo.user_exist(user.id): UserRepo.create_user(user) item = Player(user_id=str(user.id)) session.add(item) session.commit() return item
def create_subscriber(user: Union[discord.User, discord.Member], reminder_id: int) -> ReminderSubscriber: if not UserRepo.user_exist(user.id): UserRepo.create_user(user) item = ReminderSubscriber(reminder_id=reminder_id, user_id=str(user.id)) session.add(item) session.commit() return item
def __init__(self, bot: commands.Bot): super(Reminder, self).__init__(bot, __file__) self.reminder_repo = ReminderRepo() self.user_repo = UserRepo() self.reminder_repo.delete_older_than_now() self.reminder_force_update = True self.next_reminder: Union[ReminderData, None] = None self.reminder_task.start()
def set_birthday(user: Union[discord.Member, discord.User], date: datetime.date, year: int, write: bool = True): if not UserRepo.user_exist(user.id): UserRepo.create_user(user) item = BirthdayRepo.find_by_id(user.id) if item is None: item = BirthdayItem(user_id=str(user.id), date=date, year=year) session.add(item) session.commit() else: item.date = date if write: session.commit()
def create_reminder(reminder_message_id: int, reminder_message_channel_id: int, user: Union[discord.User, discord.Member, None], date: datetime, message: str) -> ReminderData: if user is not None: if not UserRepo.user_exist(user.id): UserRepo.create_user(user) item = ReminderData( reminder_message_ID=str(reminder_message_id), reminder_message_channel_ID=str(reminder_message_channel_id), user_ID=str(user.id) if user is not None else None, date=date, message=message) session.add(item) session.commit() return item
def __create_member_emoji_stats( user: discord.Member, emoji: Union[discord.Emoji, discord.PartialEmoji, str] ) -> MemberEmojiStats: if not UserRepo.guild_user_exist(user.id, user.guild.id): UserRepo.create_guild_user(user) emoji_id = general_util.emoji_id_from_emoji(emoji) if not EmojiDataRepo.emoji_data_exist(emoji_id): EmojiDataRepo.create_emoji_data(emoji) item = MemberEmojiStats(user_id=str(user.id), guild_id=str(user.guild.id), emoji_id=emoji_id) session.add(item) session.commit() return item
def create_audit_log(audit_type: AuditLogItemType, guild: Optional[discord.Guild] = None, user: Optional[Union[discord.Member, discord.User]] = None, channel_id: Optional[int] = None, data: Optional[dict] = None) -> AuditLogItem: if guild is not None and user is not None: if not UserRepo.guild_user_exist(user.id, guild.id): UserRepo.create_guild_user(user) elif guild is None and user is not None: if not UserRepo.user_exist(user.id): UserRepo.create_user(user) elif guild is not None and user is None: if not GuildRepo.guild_exist(guild.id): GuildRepo.create_guild(guild) item = AuditLogItem( user_id=str(user.id) if user is not None else None, guild_id=str(guild.id) if guild is not None else None, type=audit_type, data=data, channel_id=str(channel_id) if channel_id is not None else None) session.add(item) session.commit() return item
class BaseHandlers(Base_Cog): def __init__(self, bot:commands.Bot): super(BaseHandlers, self).__init__(bot, __file__) self.guild_repo = GuildRepo() self.user_repo = UserRepo() @commands.Cog.listener() async def on_member_join(self, member: discord.Member): if not member.bot: self.user_repo.create_guild_user(member) @commands.Cog.listener() async def on_member_remove(self, member: discord.Member): self.user_repo.delete_guild_user(member.id, member.guild.id) @commands.Cog.listener() async def on_guild_join(self, guild: discord.Guild): self.guild_repo.create_guild(guild) @commands.Cog.listener() async def on_guild_remove(self, guild: discord.Guild): self.guild_repo.delete_guild(guild.id)
class Auditlog(Base_Cog): def __init__(self, bot: commands.Bot): super(Auditlog, self).__init__(bot, __file__) self.audit_repo = AuditLogRepo() self.guild_repo = GuildRepo() self.user_repo = UserRepo() self.clear_audit_log_task.start() def cog_unload(self) -> None: if self.clear_audit_log_task.is_running(): self.clear_audit_log_task.stop() def __del__(self): if self.clear_audit_log_task.is_running(): self.clear_audit_log_task.cancel() @commands.group(pass_context=True, hidden=True) @commands.check(general_util.is_bot_developer) async def auditlog(self, ctx: commands.Context): if ctx.invoked_subcommand is None: await general_util.delete_message(self.bot, ctx) await ctx.send(embed=general_util.generate_error_message(general_util.get_command_group_signature(ctx)), delete_after=Config.base_error_duration) @auditlog.command(name="list", brief=Strings.auditlog_list_brief) async def list_recent(self, ctx: commands.Context, limit:Optional[int]=None): await general_util.delete_message(self.bot, ctx) audit_logs = self.audit_repo.get_recent_logs(limit=limit) log_strings = [] for audit_log in audit_logs: user_name = audit_log.user.username if audit_log.user is not None else None if user_name is not None: display_name = audit_log.guild_user.display_name if audit_log.guild_user is not None else None if display_name is not None and display_name != user_name: user_name = f"{user_name} ({display_name})" guild_name = audit_log.guild.name if audit_log.guild is not None else None item_list = [str(audit_log.id), user_name, guild_name, audit_log.type.name, str(audit_log.created_at)] try: item_list.remove(None) except: pass log_strings.append(" - ".join(item_list)) if not log_strings: return await ctx.send(embed=general_util.generate_error_message("*No audit logs*"), delete_after=Config.base_error_duration) final_texts = [] while log_strings: tmp_text, log_strings = general_util.add_string_until_length(log_strings, 4000, "\n") final_texts.append(tmp_text) for text in final_texts: await ctx.send(f"```{text}```", delete_after=Config.base_long_success_duration) @tasks.loop(hours=(24 * Config.auditlog_history_check_interval_days)) async def clear_audit_log_task(self): cutoff_time = datetime.datetime.utcnow() - datetime.timedelta(days=Config.auditlog_history_to_keep_day) self.audit_repo.delete_old_auditlogs(cutoff_time) @commands.Cog.listener() async def on_user_update(self, old_user: discord.User, new_user: discord.User): if old_user.bot: return if old_user.name != new_user.name: user = self.user_repo.get_user_by_dc_user(new_user) user.username = new_user.name self.user_repo.update() user_upd_data = UserUpdateData.from_users(old_user, new_user) if user_upd_data.is_empty(): return self.audit_repo.create_audit_log(AuditLogItemType.USER_UPDATED, user=new_user, data=user_upd_data.to_json()) @commands.Cog.listener() async def on_member_update(self, old_member: discord.Member, new_member: discord.Member): if old_member.bot or old_member.system: return if old_member.display_name != new_member.display_name: member = self.user_repo.get_guild_user_by_member(new_member) member.display_name = new_member.display_name self.user_repo.update() mem_upd_data = MemberUpdateData.from_members(old_member, new_member) if mem_upd_data.is_empty(): return self.audit_repo.create_audit_log(AuditLogItemType.MEMBER_UPDATED, new_member.guild, new_member, data=mem_upd_data.to_json()) @commands.Cog.listener() async def on_guild_update(self, old_guild: discord.Guild, new_guild: discord.Guild): if old_guild.name != new_guild.name: db_guild = self.guild_repo.get_guild(new_guild) db_guild.name = new_guild.name self.guild_repo.update() data = GuildUpdatedData.from_guilds(old_guild, new_guild) if data is None: return self.audit_repo.create_audit_log(AuditLogItemType.GUILD_UPDATED, new_guild, data=data.to_json()) @commands.Cog.listener() async def on_message_delete(self, message: discord.Message): if message.is_system(): return if message.author.bot: return context: commands.Context = await self.bot.get_context(message) if context.valid: return del_mess_data = MesssageDeletedData.from_message(message) self.audit_repo.create_audit_log(AuditLogItemType.MESSAGE_DELETED, message.guild, message.author, message.channel.id, del_mess_data.to_json()) @commands.Cog.listener() async def on_message_edit(self, old_message: discord.Message, new_message: discord.Message): if old_message.is_system(): return if old_message.author.bot: return edit_mess_data = MessageEditedData.from_messages(old_message, new_message) self.audit_repo.create_audit_log(AuditLogItemType.MESSAGE_EDITED, old_message.guild, old_message.author, old_message.channel.id, edit_mess_data.to_json())
def get_user_service() -> UserService: db = get_db() user_repo = UserRepo(db) user_svc = UserService(user_repo=user_repo) return user_svc
class Reminder(Base_Cog): def __init__(self, bot: commands.Bot): super(Reminder, self).__init__(bot, __file__) self.reminder_repo = ReminderRepo() self.user_repo = UserRepo() self.reminder_repo.delete_older_than_now() self.reminder_force_update = True self.next_reminder: Union[ReminderData, None] = None self.reminder_task.start() def cog_unload(self): if self.reminder_task.is_running(): self.reminder_task.stop() def __del__(self): if self.reminder_task.is_running(): self.reminder_task.cancel() async def process_reminder_trigger(self, data: ReminderData): if Config.reminder_delete_reminder_created_message_on_expire: try: channel = await self.bot.fetch_channel( int(data.reminder_message_channel_ID)) if channel is not None: reminder_message: Union[ discord.Message, None] = await channel.fetch_message( int(data.reminder_message_ID)) if reminder_message is not None: await reminder_message.delete() except: pass embed = discord.Embed(title="⏰ Reminder ⏰", description=data.message, color=discord.Color.dark_blue()) message_futures = [] if data.user_ID is not None: author = await general_util.get_user(self.bot, int(data.user_ID)) message_futures.append(author.send(embed=embed)) async with subscribers_manipulation_lock: subscribers_futures = [ general_util.get_user(self.bot, int(sub.user_id)) for sub in data.subscribers ] if subscribers_futures: subscribers = await asyncio.gather(*subscribers_futures) message_futures.extend([ sub.send(embed=embed) for sub in subscribers if sub is not None ]) if message_futures: await asyncio.gather(*message_futures) self.reminder_repo.delete_reminder_by_id(data.id) @tasks.loop(minutes=1) async def reminder_task(self): if self.reminder_force_update: self.next_reminder = self.reminder_repo.get_next() self.reminder_force_update = False if self.next_reminder is None: return diff = (self.next_reminder.date - datetime.utcnow()).total_seconds() if diff >= 60: return if diff > 0: await asyncio.sleep(diff) self.next_reminder = self.reminder_repo.get_reminder_by_id( self.next_reminder.id) if self.next_reminder is not None: await self.process_reminder_trigger(self.next_reminder) self.reminder_force_update = True await self.reminder_task() @commands.group(pass_context=True, brief=Strings.reminder_brief) async def reminder(self, ctx: commands.Context): if ctx.invoked_subcommand is None: await general_util.delete_message(self.bot, ctx) await ctx.send(embed=general_util.generate_error_message( general_util.get_command_group_signature(ctx)), delete_after=Config.base_error_duration) async def process_reminder_creation(self, ctx: commands.Context, author: Union[discord.User, discord.Member, None], date: str, time: str, message: str): date_splits = date.split(".") time_splits = time.split(":") date_obj = parse_date_splits(date_splits, time_splits) if date_obj is None: return await ctx.send(embed=general_util.generate_error_message( Strings.reminder_invalid_time_or_date_format), delete_after=Config.base_error_duration) if (datetime.utcnow() + timedelta(minutes=1)) > date_obj: return await ctx.send(embed=general_util.generate_error_message( Strings.reminder_date_in_past), delete_after=Config.base_error_duration) message = general_util.split_to_parts(message, 3000)[0] embed = discord.Embed(title="Creating reminder", color=discord.Color.orange()) general_util.add_author_footer(embed, ctx.author) resp_msg = await ctx.send(embed=embed) reminder = self.reminder_repo.create_reminder(resp_msg.id, ctx.channel.id, author, date_obj, message) if reminder is None: return await resp_msg.edit( embed=general_util.generate_error_message( "Failed to create new reminder"), delete_after=Config.base_error_duration) embed = generate_reminder_embed( reminder, "⏰ Reminder created ⏰", "\n\nReact with 🙋 to subscribe for this reminder" if ctx.guild is not None else None) general_util.add_author_footer(embed, ctx.author) await resp_msg.edit(embed=embed) if ctx.guild is not None: await resp_msg.add_reaction("🙋") self.reminder_force_update = True @reminder.command(name="time", brief=Strings.reminder_time_brief) @commands.cooldown(2, 30, type=commands.BucketType.user) async def current_time(self, ctx: commands.Context): await general_util.delete_message(self.bot, ctx) embed = discord.Embed( title="Bot time (UTC)", description=datetime.utcnow().strftime("%d.%b.%Y %H:%M"), color=discord.Color.blurple()) await ctx.send(embed=embed, delete_after=Config.base_long_success_duration) @reminder.command(name="create", aliases=["c"], brief=Strings.reminder_create_brief, help=Strings.reminder_create_help) @commands.cooldown(2, 30, type=commands.BucketType.user) async def create_reminder(self, ctx: commands.Context, date: str, time: str, *, message: str): await general_util.delete_message(self.bot, ctx) await self.process_reminder_creation(ctx, ctx.author, date, time, message) @reminder.command(name="create_empty", aliases=["ce"], brief=Strings.reminder_create_empty_brief, help=Strings.reminder_create_help) @commands.cooldown(2, 30, type=commands.BucketType.user) @commands.guild_only() async def create_empty_reminder(self, ctx: commands.Context, date: str, time: str, *, message: str): await general_util.delete_message(self.bot, ctx) await self.process_reminder_creation(ctx, None, date, time, message) @reminder.command(name="remove", aliases=["rm"], brief=Strings.reminder_remove_brief, help=Strings.reminder_remove_help) @commands.cooldown(2, 30, type=commands.BucketType.user) async def remove_reminder(self, ctx: commands.Context, reminder_id: int): await general_util.delete_message(self.bot, ctx) reminder = self.reminder_repo.get_reminder_by_id(reminder_id) if reminder is None: return await ctx.send(embed=general_util.generate_error_message( Strings.reminder_invalid_id), delete_after=Config.base_error_duration) if reminder.user_ID == str( ctx.author.id) or ctx.author.id in Config.developer_ids: # If user is author of reminder or admin remove whole reminder if Config.reminder_delete_reminder_created_message_on_expire: try: channel = await self.bot.fetch_channel( int(reminder.reminder_message_channel_ID)) if channel is not None: reminder_message: Union[ discord.Message, None] = await channel.fetch_message( int(reminder.reminder_message_ID)) if reminder_message is not None: await reminder_message.delete() except: pass self.reminder_repo.delete_reminder_by_id(reminder.id) await ctx.send(embed=general_util.generate_success_message( Strings.reminder_remove_author_success), delete_after=Config.base_success_duration) self.reminder_force_update = True elif self.reminder_repo.user_in_subscribers(ctx.author.id, reminder.id): # If its subscriber then remove it from subscribers async with subscribers_manipulation_lock: self.reminder_repo.remove_subscription(ctx.author, reminder.id) await ctx.send(embed=general_util.generate_success_message( Strings.reminder_remove_subscriber_success), delete_after=Config.base_success_duration) else: await ctx.send(embed=general_util.generate_error_message( Strings.reminder_remove_missing_permissions), delete_after=Config.base_error_duration) async def update_reminder_in_database(self, reminder: ReminderData, ctx: commands.Context, date: str = None, time: str = None, message: str = None): if date is not None and time is not None: date_splits = date.split(".") time_splits = time.split(":") date_obj = parse_date_splits(date_splits, time_splits) if date_obj is None: return await ctx.send( embed=general_util.generate_error_message( Strings.reminder_invalid_time_or_date_format), delete_after=Config.base_error_duration) if (datetime.now() + timedelta(minutes=1)) > date_obj: return await ctx.send( embed=general_util.generate_error_message( Strings.reminder_date_in_past), delete_after=Config.base_error_duration) reminder.date = date_obj if message is not None: message = general_util.split_to_parts(message, 3000)[0] reminder.message = message self.reminder_repo.update() async def update_reminder_message(self, reminder: ReminderData): original_channel = self.bot.get_channel( int(reminder.reminder_message_channel_ID)) if original_channel is None: try: original_channel = await self.bot.fetch_channel( int(reminder.reminder_message_channel_ID)) if original_channel is not None: original_rem_message = await original_channel.fetch_message( int(reminder.reminder_message_ID)) if original_rem_message is not None: embed = generate_reminder_embed( reminder, "⏰ Reminder created ⏰", "\n\nReact with 🙋 to subscribe for this reminder" if original_channel.guild is not None else None) await original_rem_message.edit(embed=embed) except discord.Forbidden: pass @reminder.command(name="edit", aliases=["e"], brief=Strings.reminder_edit_brief) @commands.cooldown(2, 60, type=commands.BucketType.user) async def edit_reminder(self, ctx: commands.Context, reminder_id: int, date: str, time: str, *, message: str): await general_util.delete_message(self.bot, ctx) reminder = self.reminder_repo.get_reminder_by_id(reminder_id) if reminder is None: return await ctx.send(embed=general_util.generate_error_message( Strings.reminder_invalid_id), delete_after=Config.base_error_duration) if reminder.user_ID == str( ctx.author.id) or ctx.author.id in Config.developer_ids: await self.update_reminder_in_database(reminder, ctx, date, time, message) await self.update_reminder_message(reminder) await ctx.send(embed=general_util.generate_success_message( Strings.populate_string("reminder_edit_success", id=reminder.id)), delete_after=Config.base_success_duration) else: await ctx.send(embed=general_util.generate_error_message( Strings.reminder_missing_permission), delete_after=Config.base_error_duration) @reminder.command(name="edit_date", aliases=["ed"], brief=Strings.reminder_edit_date_brief) @commands.cooldown(2, 60, type=commands.BucketType.user) async def edit_reminder_date(self, ctx: commands.Context, reminder_id: int, date: str, time: str): await general_util.delete_message(self.bot, ctx) reminder = self.reminder_repo.get_reminder_by_id(reminder_id) if reminder is None: return await ctx.send(embed=general_util.generate_error_message( Strings.reminder_invalid_id), delete_after=Config.base_error_duration) if reminder.user_ID == str( ctx.author.id) or ctx.author.id in Config.developer_ids: await self.update_reminder_in_database(reminder, ctx, date, time) await self.update_reminder_message(reminder) await ctx.send(embed=general_util.generate_success_message( Strings.populate_string("reminder_edit_success", id=reminder.id)), delete_after=Config.base_success_duration) else: await ctx.send(embed=general_util.generate_error_message( Strings.reminder_missing_permission), delete_after=Config.base_error_duration) @reminder.command(name="edit_message", aliases=["em"], brief=Strings.reminder_edit_message_brief) @commands.cooldown(2, 60, type=commands.BucketType.user) async def edit_reminder_message(self, ctx: commands.Context, reminder_id: int, *, message: str): await general_util.delete_message(self.bot, ctx) reminder = self.reminder_repo.get_reminder_by_id(reminder_id) if reminder is None: return await ctx.send(embed=general_util.generate_error_message( Strings.reminder_invalid_id), delete_after=Config.base_error_duration) if reminder.user_ID == str( ctx.author.id) or ctx.author.id in Config.developer_ids: await self.update_reminder_in_database(reminder, ctx, message=message) await self.update_reminder_message(reminder) await ctx.send(embed=general_util.generate_success_message( Strings.populate_string("reminder_edit_success", id=reminder.id)), delete_after=Config.base_success_duration) else: await ctx.send(embed=general_util.generate_error_message( Strings.reminder_missing_permission), delete_after=Config.base_error_duration) @reminder.command(name="remove_and_trigger", aliases=["rmt"], brief=Strings.reminder_remove_and_trigger_brief, help=Strings.reminder_remove_help) @commands.cooldown(2, 30, type=commands.BucketType.user) async def remove_reminder_and_trigger(self, ctx: commands.Context, reminder_id: int): await general_util.delete_message(self.bot, ctx) reminder = self.reminder_repo.get_reminder_by_id(reminder_id) if reminder is None: return await ctx.send(embed=general_util.generate_error_message( Strings.reminder_invalid_id), delete_after=Config.base_error_duration) if reminder.user_ID == str( ctx.author.id) or ctx.author.id in Config.developer_ids: await self.process_reminder_trigger(reminder) await ctx.send(embed=general_util.generate_success_message( Strings.reminder_remove_author_success), delete_after=Config.base_success_duration) else: await ctx.send(embed=general_util.generate_error_message( Strings.reminder_missing_permission), delete_after=Config.base_error_duration) @reminder.command(name="list", aliases=["ls", "l"], brief=Strings.reminder_list_brief) @commands.cooldown(2, 30, type=commands.BucketType.user) async def user_reminder_list(self, ctx: commands.Context): await general_util.delete_message(self.bot, ctx) user = self.user_repo.get_user_by_dc_user(ctx.author) if not user.reminders or not user.reminder_subscriptions: embed = discord.Embed(title="Reminder list", description="*No active reminders*", color=discord.Color.orange()) general_util.add_author_footer(embed, ctx.author) await ctx.send(embed=embed, delete_after=Config.base_long_success_duration) else: pages = [] for reminder in user.reminders: page = generate_reminder_embed(reminder, "Own Reminder list") general_util.add_author_footer(page, ctx.author) pages.append(page) for reminder in user.reminder_subscriptions: page = generate_reminder_embed(reminder, "Subscribed Reminder list") general_util.add_author_footer(page, ctx.author) pages.append(page) p_session = PaginatorSession(self.bot, ctx, Config.base_long_success_duration, pages) await p_session.run() async def handle_reaction_add(self, ctx: ReactionContext): if ctx.guild is None: return if ctx.emoji != "🙋": return if self.bot.user.id == ctx.member.id: return if ctx.member.id == ctx.message.author.id: return reminder = self.reminder_repo.get_reminder_by_reminder_message( ctx.message.id) if reminder is None: return if str(ctx.member.id) == reminder.user_ID: return if reminder.subscribers: for subscriber in reminder.subscribers: if subscriber.user_id == str(ctx.member.id): return async with subscribers_manipulation_lock: self.reminder_repo.create_subscriber(ctx.member, reminder.id) async def handle_reaction_remove(self, ctx: ReactionContext): if ctx.guild is None: return if ctx.emoji != "🙋": return if self.bot.user.id == ctx.member.id: return if ctx.member.id == ctx.message.author.id: return reminder = self.reminder_repo.get_reminder_by_reminder_message( ctx.message.id) if reminder is None: return if str(ctx.member.id) == reminder.user_ID: return if not reminder.subscribers: return for subscriber in reminder.subscribers: if subscriber.user_id == str(ctx.member.id): self.reminder_repo.remove_subscription(ctx.member, reminder.id) return
def __init__(self, bot:commands.Bot): super(BaseHandlers, self).__init__(bot, __file__) self.guild_repo = GuildRepo() self.user_repo = UserRepo()
# * Date : 01/01/2021 # # * Project: SNLIDB_v2 # ################################### from flask import Flask, request from flask_cors import CORS from repository.student_repo import StudentRepo import json from model.sql_builder import SQLBuilder from repository.user_repo import UserRepo from repository.db import Db app = Flask(__name__) CORS(app) studentRepo = StudentRepo() userRepo = UserRepo() db = Db() # ++++++++++++ Login API's (3) ++++++++++++ @app.route('/profile/register', methods=['POST']) def register_user(): if ('username' in request.json) and ('password' in request.json) and ( 'role' in request.json): u_name = request.json['username'] pwd = request.json['password'] role = request.json['role'] json_data = json.dumps(userRepo.register_user(u_name, pwd, role)) return json_data else: return 'Invalid request JSON!'