Skip to content

Commit 41ec5fe

Browse files
feat(tasks)!: remove unused tasks (#405)
1 parent eb51859 commit 41ec5fe

File tree

7 files changed

+0
-280
lines changed

7 files changed

+0
-280
lines changed

README.md

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,6 @@ platforms such as GitHub discussions/issues might be added in the future.
3939

4040
| variable | required | default | description |
4141
|----------------------------------|----------|------------------------------------------------------|--------------------------------------------------------------------------------------------|
42-
| DAILY_TASKS | False | `true` | Daily tasks on or off. |
43-
| DAILY_RELEASES | False | `true` | Send a message for each game released on this day in history. |
44-
| DAILY_CHANNEL_ID | False | `None` | Required if daily_tasks is enabled. |
45-
| DAILY_TASKS_UTC_HOUR | False | `12` | The hour to run daily tasks. |
4642
| DATA_REPO | False | `https://github.com/LizardByte/support-bot-data` | Repository to store persistent data. This repository should be private! |
4743
| DATA_REPO_BRANCH | False | `master` | Branch to store persistent data. |
4844
| DISCORD_BOT_TOKEN | True | `None` | Token from Bot page on discord developer portal. |
@@ -61,8 +57,6 @@ platforms such as GitHub discussions/issues might be added in the future.
6157
| GITHUB_TOKEN | True | `None` | GitHub personal access token. Must have `read:org` |
6258
| GITHUB_WEBHOOK_SECRET_KEY | True | `None` | A secret value to ensure webhooks are from trusted sources. |
6359
| GRAVATAR_EMAIL | False | `None` | Gravatar email address for bot avatar. |
64-
| IGDB_CLIENT_ID | False | `None` | Required if daily_releases is enabled. |
65-
| IGDB_CLIENT_SECRET | False | `None` | Required if daily_releases is enabled. |
6660
| PRAW_CLIENT_ID | True | `None` | `client_id` from reddit app setup page. |
6761
| PRAW_CLIENT_SECRET | True | `None` | `client_secret` from reddit app setup page. |
6862
| PRAW_SUBREDDIT | True | `None` | Subreddit to monitor (reddit user should be moderator of the subreddit) |

requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
cryptography==44.0.3
22
Flask==3.1.1
33
GitPython==3.1.44
4-
igdb-api-v4==0.3.3
54
libgravatar==1.0.4
65
mistletoe==1.4.0
76
praw==7.8.1

src/discord_bot/bot.py

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ def __init__(self, *args, **kwargs):
4040
self.ephemeral_db = {}
4141
self.oauth_states = {}
4242
self.clean_ephemeral_cache = tasks.clean_ephemeral_cache
43-
self.daily_task = tasks.daily_task
4443
self.role_update_task = tasks.role_update_task
4544

4645
self.load_extension(
@@ -74,16 +73,6 @@ async def on_ready(self):
7473
self.clean_ephemeral_cache.start(bot=self)
7574
self.role_update_task.start(bot=self)
7675

77-
try:
78-
os.environ['DAILY_TASKS']
79-
except KeyError:
80-
self.daily_task.start(bot=self)
81-
else:
82-
if os.environ['DAILY_TASKS'].lower() == 'true':
83-
self.daily_task.start(bot=self)
84-
else:
85-
print("'DAILY_TASKS' environment variable is disabled")
86-
8776
await self.sync_commands()
8877

8978
async def async_send_message(
@@ -284,7 +273,6 @@ def start_threaded(self):
284273
def stop(self, future: asyncio.Future = None):
285274
print("Attempting to stop tasks")
286275
self.DEGRADED = True
287-
self.daily_task.stop()
288276
self.role_update_task.stop()
289277
self.clean_ephemeral_cache.stop()
290278
print("Attempting to close bot connection")

src/discord_bot/helpers.py

Lines changed: 0 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -4,55 +4,6 @@
44
# lib imports
55
import requests
66

7-
# convert month number to igdb human-readable month
8-
month_dictionary = {
9-
1: 'Jan',
10-
2: 'Feb',
11-
3: 'Mar',
12-
4: 'Apr',
13-
5: 'May',
14-
6: 'Jun',
15-
7: 'Jul',
16-
8: 'Aug',
17-
9: 'Sep',
18-
10: 'Oct',
19-
11: 'Nov',
20-
12: 'Dec'
21-
}
22-
23-
24-
def igdb_authorization(client_id: str, client_secret: str) -> Any:
25-
"""
26-
Authorization for IGDB.
27-
28-
Return an authorization dictionary for the IGDB api.
29-
30-
Parameters
31-
----------
32-
client_id : str
33-
IGDB/Twitch API client id.
34-
client_secret : str
35-
IGDB/Twitch client secret.
36-
37-
Returns
38-
-------
39-
Any
40-
Authorization dictionary.
41-
"""
42-
grant_type = 'client_credentials'
43-
44-
auth_headers = {
45-
'Accept': 'application/json',
46-
'client_id': client_id,
47-
'client_secret': client_secret,
48-
'grant_type': grant_type
49-
}
50-
51-
token_url = 'https://id.twitch.tv/oauth2/token'
52-
53-
authorization = post_json(url=token_url, headers=auth_headers)
54-
return authorization
55-
567

578
def get_json(url: str) -> Any:
589
"""
@@ -74,25 +25,3 @@ def get_json(url: str) -> Any:
7425
data = res.json()
7526

7627
return data
77-
78-
79-
def post_json(url: str, headers: dict) -> Any:
80-
"""
81-
Make a POST request and get the response in json.
82-
83-
Makes a POST request with given headers to the given url.
84-
85-
Parameters
86-
----------
87-
url : str
88-
The url for the POST request.
89-
headers : dict
90-
Headers for the POST request.
91-
92-
Returns
93-
-------
94-
Any
95-
The json response.
96-
"""
97-
result = requests.post(url=url, data=headers).json()
98-
return result

src/discord_bot/tasks.py

Lines changed: 0 additions & 154 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,14 @@
22
import asyncio
33
import copy
44
from datetime import datetime, UTC
5-
import json
6-
import os
75

86
# lib imports
97
import discord
108
from discord.ext import tasks
11-
from igdb.wrapper import IGDBWrapper
129

1310
# local imports
14-
from src.common.common import avatar, bot_name, bot_url, colors
1511
from src.common import sponsors
1612
from src.discord_bot.bot import Bot
17-
from src.discord_bot.helpers import igdb_authorization, month_dictionary
1813

1914

2015
@tasks.loop(seconds=30)
@@ -32,155 +27,6 @@ async def clean_ephemeral_cache(bot: Bot) -> bool:
3227
return True
3328

3429

35-
@tasks.loop(minutes=60.0)
36-
async def daily_task(bot: Bot) -> bool:
37-
"""
38-
Run daily task loop.
39-
40-
This function runs on a schedule, every 60 minutes. Create an embed and thread for each game released
41-
on this day in history (according to IGDB), if enabled.
42-
43-
Returns
44-
-------
45-
bool
46-
True if the task ran successfully, False otherwise.
47-
"""
48-
date = datetime.now(UTC)
49-
if date.hour != int(os.getenv(key='DAILY_TASKS_UTC_HOUR', default=12)):
50-
return False
51-
52-
daily_releases = True if os.getenv(key='DAILY_RELEASES', default='true').lower() == 'true' else False
53-
if not daily_releases:
54-
print("'DAILY_RELEASES' environment variable is disabled")
55-
return False
56-
57-
try:
58-
channel_id = int(os.environ['DAILY_CHANNEL_ID'])
59-
except KeyError:
60-
print("'DAILY_CHANNEL_ID' not defined in environment variables.")
61-
return False
62-
63-
igdb_auth = igdb_authorization(client_id=os.environ['IGDB_CLIENT_ID'],
64-
client_secret=os.environ['IGDB_CLIENT_SECRET'])
65-
wrapper = IGDBWrapper(client_id=os.environ['IGDB_CLIENT_ID'], auth_token=igdb_auth['access_token'])
66-
67-
end_point = 'release_dates'
68-
fields = [
69-
'human',
70-
'game.name',
71-
'game.summary',
72-
'game.url',
73-
'game.genres.name',
74-
'game.rating',
75-
'game.cover.url',
76-
'game.artworks.url',
77-
'game.platforms.name',
78-
'game.platforms.url'
79-
]
80-
81-
where = f'human="{month_dictionary[date.month]} {date.day:02d}"*'
82-
limit = 500
83-
query = f'fields {", ".join(fields)}; where {where}; limit {limit};'
84-
85-
byte_array = bytes(wrapper.api_request(endpoint=end_point, query=query))
86-
json_result = json.loads(byte_array)
87-
88-
game_ids = []
89-
90-
for game in json_result:
91-
try:
92-
game_id = game['game']['id']
93-
except KeyError:
94-
continue
95-
96-
if game_id in game_ids:
97-
continue # do not repeat the same game... even though it could be a different platform
98-
game_ids.append(game_id)
99-
100-
try:
101-
embed = discord.Embed(
102-
title=game['game']['name'],
103-
url=game['game']['url'],
104-
description=game['game']['summary'][0:2000 - 1],
105-
color=colors['purple']
106-
)
107-
except KeyError:
108-
continue
109-
110-
try:
111-
rating = round(game['game']['rating'] / 20, 1)
112-
embed.add_field(
113-
name='Average Rating',
114-
value=f'⭐{rating}',
115-
inline=True
116-
)
117-
except KeyError:
118-
continue
119-
if rating < 4.0: # reduce the number of messages per day
120-
continue
121-
122-
try:
123-
embed.add_field(
124-
name='Release Date',
125-
value=game['human'],
126-
inline=True
127-
)
128-
except KeyError:
129-
pass
130-
131-
try:
132-
embed.set_thumbnail(url=f"https:{game['game']['cover']['url'].replace('_thumb', '_original')}")
133-
except KeyError:
134-
pass
135-
136-
try:
137-
embed.set_image(url=f"https:{game['game']['artworks'][0]['url'].replace('_thumb', '_original')}")
138-
except KeyError:
139-
pass
140-
141-
try:
142-
platforms = ', '.join(platform['name'] for platform in game['game']['platforms'])
143-
name = 'Platforms' if len(game['game']['platforms']) > 1 else 'Platform'
144-
145-
embed.add_field(
146-
name=name,
147-
value=platforms,
148-
inline=False
149-
)
150-
except KeyError:
151-
pass
152-
153-
try:
154-
genres = ', '.join(genre['name'] for genre in game['game']['genres'])
155-
name = 'Genres' if len(game['game']['genres']) > 1 else 'Genre'
156-
157-
embed.add_field(
158-
name=name,
159-
value=genres,
160-
inline=False
161-
)
162-
except KeyError:
163-
pass
164-
165-
embed.set_author(
166-
name=bot_name,
167-
url=bot_url,
168-
icon_url=avatar
169-
)
170-
171-
embed.set_footer(
172-
text='Data provided by IGDB',
173-
icon_url='https://www.igdb.com/favicon-196x196.png'
174-
)
175-
176-
message = bot.send_message(channel_id=channel_id, embed=embed)
177-
thread = bot.create_thread(message=message, name=embed.title)
178-
179-
print(f'thread created: {thread.name}')
180-
181-
return True
182-
183-
18430
@tasks.loop(minutes=1.0)
18531
async def role_update_task(bot: Bot, test_mode: bool = False) -> bool:
18632
"""

tests/conftest.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ def discord_bot():
2626
time.sleep(1)
2727

2828
bot.role_update_task.stop()
29-
bot.daily_task.stop()
3029
bot.clean_ephemeral_cache.stop()
3130

3231
yield bot

tests/unit/discord/test_tasks.py

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,6 @@ def set_env_variable(env_var_name, request):
2121
del os.environ[env_var_name]
2222

2323

24-
@pytest.fixture(scope='function')
25-
def set_daily_channel_id(request):
26-
yield from set_env_variable('DAILY_CHANNEL_ID', request)
27-
28-
29-
@pytest.fixture(scope='function')
30-
def set_daily_releases(request):
31-
yield from set_env_variable('DAILY_RELEASES', request)
32-
33-
3424
@pytest.mark.asyncio
3525
@pytest.mark.parametrize("db_start, expected_keys", [
3626
(
@@ -85,31 +75,6 @@ async def test_clean_ephemeral_cache(discord_bot, mocker, db_start, expected_key
8575
assert v['expires_at'] >= datetime.now(UTC) - timedelta(minutes=5), f"Key {k} should not have expired"
8676

8777

88-
@pytest.mark.asyncio
89-
@pytest.mark.parametrize("skip, set_daily_releases, set_daily_channel_id, expected", [
90-
(True, 'false', None, False),
91-
(False, 'false', None, False),
92-
(False, 'true', None, False),
93-
(False, 'true', os.environ['DISCORD_GITHUB_STATUS_CHANNEL_ID'], True),
94-
], indirect=["set_daily_releases", "set_daily_channel_id"])
95-
async def test_daily_task(discord_bot, mocker, skip, set_daily_releases, set_daily_channel_id, expected):
96-
"""
97-
WHEN the daily task is called
98-
THEN check that the task runs without error
99-
"""
100-
# Patch datetime.datetime at the location where it's imported in `tasks`
101-
mock_datetime = mocker.patch('src.discord_bot.tasks.datetime', autospec=True)
102-
mock_datetime.now.return_value = datetime(2023, 1, 1, 1 if skip else 12, 0, 0, tzinfo=timezone.utc)
103-
104-
# Run the daily task
105-
result = await tasks.daily_task(bot=discord_bot)
106-
107-
assert result is expected
108-
109-
# Verify that datetime.now() was called
110-
mock_datetime.now.assert_called_once()
111-
112-
11378
@pytest.mark.asyncio
11479
@pytest.mark.parametrize("skip", [True, False])
11580
async def test_role_update_task(discord_bot, discord_db_users, mocker, skip):

0 commit comments

Comments
 (0)