Skip to content

Commit

Permalink
fix: make scheduled tasks purely optional
Browse files Browse the repository at this point in the history
  • Loading branch information
huenique committed Nov 4, 2021
1 parent 9ef58bf commit a603e07
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 37 deletions.
4 changes: 2 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ BOT_TOKEN=your_bot_token
DATABASE_URL=postgresql+asyncpg://{user}:{password}@{hostname}:{port}/{database-name}

# required when fetching content on email subscription
EMAIL=your_email
EMAIL_PASSWORD=password_for_your_email_account
EMAIL=
EMAIL_PASSWORD=
6 changes: 4 additions & 2 deletions app.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
"description": "The jumble of letters and numbers that acts as a key to controlling a Discord Bot"
},
"EMAIL": {
"description": "The email address subscribed to a service (i.e. Medium Daily Digest)"
"description": "The email address subscribed to a service (i.e. Medium Daily Digest)",
"required": false
},
"EMAIL_PASSWORD": {
"description": "The email account's password."
"description": "The email account's password.",
"required": false
}
},
"formation": {
Expand Down
14 changes: 0 additions & 14 deletions dayong/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,6 @@
from sqlmodel.engine.result import ScalarResult


class Client(ABC):
"""Interface for a client class supporting any third-party service."""

@staticmethod
@abstractmethod
async def get_content(data: Any, *args: Any, **kwargs: Any) -> Any:
"""Parse response data from a web request for specific content or detail.
Returns:
Any: Part of the response data.
"""
raise NotImplementedError


class DBProto(ABC):
"""Protocol for a generic database interface."""

Expand Down
20 changes: 14 additions & 6 deletions dayong/components/task_component.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
task_manager = TaskManager()
ext_instance: dict[str, Any] = {}

RESPONSE_INTVL = 30
RESPONSE_INTVL = 60
RESPONSE_MESSG = {False: "Sorry, I got nothing for today 😔"}


Expand Down Expand Up @@ -92,13 +92,12 @@ async def _devto_article(ctx: tanjun.abc.SlashContext, *args: Any) -> NoReturn:

while True:
articles = await client.get_devto_article()
content = articles.content
await _set_ext_loop(ctx, content, response_intvl)
await _set_ext_loop(ctx, articles.content, response_intvl)


async def _medium_daily_digest(
ctx: tanjun.abc.SlashContext, config: DayongConfig
) -> NoReturn:
) -> Union[NoReturn, None]:
"""Async wrapper for `dayong.tasks.get_medium_daily_digest()`.
This coroutine is tasked to retrieve medium content on email subscription and
Expand All @@ -109,12 +108,21 @@ async def _medium_daily_digest(
config (DayongConfig): Instance of `dayong.configs.DayongConfig`.
"""
response_intvl = await _set_response_intvl()
email = config.email
email_password = config.email_password

if email is None or email_password is None:
await ctx.respond(
"Can't retrieve content. Please check for missing email credentials 😕"
)
return

client = await _set_ext_instance(
EmailClient.__name__,
EmailClient,
config.imap_domain_name,
config.email,
config.email_password,
email_password,
)
assert isinstance(client, EmailClient)

Expand Down Expand Up @@ -218,7 +226,7 @@ async def share_content(
await ctx.respond(
f"I'll comeback here to deliver content from `{source}` 📰"
)
except RuntimeError:
except PermissionError:
await ctx.respond("I'm already doing that 👌")
elif action == "stop":
task_manager.stop_task(task_nm)
Expand Down
12 changes: 7 additions & 5 deletions dayong/configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"""
import json
import os
from typing import Any, Union
from typing import Any, Optional, Union

from pydantic import BaseModel

Expand All @@ -29,8 +29,8 @@ class EnvironVariables(BaseModel):

bot_token: str
database_uri: str
email: str
email_password: str
email: Optional[str] = None
email_password: Optional[str] = None


class DayongConfig(EnvironVariables, ConfigFile):
Expand All @@ -43,13 +43,15 @@ def load(cls, **kwargs: Any) -> "DayongConfig":
Returns:
An instance of `dayong.configs.DayongConfig`.
"""
email = kwargs.get("email")
email_password = kwargs.get("email_password")
return cls(
bot_prefix=kwargs["bot_prefix"],
bot_token=kwargs["bot_token"],
database_uri=kwargs["database_uri"],
embeddings=kwargs["embeddings"],
email=kwargs["email"],
email_password=kwargs["email_password"],
email=email if email else None,
email_password=email_password if email_password else None,
guild_id=kwargs["guild_id"],
imap_domain_name=kwargs["imap_domain_name"],
)
Expand Down
6 changes: 0 additions & 6 deletions dayong/tasks/celery.py

This file was deleted.

4 changes: 2 additions & 2 deletions dayong/tasks/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
dayong.tasks.manager
~~~~~~~~~~~~~~~~~~~~
Task managers for coroutines.
Custom implementation of background task managers.
"""
import asyncio
from asyncio.tasks import Task
Expand Down Expand Up @@ -43,7 +43,7 @@ async def start_task(
tuple[str, Task[Any]]: The task name and `asyncio.Task` object.
"""
if task_name in self.tasks:
raise RuntimeError
raise PermissionError

async def wrapped_coro():
try:
Expand Down

0 comments on commit a603e07

Please sign in to comment.