Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/mikeyusersrec/erm
Browse files Browse the repository at this point in the history
  • Loading branch information
Mikey committed Jan 7, 2025
2 parents 7629a85 + ad5b0a4 commit dbd41d8
Show file tree
Hide file tree
Showing 6 changed files with 120 additions and 6 deletions.
6 changes: 5 additions & 1 deletion cogs/Configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ async def callback_override(interaction: discord.Interaction, *args, **kwargs):
discord.SelectOption(
label=":",
description="Use ':' as your custom prefix."
),
discord.SelectOption(
label="-",
description="Use '-' as your custom prefix."
)
])
prefix = prefix_view.children[0]
Expand Down Expand Up @@ -516,7 +520,7 @@ async def _config(self, ctx: commands.Context):
['CUSTOM_CONF', {
'_FIND_BY_LABEL': True
}],
settings['customisation'].get('prefix') if settings['customisation'].get('prefix') in ['!', '>', '?', ':'] else None
settings['customisation'].get('prefix') if settings['customisation'].get('prefix') in ['!', '>', '?', ':', '-'] else None
]

)
Expand Down
2 changes: 1 addition & 1 deletion cogs/ShiftLogging.py
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,7 @@ async def duty_active(self, ctx: commands.Context, *, type: str = None):

if (
len((embeds[-1].description or "").splitlines()) >= 16
and ctx.author.id not in added_staff
and member.id not in added_staff
):
embed = discord.Embed(
title="Active Shifts", color=BLANK_COLOR
Expand Down
2 changes: 2 additions & 0 deletions erm.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from tasks.statistics_check import statistics_check
from tasks.change_status import change_status
from tasks.check_whitelisted_car import check_whitelisted_car
from tasks.sync_weather import sync_weather

from utils.log_tracker import LogTracker
from utils.mongo import Document
Expand Down Expand Up @@ -229,6 +230,7 @@ async def setup_hook(self) -> None:
check_whitelisted_car.start(bot)
change_status.start(bot)
process_scheduled_pms.start(bot)
sync_weather.start(bot)
logging.info("Setup_hook complete! All tasks are now running!")

async for document in self.views.db.find({}):
Expand Down
6 changes: 5 additions & 1 deletion menus.py
Original file line number Diff line number Diff line change
Expand Up @@ -4989,7 +4989,11 @@ async def management_role_select(
discord.SelectOption(
label=":",
description="Use ':' as your custom prefix."
)
),
discord.SelectOption(
label="-",
description="Use '-' as your custom prefix."
),
], max_values=1)
async def prefix_select(self, interaction: discord.Interaction, select: discord.ui.Select):
value = await self.interaction_check(interaction)
Expand Down
11 changes: 8 additions & 3 deletions tasks/iterate_prc_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,8 @@ async def process_player_logs(bot, settings, guild_id, player_logs, last_timesta
name="Player Information",
value=f"> **Username:** [{user.name}](https://roblox.com/users/{user_id}/profile)\n> **User ID:** {user_id}\n> **Reason:** {', '.join(reasons)}"
).set_thumbnail(url=avatar_url),
view=view
view=view,
allowed_mentions=discord.AllowedMentions.all()
)

if settings['ERLC']['avatar_check'].get('message'):
Expand Down Expand Up @@ -408,12 +409,16 @@ async def check_team_restrictions(bot, settings, guild_id, players):
kick_against.append(plr.username)
bot.team_restrictions_infractions[guild_id][plr.username] = 0
if len(load_against) > 0:
cmd = f":load {','.join(load_against)}"
if cmd.strip() != ":load":
filtered_load = [username for username in load_against if username.strip() and len(username.strip()) >= 3]
if filtered_load:
cmd = f":load {','.join(filtered_load)}"
try:
await bot.prc_api.run_command(guild_id, cmd)
except:
logging.warning("PRC API Rate limit reached when loading.")
else:
logging.warning("Skipped sending load command - usernames too short or empty")

for message, plrs_to_send in pm_against.items():
try:
await bot.scheduled_pm_queue.put((guild_id, ','.join(plrs_to_send), message))
Expand Down
99 changes: 99 additions & 0 deletions tasks/sync_weather.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import asyncio
import logging
from discord.ext import tasks
import aiohttp
from decouple import config

from utils.prc_api import ResponseFailure

@tasks.loop(minutes=5, reconnect=True)
async def sync_weather(bot):
try:
logging.info("Starting weather sync task...")

logging.info("Querying for servers with weather sync settings...")
pipeline = [
{
'$match': {
'ERLC.weather': {'$exists': True},
'$or': [
{'ERLC.weather.sync_time': True},
{'ERLC.weather.sync_weather': True}
],
'ERLC.weather.location': {'$exists': True, '$ne': ''}
}
},
{
'$lookup': {
'from': 'server_keys',
'localField': '_id',
'foreignField': '_id',
'as': 'server_key'
}
},
{
'$match': {
'server_key': {'$ne': []}
}
}
]

weather_service_url = config('WEATHER_SERVICE_URL')
logging.info(f"Using weather service URL: {weather_service_url}")

server_count = await bot.settings.db.count_documents({
'ERLC.weather': {'$exists': True},
'$or': [
{'ERLC.weather.sync_time': True},
{'ERLC.weather.sync_weather': True}
],
'ERLC.weather.location': {'$exists': True, '$ne': ''}
})
logging.info(f"Found {server_count} servers with weather sync enabled")

processed = 0
async with aiohttp.ClientSession() as session:
async for guild_data in bot.settings.db.aggregate(pipeline):
processed += 1
guild_id = guild_data['_id']
weather_settings = guild_data['ERLC']['weather']
location = weather_settings['location']

logging.info(f"Processing guild {guild_id} ({processed}/{server_count})")
logging.info(f"Location: {location}")
logging.info(f"Settings: sync_weather={weather_settings.get('sync_weather')}, sync_time={weather_settings.get('sync_time')}")

try:
# Fetch weather data
logging.info(f"Fetching weather data for {location}...")
async with session.get(f'{weather_service_url}/?location={location}') as resp:
if resp.status != 200:
logging.error(f"Failed to fetch weather data for {location}: Status {resp.status}")
continue
weather_data = await resp.json()
logging.info(f"Weather data received: {weather_data}")

# Execute weather/time commands based on settings
if weather_settings.get('sync_weather'):
try:
logging.info(f"Setting weather to {weather_data['weatherType']} for guild {guild_id}")
await bot.prc_api.run_command(guild_id, f":weather {weather_data['weatherType']}")
logging.info(f"Successfully set weather for guild {guild_id}")
except ResponseFailure as e:
logging.error(f"Failed to sync weather for guild {guild_id}: {str(e)}")

if weather_settings.get('sync_time'):
try:
logging.info(f"Setting time to {weather_data['time']} for guild {guild_id}")
await bot.prc_api.run_command(guild_id, f":time {weather_data['time']}")
logging.info(f"Successfully set time for guild {guild_id}")
except ResponseFailure as e:
logging.error(f"Failed to sync time for guild {guild_id}: {str(e)}")

except Exception as e:
logging.error(f"Error syncing weather for guild {guild_id}: {str(e)}", exc_info=True)

logging.info(f"Weather sync task completed. Processed {processed}/{server_count} servers")

except Exception as e:
logging.error(f"Critical error in weather sync task: {str(e)}", exc_info=True)

0 comments on commit dbd41d8

Please sign in to comment.