Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Space Cog implementing #364

Merged
merged 42 commits into from Mar 31, 2020
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
e4296ed
Added Space Cog
ks129 Feb 29, 2020
5b05592
Added NASA API Key to constants.py
ks129 Feb 29, 2020
0aef9fe
(Space Cog): Added NASA API key check on load, added logger
ks129 Feb 29, 2020
1fc0b1c
(Space Cog): Added NASA API base URL and .apod command HTTP request d…
ks129 Feb 29, 2020
1b3f274
(Space Cog): Added fetch_from_nasa function to space.py, what do requ…
ks129 Feb 29, 2020
7c15f14
(Space Cog): Created .apod command that support date parameter.
ks129 Feb 29, 2020
1575b79
(Space Cog): Created get_random_nasa_item function what will be used …
ks129 Feb 29, 2020
698f78e
(Space Cog): Added .nasa command that show information and facts abou…
ks129 Feb 29, 2020
2d82c35
(Space Cog): Added .earth command, created new base URL: NASA Epic AP…
ks129 Feb 29, 2020
0c33dc3
(Space Cog): Added .mars command, removed get_random_nasa_command (no…
ks129 Feb 29, 2020
106bbcc
(Space Cog): Modified base URLs (removed slash at end, added to queri…
ks129 Feb 29, 2020
95a43dd
(Space Cog): Renamed + fixed base URLs constants
ks129 Mar 2, 2020
904e465
(Space Cog): .apod Command Fixes: Renamed default parameters constant…
ks129 Mar 2, 2020
3efc262
(Space Cog): Fixes with random module. Removed manual random list ite…
ks129 Mar 2, 2020
e5f6ed6
(Space Cog): Created head command `.space` and added all other comman…
ks129 Mar 7, 2020
2d95e9b
(Space Cog): Renamed `.space earth` command to `.space epic` for upco…
ks129 Mar 7, 2020
8d0f141
(Space Cog): Improved `.space mars` command, added possibility for SO…
ks129 Mar 7, 2020
769ee66
(Space Cog): Added `invoke_without_command` parameter to `.space` com…
ks129 Mar 7, 2020
266bcaa
(Space Cog): Added date parameter to `.space epic` command.
ks129 Mar 7, 2020
ca77b34
(Space Cog): Added optional search term to `.space nasa` command, rem…
ks129 Mar 7, 2020
7bf4984
Merge branch 'master' into space-cog
ks129 Mar 7, 2020
2c4c472
(Space Cog): Removed unnecessary sentence from `.mars` command docstring
ks129 Mar 10, 2020
6e7e873
(Space Cog): Add base URL parameter to helper function `fetch_from_nasa`
ks129 Mar 11, 2020
4ecacdc
(Space Cog): Created task for `.mars` command rovers fetching one tim…
ks129 Mar 11, 2020
a3e6e5c
(Space Cog): Added `.space mars dates` command to see what rovers is …
ks129 Mar 11, 2020
4b4616a
(Space Cog): Removed unnecessary part of `.space mars` docstring due …
ks129 Mar 11, 2020
5cf725a
(Space Cog): Add `self.rovers` using to `.space mars` command check.
ks129 Mar 11, 2020
906288a
(Space Cog): Fix `DateConverter`'s docstring
ks129 Mar 11, 2020
1aaeec4
(Space Cog): Add `.space mars dates` information to `.space mars` com…
ks129 Mar 11, 2020
4e3f756
(Space Cog): Added rovers aliases to `.space mars dates` command
ks129 Mar 11, 2020
90ecfb0
(Space Cog): Added information about when date is not specified to `.…
ks129 Mar 11, 2020
9e3f043
(Space Cog): Create new helper function `create_nasa_embed` and apply…
ks129 Mar 11, 2020
5761cc5
(Space Cog): Use `fetch_from_nasa` in every command + make modificati…
ks129 Mar 11, 2020
4ec0093
(Space Cog): Clean comments
ks129 Mar 11, 2020
570cb89
Merge remote-tracking branch 'origin/space-cog' into space-cog
ks129 Mar 11, 2020
7950640
(Space Cog): Fixed function signatures and `ctx.send` `embed` value f…
ks129 Mar 14, 2020
783b85d
(Space Cog): Refactored url query parameters system, apply changes to…
ks129 Mar 14, 2020
0745886
(Space Cog): Removed date requirement from `.space mars` command. Now…
ks129 Mar 14, 2020
0acd912
Merge branch 'master' into space-cog
sco1 Mar 20, 2020
522e1c6
(Space Cog): Added `get_rovers` task canceling with `cog_unload` func…
ks129 Mar 31, 2020
e82daf0
(Space Cog): Removed `async` from `create_nasa_embed` function.
ks129 Mar 31, 2020
0a29c39
Merge branch 'master' into space-cog
ikuyarihS Mar 31, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions bot/constants.py
Expand Up @@ -134,6 +134,7 @@ class Tokens(NamedTuple):
omdb = environ.get("OMDB_API_KEY")
youtube = environ.get("YOUTUBE_API_KEY")
tmdb = environ.get("TMDB_API_KEY")
nasa = environ.get("NASA_API_KEY")


# Default role combinations
Expand Down
154 changes: 154 additions & 0 deletions bot/seasons/evergreen/space.py
@@ -0,0 +1,154 @@
import logging
from datetime import datetime
from random import randint
from typing import Any, Dict, Optional
from urllib.parse import urlencode

from discord import Embed
from discord.ext.commands import Cog, Context, command

from bot.bot import SeasonalBot
from bot.constants import Tokens

logger = logging.getLogger(__name__)

# NASA API base URL
BASE_URL = "https://api.nasa.gov"
NASA_IMAGES_BASE = "https://images-api.nasa.gov"
EPIC_BASE_URL = "https://epic.gsfc.nasa.gov"
ks129 marked this conversation as resolved.
Show resolved Hide resolved

# Default Parameters:
# .apod command default request parameters
APOD_PARAMS = {
ks129 marked this conversation as resolved.
Show resolved Hide resolved
"api_key": Tokens.nasa,
"hd": True
ks129 marked this conversation as resolved.
Show resolved Hide resolved
}


class Space(Cog):
"""Space Cog contains commands, that show images, facts or other information about space."""

def __init__(self, bot: SeasonalBot):
self.bot = bot
self.http_session = bot.http_session

@command(name="apod")
async def apod(self, ctx: Context, date: Optional[str] = None) -> None:
"""Get Astronomy Picture of Day from NASA API. Date is optional parameter, what formatting is YYYY-MM-DD."""
ks129 marked this conversation as resolved.
Show resolved Hide resolved
# Make copy of parameters
params = APOD_PARAMS.copy()
# Parse date to params, when provided. Show error message when invalid formatting
if date:
try:
params["date"] = datetime.strptime(date, "%Y-%m-%d").date().isoformat()
except ValueError:
await ctx.send(f"Invalid date {date}. Please make sure your date is in format YYYY-MM-DD.")
return

# Do request to NASA API
result = await self.fetch_from_nasa("planetary/apod", params)

# Create embed from result
embed = Embed(title=f"Astronomy Picture of Day in {result['date']}", description=result["explanation"])
ks129 marked this conversation as resolved.
Show resolved Hide resolved
embed.set_image(url=result["hdurl"])
embed.set_footer(text="Powered by NASA API")

await ctx.send(embed=embed)

@command(name="nasa")
async def nasa(self, ctx: Context) -> None:
"""Get random NASA information/facts + image."""
page = randint(1, 50)
ks129 marked this conversation as resolved.
Show resolved Hide resolved

# Create params for request, create URL and do request
params = {
"media_type": "image",
"page": page
}
async with self.http_session.get(url=f"{NASA_IMAGES_BASE}/search?{urlencode(params)}") as resp:
data = await resp.json()

# Get (random) item from result, that will be shown
item = data["collection"]["items"][randint(0, len(data["collection"]["items"]) - 1)]
ks129 marked this conversation as resolved.
Show resolved Hide resolved

# Create embed and send it
embed = Embed(title=item["data"][0]["title"], description=item["data"][0]["description"])
ks129 marked this conversation as resolved.
Show resolved Hide resolved
embed.set_image(url=item["links"][0]["href"])
embed.set_footer(text="Powered by NASA API")

await ctx.send(embed=embed)

@command(name="earth")
async def earth(self, ctx: Context) -> None:
"""Get one of latest random image of earth from NASA API."""
# Generate URL and make request to API
async with self.http_session.get(url=f"{EPIC_BASE_URL}/api/natural") as resp:
data = await resp.json()

# Get random item from result that will be shown
item = data[randint(0, len(data) - 1)]
ks129 marked this conversation as resolved.
Show resolved Hide resolved

# Split date for image URL
year, month, day = item["date"].split(" ")[0].split("-")

image_url = f"{EPIC_BASE_URL}/archive/natural/{year}/{month}/{day}/jpg/{item['image']}.jpg"

# Create embed, fill and send it
embed = Embed(title="Earth Image", description=item["caption"])
embed.set_image(url=image_url)
embed.set_footer(text=f"Identifier: {item['identifier']} \u2022 Powered by NASA API")

await ctx.send(embed=embed)

@command(name="mars")
async def mars(self, ctx: Context, date: str) -> None:
"""
Get random Mars image by date.

Date formatting is YYYY-MM-DD. Current max date is 2019-09-28 and min 2012-08-06.
"""
# Create API request parameters, try to parse date
params = {
"api_key": Tokens.nasa
}
try:
params["earth_date"] = datetime.strptime(date, "%Y-%m-%d")
except ValueError:
await ctx.send(f"Invalid date {date}. Please make sure your date is in format YYYY-MM-DD.")
return

result = await self.fetch_from_nasa("mars-photos/api/v1/rovers/curiosity/photos", params)

# Check for empty result
if len(result["photos"]) < 1:
err_msg = (
f"We can't find result in date {date}. "
"**Note:** Current dates must in range 2012-08-06 and 2019-09-28."
)
await ctx.send(err_msg)
return

# Get random item from result, generate embed with it and send
item = result["photos"][randint(0, len(result["photos"]) - 1)]
ks129 marked this conversation as resolved.
Show resolved Hide resolved

embed = Embed(title=f"{item['rover']['name']}'s {item['camera']['full_name']} Mars Image")
embed.set_image(url=item["img_src"])
embed.set_footer(text="Powered by NASA API")

await ctx.send(embed=embed)

async def fetch_from_nasa(self, endpoint: str, params: Dict[str, Any]) -> Dict[str, Any]:
"""Fetch information from NASA API, return result."""
# Generate request URL from base URL, endpoint and parsed params
async with self.http_session.get(url=f"{BASE_URL}/{endpoint}?{urlencode(params)}") as resp:
return await resp.json()


def setup(bot: SeasonalBot) -> None:
"""Load Space Cog."""
# Check does bot have NASA API key in .env, when not, don't load Cog and print warning
if not Tokens.nasa:
logger.warning("Can't find NASA API key. Not loading Space Cog.")
return

bot.add_cog(Space(bot))