aboutsummaryrefslogtreecommitdiffstats
path: root/bot/cogs
diff options
context:
space:
mode:
Diffstat (limited to 'bot/cogs')
-rw-r--r--bot/cogs/hacktoberstats.py9
-rw-r--r--bot/cogs/halloween_facts.py75
-rw-r--r--bot/cogs/halloweenify.py9
-rw-r--r--bot/cogs/movie.py89
-rw-r--r--bot/cogs/spookyreact.py31
-rw-r--r--bot/cogs/template.py2
6 files changed, 183 insertions, 32 deletions
diff --git a/bot/cogs/hacktoberstats.py b/bot/cogs/hacktoberstats.py
index 4e896ae9..ac81b887 100644
--- a/bot/cogs/hacktoberstats.py
+++ b/bot/cogs/hacktoberstats.py
@@ -95,7 +95,14 @@ class Stats:
is_query = f"public+author:{username}"
date_range = "2018-10-01..2018-10-31"
per_page = "300"
- query_url = f"{base_url}-label:{not_label}+type:{action_type}+is:{is_query}+created:{date_range}&per_page={per_page}"
+ query_url = (
+ f"{base_url}"
+ f"-label:{not_label}"
+ f"+type:{action_type}"
+ f"+is:{is_query}"
+ f"+created:{date_range}"
+ f"&per_page={per_page}"
+ )
headers = {"user-agent": "Discord Python Hactoberbot"}
async with aiohttp.ClientSession() as session:
diff --git a/bot/cogs/halloween_facts.py b/bot/cogs/halloween_facts.py
new file mode 100644
index 00000000..e97c80d2
--- /dev/null
+++ b/bot/cogs/halloween_facts.py
@@ -0,0 +1,75 @@
+import asyncio
+import json
+import random
+from datetime import timedelta
+from pathlib import Path
+
+import discord
+from discord.ext import commands
+
+SPOOKY_EMOJIS = [
+ "\N{BAT}",
+ "\N{DERELICT HOUSE BUILDING}",
+ "\N{EXTRATERRESTRIAL ALIEN}",
+ "\N{GHOST}",
+ "\N{JACK-O-LANTERN}",
+ "\N{SKULL}",
+ "\N{SKULL AND CROSSBONES}",
+ "\N{SPIDER WEB}",
+]
+PUMPKIN_ORANGE = discord.Color(0xFF7518)
+HACKTOBERBOT_CHANNEL_ID = 498804484324196362
+INTERVAL = timedelta(hours=6).total_seconds()
+
+
+class HalloweenFacts:
+
+ def __init__(self, bot):
+ self.bot = bot
+ with open(Path("./bot/resources", "halloween_facts.json"), "r") as file:
+ self.halloween_facts = json.load(file)
+ self.channel = None
+ self.last_fact = None
+
+ async def on_ready(self):
+ self.channel = self.bot.get_channel(HACKTOBERBOT_CHANNEL_ID)
+ self.bot.loop.create_task(self._fact_publisher_task())
+
+ async def _fact_publisher_task(self):
+ """
+ A background task that runs forever, sending Halloween facts at random to the Discord channel with id equal to
+ HACKTOBERFEST_CHANNEL_ID every INTERVAL seconds.
+ """
+ facts = list(enumerate(self.halloween_facts))
+ while True:
+ # Avoid choosing each fact at random to reduce chances of facts being reposted soon.
+ random.shuffle(facts)
+ for index, fact in facts:
+ embed = self._build_embed(index, fact)
+ await self.channel.send("Your regular serving of random Halloween facts", embed=embed)
+ self.last_fact = (index, fact)
+ await asyncio.sleep(INTERVAL)
+
+ @commands.command(name="hallofact", aliases=["hallofacts"], brief="Get the most recent Halloween fact")
+ async def get_last_fact(self, ctx):
+ """
+ Reply with the most recent Halloween fact.
+ """
+ if ctx.channel != self.channel:
+ return
+ index, fact = self.last_fact
+ embed = self._build_embed(index, fact)
+ await ctx.send("Halloween fact recap", embed=embed)
+
+ @staticmethod
+ def _build_embed(index, fact):
+ """
+ Builds a Discord embed from the given fact and its index.
+ """
+ emoji = random.choice(SPOOKY_EMOJIS)
+ title = f"{emoji} Halloween Fact #{index + 1}"
+ return discord.Embed(title=title, description=fact, color=PUMPKIN_ORANGE)
+
+
+def setup(bot):
+ bot.add_cog(HalloweenFacts(bot))
diff --git a/bot/cogs/halloweenify.py b/bot/cogs/halloweenify.py
index 8a9db3df..a5fe45ef 100644
--- a/bot/cogs/halloweenify.py
+++ b/bot/cogs/halloweenify.py
@@ -1,15 +1,13 @@
-from pathlib import Path
from json import load
+from pathlib import Path
from random import choice
-
import discord
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
class Halloweenify:
-
"""
A cog to change a invokers nickname to a spooky one!
"""
@@ -20,7 +18,10 @@ class Halloweenify:
@commands.cooldown(1, 300, BucketType.user)
@commands.command()
async def halloweenify(self, ctx):
- with open(Path('../bot/resources', 'halloweenify.json'), 'r') as f:
+ """
+ Change your nickname into a much spookier one!
+ """
+ with open(Path('./bot/resources', 'halloweenify.json'), 'r') as f:
data = load(f)
# Choose a random character from our list we loaded above and set apart the nickname and image url.
diff --git a/bot/cogs/movie.py b/bot/cogs/movie.py
index bb6f8df8..925f813f 100644
--- a/bot/cogs/movie.py
+++ b/bot/cogs/movie.py
@@ -1,8 +1,10 @@
-import requests
import random
from os import environ
-from discord.ext import commands
+
+import aiohttp
from discord import Embed
+from discord.ext import commands
+
TMDB_API_KEY = environ.get('TMDB_API_KEY')
TMDB_TOKEN = environ.get('TMDB_TOKEN')
@@ -16,8 +18,11 @@ class Movie:
def __init__(self, bot):
self.bot = bot
- @commands.command(name='movie', alias=['tmdb'], brief='Pick a scary movie')
+ @commands.command(name='movie', alias=['tmdb'])
async def random_movie(self, ctx):
+ """
+ Randomly select a scary movie and display information about it.
+ """
selection = await self.select_movie()
movie_details = await self.format_metadata(selection)
@@ -40,19 +45,24 @@ class Movie:
}
# Get total page count of horror movies
- response = requests.get(url=url, params=params, headers=headers)
- total_pages = response.json().get('total_pages')
+ async with aiohttp.ClientSession() as session:
+ response = await session.get(url=url, params=params, headers=headers)
+ total_pages = await response.json()
+ total_pages = total_pages.get('total_pages')
- # Get movie details from one random result on a random page
- params['page'] = random.randint(1, total_pages)
- response = requests.get(url=url, params=params, headers=headers)
- selection_id = random.choice(response.json().get('results')).get('id')
+ # Get movie details from one random result on a random page
+ params['page'] = random.randint(1, total_pages)
+ response = await session.get(url=url, params=params, headers=headers)
+ response = await response.json()
+ selection_id = random.choice(response.get('results')).get('id')
- # Get full details and credits
- selection = requests.get(url='https://api.themoviedb.org/3/movie/' + str(selection_id),
- params={'api_key': TMDB_API_KEY, 'append_to_response': 'credits'})
+ # Get full details and credits
+ selection = await session.get(
+ url='https://api.themoviedb.org/3/movie/' + str(selection_id),
+ params={'api_key': TMDB_API_KEY, 'append_to_response': 'credits'}
+ )
- return selection.json()
+ return await selection.json()
@staticmethod
async def format_metadata(movie):
@@ -60,36 +70,63 @@ class Movie:
Formats raw TMDb data to be embedded in discord chat
"""
- tmdb_url = 'https://www.themoviedb.org/movie/' + str(movie.get('id'))
- poster = 'https://image.tmdb.org/t/p/original' + movie.get('poster_path')
+ # Build the relevant URLs.
+ movie_id = movie.get("id")
+ poster_path = movie.get("poster_path")
+ tmdb_url = f'https://www.themoviedb.org/movie/{movie_id}' if movie_id else None
+ poster = f'https://image.tmdb.org/t/p/original{poster_path}' if poster_path else None
+ # Get cast names
cast = []
- for actor in movie.get('credits').get('cast')[:3]:
+ for actor in movie.get('credits', {}).get('cast', [])[:3]:
cast.append(actor.get('name'))
- director = movie.get('credits').get('crew')[0].get('name')
+ # Get director name
+ director = movie.get('credits', {}).get('crew', [])
+ if director:
+ director = director[0].get('name')
- rating_count = movie.get('vote_average') / 2
+ # Determine the spookiness rating
rating = ''
+ rating_count = movie.get('vote_average', 0)
- for i in range(int(rating_count)):
- rating += ':skull:'
+ if rating_count:
+ rating_count /= 2
+ for _ in range(int(rating_count)):
+ rating += ':skull:'
if (rating_count % 1) >= .5:
rating += ':bat:'
+ # Try to get year of release and runtime
+ year = movie.get('release_date', [])[:4]
+ runtime = movie.get('runtime')
+ runtime = f"{runtime} minutes" if runtime else None
+
+ # Not all these attributes will always be present
+ movie_attributes = {
+ "Directed by": director,
+ "Starring": ', '.join(cast),
+ "Running time": runtime,
+ "Release year": year,
+ "Spookiness rating": rating,
+ }
+
embed = Embed(
colour=0x01d277,
title='**' + movie.get('title') + '**',
url=tmdb_url,
description=movie.get('overview')
)
- embed.set_image(url=poster)
- embed.add_field(name='Starring', value=', '.join(cast))
- embed.add_field(name='Directed by', value=director)
- embed.add_field(name='Year', value=movie.get('release_date')[:4])
- embed.add_field(name='Runtime', value=str(movie.get('runtime')) + ' min')
- embed.add_field(name='Spooky Rating', value=rating)
+
+ if poster:
+ embed.set_image(url=poster)
+
+ # Add the attributes that we actually have data for, but not the others.
+ for name, value in movie_attributes.items():
+ if value:
+ embed.add_field(name=name, value=value)
+
embed.set_footer(text='powered by themoviedb.org')
return embed
diff --git a/bot/cogs/spookyreact.py b/bot/cogs/spookyreact.py
new file mode 100644
index 00000000..2652a60e
--- /dev/null
+++ b/bot/cogs/spookyreact.py
@@ -0,0 +1,31 @@
+SPOOKY_TRIGGERS = {
+ 'spooky': "\U0001F47B",
+ 'skeleton': "\U0001F480",
+ 'doot': "\U0001F480",
+ 'pumpkin': "\U0001F383",
+ 'halloween': "\U0001F383",
+ 'jack-o-lantern': "\U0001F383",
+ 'danger': "\U00002620"
+}
+
+
+class SpookyReact:
+
+ """
+ A cog that makes the bot react to message triggers.
+ """
+
+ def __init__(self, bot):
+ self.bot = bot
+
+ async def on_message(self, ctx):
+ """
+ A command to send the hacktoberbot github project
+ """
+ for trigger in SPOOKY_TRIGGERS.keys():
+ if trigger in ctx.content.lower():
+ await ctx.add_reaction(SPOOKY_TRIGGERS[trigger])
+
+
+def setup(bot):
+ bot.add_cog(SpookyReact(bot))
diff --git a/bot/cogs/template.py b/bot/cogs/template.py
index b3f4da21..aa01432c 100644
--- a/bot/cogs/template.py
+++ b/bot/cogs/template.py
@@ -17,7 +17,7 @@ class Template:
"""
await ctx.send('https://github.com/discord-python/hacktoberbot')
- @commands.group(name='git', invoke_without_command=True)
+ @commands.group(name='git', invoke_without_command=True, brief="A link to resources for learning Git")
async def github(self, ctx):
"""
A command group with the name git. You can now create sub-commands such as git commit.