Skip to content
This repository was archived by the owner on Mar 14, 2021. It is now read-only.

Team 7 #2

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ coverage.xml
*.cover
.hypothesis/

# VSCode
.vscode/

# Translations
*.mo
*.pot
Expand Down
3 changes: 3 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ name = "pypi"
aiodns = "*"
aiohttp = "<2.3.0,>=2.0.0"
websockets = ">=4.0,<5.0"
"beautifulsoup4" = "*"
lxml = "*"
pickledb = "*"

[dev-packages]
"flake8" = "*"
Expand Down
84 changes: 80 additions & 4 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

63 changes: 63 additions & 0 deletions bot/cogs/WikiListener.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import json

import aiohttp

"""

Handle requests and grab and returns detail from wikipedia using MediaWiki.

"""


async def get_json(url):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not json.loads inside this function so that you don't have to repeat code in future usages of this function?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

""" Returns the text from request to url """
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()


def get_all_snek():
"""" Gets all valid snake from a text file """
file_save = open("bot/snakedata/common-snake-names.txt", "r")
snake_text = file_save.read()
snake_names = snake_text.split("\n")
print("Returned all snake names")
return snake_names


async def get_raw_json(name):
""" Returns a dictionary from the JSON grabbed from MediaWiki API. """
api_url = f'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts|pageimages&exintro=&explaintext=&titles={name}&redirects=1'
raw_json = await get_json(api_url)
clean_json = json.loads(raw_json)
return clean_json


async def get_snek_description(name: str = None):
""" Returns 'extract' text from JSON, using a dictionary """
json_dict = await get_raw_json(name)
return list(json_dict['query']['pages'].values())[0]['extract']


async def get_snek_scientific(name: str = None):
""" Returns 'title' text from JSON, using a dictionary """
json_dict = await get_raw_json(name)
scientific = list(json_dict['query']['pages'].values())[0]['title']
if scientific == name:
return None
else:
return scientific


async def get_snek_thumbnail(name: str = None):
""" Returns 'thumbnail' source from JSON, using a dictionary """
json_dict = await get_raw_json(name)
return list(json_dict['query']['pages'].values())[0]['thumbnail']['source']


async def get_snek_url(name: str = None):
""" Returns the url of the snake searched """
json_dict = await get_raw_json(name)
title = list(json_dict['query']['pages'].values())[0]['title']
url = f'https://en.wikipedia.org/wiki/{title}'
return url
84 changes: 63 additions & 21 deletions bot/cogs/snakes.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
# coding=utf-8
import logging
from typing import Any, Dict

from bot.cogs import WikiListener
from discord.ext.commands import AutoShardedBot, Context, command
import discord
import aiohttp
import random
import json

log = logging.getLogger(__name__)

Expand All @@ -15,35 +19,73 @@ class Snakes:
def __init__(self, bot: AutoShardedBot):
self.bot = bot

async def get_snek(self, name: str = None) -> Dict[str, Any]:
"""
Go online and fetch information about a snake

The information includes the name of the snake, a picture of the snake, and various other pieces of info.
What information you get for the snake is up to you. Be creative!
async def is_snek(self, name: str = None) -> Dict[str, Any]:
if name in WikiListener.get_all_snek():
return True
else:
return False

If "python" is given as the snake name, you should return information about the programming language, but with
all the information you'd provide for a real snake. Try to have some fun with this!
@command()
async def get(self, ctx: Context, name: str = None):

:param name: Optional, the name of the snake to get information for - omit for a random snake
:return: A dict containing information on a snake
"""
if name is None:
ctx.send("Ensure your command specifies the correct arguments.")
state = await self.is_snek(name)
if state:
if WikiListener.get_snek_scientific(name) is None:
title = await WikiListener.get_snek_scientific(name)
description = await WikiListener.get_snek_description(name)
embed = discord.Embed(title=f"{name}", description=f"{description}", color=0x00ff80)
try:
thumbnail = await WikiListener.get_snek_thumbnail(name)
embed.set_thumbnail(url=f'{thumbnail}')
except aiohttp.web.HTTPExceptionError:
pass
await ctx.send(embed=embed)
else:
title = await WikiListener.get_snek_scientific(name)
description = await WikiListener.get_snek_description(name)
embed = discord.Embed(title=f"{name}", description=f"{description}", color=0x00ff80)
embed.set_author(name=f"{title}")
try:
thumbnail = await WikiListener.get_snek_thumbnail(name)
embed.set_thumbnail(url=f'{thumbnail}')
except aiohttp.web.HTTPClientError:
pass
await ctx.send(embed=embed)
else:
await ctx.channel.send(f"Did not find {name} in the database.")

@command()
async def get(self, ctx: Context, name: str = None):
"""
Go online and fetch information about a snake
async def quiz(self, ctx: Context, name: str = None):
async def addmoji(msg, emojilist):
for emoji in emojilist:
await msg.add_reaction(emoji)
with open("bot/snakedata/questions.json") as quizson:
questions = json.load(quizson)

This should make use of your `get_snek` method, using it to get information about a snake. This information
should be sent back to Discord in an embed.
quemoji = ['🇦', '🇧', '🇨', '🇩']
random_quiz = questions["questions"][random.randint(0,10)]
em = discord.Embed(title=random_quiz['question'], description='🇦 {0}\n\n🇧 {1}\n\n🇨 {2}\n\n🇩 {3}'.format(random_quiz['a'],random_quiz['b'],random_quiz['c'],random_quiz['d']))
channel = ctx.channel
quiz = await channel.send('', embed=em)
await addmoji(quiz, quemoji)

:param ctx: Context object passed from discord.py
:param name: Optional, the name of the snake to get information for - omit for a random snake
"""
def check(reaction, user):
return user == ctx.author and str(reaction.emoji)

# Any additional commands can be placed here. Be creative, but keep it to a reasonable amount!
try:
reaction, user = await ctx.bot.wait_for('reaction_add', timeout=20.0, check=check)
except asyncio.TimeoutError as err:
await channel.send('Bah! You took too long.')
else:
if str(reaction.emoji) == random_quiz["answerkey"]:
await channel.send('That was correct! Well done!')
else:
await channel.send('That was incorrect! The correct answer was {0}, unfortunately.'.format(random_quiz["answerkey"]))


# Any additional commands can be placed here. Be creative, but keep it to a reasonable amount!
def setup(bot):
bot.add_cog(Snakes(bot))
log.info("Cog loaded: Snakes")
Loading