From fe4d93e4f497986329c948102e818af8d1d3227c Mon Sep 17 00:00:00 2001 From: Noah <117038300+NoahCxrest@users.noreply.github.com> Date: Tue, 19 Nov 2024 12:08:28 -0700 Subject: [PATCH] Update erm.py --- erm.py | 311 +++++++++++++++++++++++++++++---------------------------- 1 file changed, 157 insertions(+), 154 deletions(-) diff --git a/erm.py b/erm.py index 8309723..8e5e241 100644 --- a/erm.py +++ b/erm.py @@ -108,7 +108,7 @@ async def setup_hook(self) -> None: if not setup: # await bot.load_extension('utils.routes') logging.info( - "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n{} is online!".format( + "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n{} is online!".format( self.user.name ) ) @@ -884,178 +884,181 @@ async def check_whitelisted_car(): @tasks.loop(seconds=120, reconnect=True) async def iterate_prc_logs(): if not bot.is_ready(): + logging.warning("[ITERATE] Bot not ready, skipping iteration") return - logging.warning("[ITERATE] Iteration Started") - async for item in bot.settings.db.find({'ERLC': {'$exists': True}}): - logging.warning("[ITERATE] Servers Found") - try: - guild = await bot.fetch_guild(item['_id']) - except discord.HTTPException: - continue - - settings = await bot.settings.find_by_id(guild.id) - try: - kill_logs_channel = await fetch_get_channel(guild, item['ERLC'].get('kill_logs')) - player_logs_channel = await fetch_get_channel(guild, item['ERLC'].get('player_logs')) - except KeyError: - continue + try: + logging.warning("[ITERATE] Iteration Started") + async for item in bot.settings.db.find({'ERLC': {'$exists': True}}): + logging.warning("[ITERATE] Servers Found") + try: + guild = await bot.fetch_guild(item['_id']) + except discord.HTTPException: + continue - if not kill_logs_channel and not player_logs_channel: - continue - try: - kill_logs: list[prc_api.KillLog] = await bot.prc_api.fetch_kill_logs(guild.id) - player_logs: list[prc_api.JoinLeaveLog] = await bot.prc_api.fetch_player_logs(guild.id) - except prc_api.ResponseFailure: - continue + settings = await bot.settings.find_by_id(guild.id) + try: + kill_logs_channel = await fetch_get_channel(guild, item['ERLC'].get('kill_logs')) + player_logs_channel = await fetch_get_channel(guild, item['ERLC'].get('player_logs')) + except KeyError: + continue - sorted_kill_logs = sorted(kill_logs, key=lambda x: x.timestamp, reverse=False) - sorted_player_logs = sorted(player_logs, key=lambda x: x.timestamp, reverse=False) - players = {} - current_timestamp = int(datetime.datetime.now(tz=pytz.UTC).timestamp()) + if not kill_logs_channel and not player_logs_channel: + continue + try: + kill_logs: list[prc_api.KillLog] = await bot.prc_api.fetch_kill_logs(guild.id) + player_logs: list[prc_api.JoinLeaveLog] = await bot.prc_api.fetch_player_logs(guild.id) + except prc_api.ResponseFailure: + continue - if kill_logs_channel is not None: - for item in sorted_kill_logs: - if (current_timestamp - item.timestamp) > 120: - continue - if not players.get(item.killer_username): - players[item.killer_username] = [1, [item]] - else: - players[item.killer_username] = [players[item.killer_username][0]+1, players[item.killer_username][1] + [item]] - await kill_logs_channel.send(embed=discord.Embed(title="Kill Log", color=BLANK_COLOR, description=f"[{item.killer_username}](https://roblox.com/users/{item.killer_user_id}/profile) killed [{item.killed_username}](https://roblox.com/users/{item.killed_user_id}/profile) • ")) + sorted_kill_logs = sorted(kill_logs, key=lambda x: x.timestamp, reverse=False) + sorted_player_logs = sorted(player_logs, key=lambda x: x.timestamp, reverse=False) + players = {} + current_timestamp = int(datetime.datetime.now(tz=pytz.UTC).timestamp()) + if kill_logs_channel is not None: + for item in sorted_kill_logs: + if (current_timestamp - item.timestamp) > 120: + continue + if not players.get(item.killer_username): + players[item.killer_username] = [1, [item]] + else: + players[item.killer_username] = [players[item.killer_username][0]+1, players[item.killer_username][1] + [item]] + await kill_logs_channel.send(embed=discord.Embed(title="Kill Log", color=BLANK_COLOR, description=f"[{item.killer_username}](https://roblox.com/users/{item.killer_user_id}/profile) killed [{item.killed_username}](https://roblox.com/users/{item.killed_user_id}/profile) • ")) - channel = ((settings or {}).get('ERLC', {}) or {}).get('rdm_channel', 0) - try: - channel = await (await bot.fetch_guild(guild.id)).fetch_channel(channel) - except discord.HTTPException: - channel = None - if channel: - for username, value in players.items(): - count = value[0] - items = value[1] - if count > 3: - roblox_player = await bot.roblox.get_user_by_username(username) - thumbnails = await bot.roblox.thumbnails.get_user_avatar_thumbnails([roblox_player], size=(420, 420)) - thumbnail = thumbnails[0].image_url - pings = [] - pings = [((guild.get_role(role_id)).mention) if guild.get_role(role_id) else None for role_id in (settings or {}).get('ERLC', {}).get('rdm_mentionables', [])] - pings = list(filter(lambda x: x is not None, pings)) - - await channel.send( - ', '.join(pings) if pings not in [[], None] else '', - embed=discord.Embed( - title="<:security:1169804198741823538> RDM Detected", - color=BLANK_COLOR - ).add_field( - name="User Information", - value=( - f"> **Username:** {roblox_player.name}\n" - f"> **User ID:** {roblox_player.id}\n" - f"> **Profile Link:** [Click here](https://roblox.com/users/{roblox_player.id}/profile)\n" - f"> **Account Created:** " + channel = ((settings or {}).get('ERLC', {}) or {}).get('rdm_channel', 0) + try: + channel = await (await bot.fetch_guild(guild.id)).fetch_channel(channel) + except discord.HTTPException: + channel = None + + if channel: + for username, value in players.items(): + count = value[0] + items = value[1] + if count > 3: + roblox_player = await bot.roblox.get_user_by_username(username) + thumbnails = await bot.roblox.thumbnails.get_user_avatar_thumbnails([roblox_player], size=(420, 420)) + thumbnail = thumbnails[0].image_url + pings = [] + pings = [((guild.get_role(role_id)).mention) if guild.get_role(role_id) else None for role_id in (settings or {}).get('ERLC', {}).get('rdm_mentionables', [])] + pings = list(filter(lambda x: x is not None, pings)) + + await channel.send( + ', '.join(pings) if pings not in [[], None] else '', + embed=discord.Embed( + title="<:security:1169804198741823538> RDM Detected", + color=BLANK_COLOR + ).add_field( + name="User Information", + value=( + f"> **Username:** {roblox_player.name}\n" + f"> **User ID:** {roblox_player.id}\n" + f"> **Profile Link:** [Click here](https://roblox.com/users/{roblox_player.id}/profile)\n" + f"> **Account Created:** " + ), + inline=False + ).add_field( + name="Abuse Information", + value=( + f"> **Type:** Mass RDM\n" + f"> **Individuals Affected [{count}]:** {', '.join([f'[{i.killed_username}](https://roblox.com/users/{i.killed_user_id}/profile)' for i in items])}\n" + f"> **At:** " + ), + inline=False + ).set_thumbnail( + url=thumbnail ), - inline=False - ).add_field( - name="Abuse Information", - value=( - f"> **Type:** Mass RDM\n" - f"> **Individuals Affected [{count}]:** {', '.join([f'[{i.killed_username}](https://roblox.com/users/{i.killed_user_id}/profile)' for i in items])}\n" - f"> **At:** " + allowed_mentions=discord.AllowedMentions( + everyone=True, + users=True, + roles=True, + replied_user=True, ), - inline=False - ).set_thumbnail( - url=thumbnail - ), - allowed_mentions=discord.AllowedMentions( - everyone=True, - users=True, - roles=True, - replied_user=True, - ), - view=RDMActions(bot) - ) - staff_roles = [] - if settings["staff_management"].get("role"): - if isinstance(settings["staff_management"]["role"], int): - staff_roles.append(settings["staff_management"]["role"]) - elif isinstance(settings["staff_management"]["role"], list): - for role in settings["staff_management"]["role"]: + view=RDMActions(bot) + ) + staff_roles = [] + if settings["staff_management"].get("role"): + if isinstance(settings["staff_management"]["role"], int): + staff_roles.append(settings["staff_management"]["role"]) + elif isinstance(settings["staff_management"]["role"], list): + for role in settings["staff_management"]["role"]: + staff_roles.append(role) + + if settings["staff_management"].get("management_role"): + if isinstance(settings["staff_management"]["management_role"], int): + staff_roles.append(settings["staff_management"]["management_role"]) + elif isinstance(settings["staff_management"]["management_role"], list): + for role in settings["staff_management"]["management_role"]: staff_roles.append(role) - - if settings["staff_management"].get("management_role"): - if isinstance(settings["staff_management"]["management_role"], int): - staff_roles.append(settings["staff_management"]["management_role"]) - elif isinstance(settings["staff_management"]["management_role"], list): - for role in settings["staff_management"]["management_role"]: - staff_roles.append(role) - - await guild.chunk() - staff_roles = [guild.get_role(role) for role in staff_roles] - added_staff = [] - - for role in staff_roles.copy(): - if role is None: - staff_roles.remove(role) - - perm_staff = list( - filter( - lambda m: ( - m.guild_permissions.manage_messages - or m.guild_permissions.manage_guild - or m.guild_permissions.administrator + + await guild.chunk() + staff_roles = [guild.get_role(role) for role in staff_roles] + added_staff = [] + + for role in staff_roles.copy(): + if role is None: + staff_roles.remove(role) + + perm_staff = list( + filter( + lambda m: ( + m.guild_permissions.manage_messages + or m.guild_permissions.manage_guild + or m.guild_permissions.administrator + ) + and not m.bot, + guild.members ) - and not m.bot, - guild.members ) - ) - for role in staff_roles: - for member in role.members: - if not member.bot and member not in added_staff: + for role in staff_roles: + for member in role.members: + if not member.bot and member not in added_staff: + added_staff.append(member) + + for member in perm_staff: + if member not in added_staff: added_staff.append(member) - - for member in perm_staff: - if member not in added_staff: - added_staff.append(member) - - automatic_shifts_enabled = ((settings.get('ERLC', {}) or {}).get('automatic_shifts', {}) or {}).get('enabled', False) - automatic_shift_type = ((settings.get('ERLC', {}) or {}).get('automatic_shifts', {}) or {}).get('shift_type', '') - roblox_to_discord = {} - for item in perm_staff: - roblox_to_discord[int(((await bot.oauth2_users.db.find_one({"discord_id": item.id})) or {}).get("roblox_id", 0))] = item - - if player_logs_channel is not None: - for item in sorted_player_logs: - if (current_timestamp - item.timestamp) > 120: - continue - if item.user_id in roblox_to_discord.keys(): - if automatic_shifts_enabled: - consent_item = await bot.consent.find_by_id(roblox_to_discord[item.user_id].id) - if (consent_item or {}).get('auto_shifts', True) is True: - shift = await bot.shift_management.get_current_shift(roblox_to_discord[item.user_id], guild.id) - if item.type == 'join': - if not shift: - await bot.shift_management.add_shift_by_user(roblox_to_discord[item.user_id], automatic_shift_type, [], guild.id, timestamp=item.timestamp) - else: - if shift: - await bot.shift_management.end_shift(shift['_id'], guild.id, timestamp=item.timestamp) - - await player_logs_channel.send( - embed=discord.Embed( - title=f"Player {'Join' if item.type == 'join' else 'Leave'} Log", - description=f"[{item.username}](https://roblox.com/users/{item.user_id}/profile) {'joined the server' if item.type == 'join' else 'left the server'} • ", - color=GREEN_COLOR if item.type == 'join' else RED_COLOR - ) - ) - - logging.warning("[ITERATE] Completed task!") + automatic_shifts_enabled = ((settings.get('ERLC', {}) or {}).get('automatic_shifts', {}) or {}).get('enabled', False) + automatic_shift_type = ((settings.get('ERLC', {}) or {}).get('automatic_shifts', {}) or {}).get('shift_type', '') + roblox_to_discord = {} + for item in perm_staff: + roblox_to_discord[int(((await bot.oauth2_users.db.find_one({"discord_id": item.id})) or {}).get("roblox_id", 0))] = item + + if player_logs_channel is not None: + for item in sorted_player_logs: + if (current_timestamp - item.timestamp) > 120: + continue + if item.user_id in roblox_to_discord.keys(): + if automatic_shifts_enabled: + consent_item = await bot.consent.find_by_id(roblox_to_discord[item.user_id].id) + if (consent_item or {}).get('auto_shifts', True) is True: + shift = await bot.shift_management.get_current_shift(roblox_to_discord[item.user_id], guild.id) + if item.type == 'join': + if not shift: + await bot.shift_management.add_shift_by_user(roblox_to_discord[item.user_id], automatic_shift_type, [], guild.id, timestamp=item.timestamp) + else: + if shift: + await bot.shift_management.end_shift(shift['_id'], guild.id, timestamp=item.timestamp) + + await player_logs_channel.send( + embed=discord.Embed( + title=f"Player {'Join' if item.type == 'join' else 'Leave'} Log", + description=f"[{item.username}](https://roblox.com/users/{item.user_id}/profile) {'joined the server' if item.type == 'join' else 'left the server'} • ", + color=GREEN_COLOR if item.type == 'join' else RED_COLOR + ) + ) + + logging.warning("[ITERATE] Completed task!") + except Exception as e: + logging.error(f"[ITERATE] Error in iteration: {str(e)}", exc_info=True) async def before_prc_logs(): await bot.wait_until_ready() - logging.info("PRC Logs task is ready to start") + logging.info("[ITERATE] PRC Logs task is ready to start") @tasks.loop(minutes=5, reconnect=True) async def iterate_ics():