Fix tasks, logger dependency injection

This commit is contained in:
Zeva Rose 2022-02-19 16:56:17 -07:00
parent c3c3c4a191
commit e9cd48a21c
4 changed files with 29 additions and 8 deletions

View file

@ -1,21 +1,23 @@
"""JARVIS ban tasks.""" """JARVIS ban tasks."""
import asyncio import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
from logging import Logger
from dis_snek import Snake from dis_snek import Snake
from jarvis_core.db import q from jarvis_core.db import q
from jarvis_core.db.models import Ban, Unban from jarvis_core.db.models import Ban, Unban
async def unban(bot: Snake) -> None: async def unban(bot: Snake, logger: Logger) -> None:
""" """
Unban users when ban expires. Unban users when ban expires.
Args: Args:
bot: Snake instance bot: Snake instance
logger: Global logger
""" """
while True: while True:
asyncio.sleep(600) await asyncio.sleep(600)
max_time = datetime.utcnow() + timedelta(minutes=10) max_time = datetime.utcnow() + timedelta(minutes=10)
bans = Ban.find(q(type="temp", active=True)) bans = Ban.find(q(type="temp", active=True))
async for ban in bans: async for ban in bans:

View file

@ -1,6 +1,7 @@
"""JARVIS reminders.""" """JARVIS reminders."""
import asyncio import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
from logging import Logger
from dis_snek import Snake from dis_snek import Snake
from jarvis_core.db import q from jarvis_core.db import q
@ -8,12 +9,13 @@ from jarvis_core.db.models import Reminder
from jarvis_core.util import build_embed from jarvis_core.util import build_embed
async def remind(bot: Snake) -> None: async def remind(bot: Snake, logger: Logger) -> None:
""" """
Run reminders in the background. Run reminders in the background.
Args: Args:
bot: Snake instance bot: Snake instance
logger: Global logger
""" """
while True: while True:
await asyncio.sleep(5) await asyncio.sleep(5)
@ -23,6 +25,7 @@ async def remind(bot: Snake) -> None:
async for reminder in reminders: async for reminder in reminders:
user = await bot.fetch_user(reminder.user) user = await bot.fetch_user(reminder.user)
if not user: if not user:
logger.debug(f"Failed to get user with ID {reminder.user}")
await reminder.delete() await reminder.delete()
continue continue
@ -37,20 +40,32 @@ async def remind(bot: Snake) -> None:
try: try:
await user.send(embed=embed) await user.send(embed=embed)
logger.debug(f"Reminder {reminder.id} sent to user")
await reminder.delete()
except Exception: except Exception:
logger.debug("User has closed DMs")
guild = await bot.fetch_guild(reminder.guild) guild = await bot.fetch_guild(reminder.guild)
member = await bot.fetch_member(user.id) member = await bot.fetch_member(user.id)
if not member: if not member:
logger.debug("User no longer member of origin guild, deleting reminder")
await reminder.delete()
continue continue
channel = await guild.fetch_channel(reminder.channel) if guild else None channel = await guild.fetch_channel(reminder.channel) if guild else None
if channel and not reminder.private: if channel and not reminder.private:
await channel.send(f"{member.mention}", embed=embed) await channel.send(f"{member.mention}", embed=embed)
logger.debug(f"Reminder {reminder.id} sent to origin channel")
await reminder.delete() await reminder.delete()
else: elif channel:
await channel.send( await channel.send(
f"{member.mention}, you had a private reminder set for now," f"{member.mention}, you had a private reminder set for now,"
" but I couldn't send it to you.\n" " but I couldn't send it to you.\n"
f"Use `/reminder fetch {str(reminder.id)}` to view" f"Use `/reminder fetch {str(reminder.id)}` to view"
) )
logger.debug(
f"Reminder {reminder.id} private, sent notification to origin channel"
)
reminder.update(q(active=False)) reminder.update(q(active=False))
await reminder.commit() await reminder.commit()
else:
logger.debug("No way to contact user, deleting reminder")
await reminder.delete()

View file

@ -1,6 +1,7 @@
"""JARVIS Twitter sync.""" """JARVIS Twitter sync."""
import asyncio import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
from logging import Logger
import tweepy import tweepy
from dis_snek import Snake from dis_snek import Snake
@ -12,18 +13,19 @@ from jarvis_tasks.config import TaskConfig
config = TaskConfig.from_yaml() config = TaskConfig.from_yaml()
async def twitter(self, bot: "Snake") -> None: async def twitter(bot: Snake, logger: Logger) -> None:
""" """
Sync tweets in the background. Sync tweets in the background.
Args: Args:
bot: Snake instance bot: Snake instance
logger: Global logger
""" """
auth = tweepy.AppAuthHandler(config.twitter["consumer_key"], config.twitter["consumer_secret"]) auth = tweepy.AppAuthHandler(config.twitter["consumer_key"], config.twitter["consumer_secret"])
api = tweepy.API(auth) api = tweepy.API(auth)
while True: while True:
# Only check once a minute # Only check once a minute
asyncio.sleep(60) await asyncio.sleep(60)
accounts = TwitterAccount.find() accounts = TwitterAccount.find()
accounts_to_delete = [] accounts_to_delete = []

View file

@ -1,21 +1,23 @@
"""JARVIS warnings tasks.""" """JARVIS warnings tasks."""
import asyncio import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
from logging import Logger
from dis_snek import Snake from dis_snek import Snake
from jarvis_core.db import q from jarvis_core.db import q
from jarvis_core.db.models import Warning from jarvis_core.db.models import Warning
async def unwarn(bot: Snake) -> None: async def unwarn(bot: Snake, logger: Logger) -> None:
""" """
Deactivate warnings when they expire. Deactivate warnings when they expire.
Args: Args:
bot: Snake instance bot: Snake instance
logger: Global logger
""" """
while True: while True:
asyncio.sleep(3600) await asyncio.sleep(3600)
warns = Warning.find(q(active=True)) warns = Warning.find(q(active=True))
async for warn in warns: async for warn in warns:
if warn.created_at + timedelta(hours=warn.duration) < datetime.utcnow(): if warn.created_at + timedelta(hours=warn.duration) < datetime.utcnow():