Skip to content
This repository was archived by the owner on Mar 14, 2021. It is now read-only.
Open
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
ece1140
Merge pull request #1 from discord-python/master
skrungly Mar 23, 2018
54fbeb0
First draft
isik-kaplan Mar 23, 2018
105b415
Adding snakes.txt
isik-kaplan Mar 23, 2018
fd9db0d
Cleaned up a bit, added bot test
invalid-email-address Mar 23, 2018
63ccb69
Added pictures
isik-kaplan Mar 23, 2018
3763038
Embeds and redirects :D
invalid-email-address Mar 23, 2018
47e03d6
Fixed url encoder
isik-kaplan Mar 23, 2018
9b4a683
I don't fucking know
invalid-email-address Mar 23, 2018
73ab47b
I don't fucking know
invalid-email-address Mar 23, 2018
2cbbf34
Fixed up wikipedia's bullshit
invalid-email-address Mar 23, 2018
0ddc2a4
fixed little stuff
isik-kaplan Mar 24, 2018
e766154
Various small edits
Mar 24, 2018
8d89ccf
Various small edits
Mar 24, 2018
002dcfa
fixed more little stuff
Mar 24, 2018
163d4d7
Merge pull request #2 from discord-python/master
skrungly Mar 24, 2018
916a7ac
Added autocomplete kwarg(ish)
Mar 24, 2018
9338eeb
Merge branch 'master' of https://github.com/kingdom5500/code-jam-1
Mar 24, 2018
a626e56
kwarg parsing ^^
Mar 25, 2018
aa43444
fucking hell, had accidentally pushed bot token :I
Mar 25, 2018
532995e
Revert "kwarg parsing ^^"
Mar 25, 2018
992de22
Revert "fucking hell, had accidentally pushed bot token :I"
Mar 25, 2018
305c3fe
Revert "kwarg parsing ^^"
Mar 25, 2018
d419d1c
Well I'm stupid :D
Mar 25, 2018
108e84d
snakes.txt + snakes2.py
isik-kaplan Mar 25, 2018
971d098
Merge branch 'master' of https://github.com/kingdom5500/code-jam-1
isik-kaplan Mar 25, 2018
2c6af66
Added snake_card command (kinda)
Mar 25, 2018
80e01f6
These files are useful
Mar 25, 2018
8bb749d
Finally used .env
Mar 25, 2018
fc5dddb
Arg edits, made by someone
Mar 25, 2018
3330e52
added snkaes.py *duuh*
isik-kaplan Mar 25, 2018
1b5e682
Oops.
Mar 25, 2018
2344edc
Oops.
Mar 25, 2018
94bfad1
Revert "Finally used .env"
Mar 25, 2018
a93cc3b
Revert "These files are useful"
Mar 25, 2018
9f77c25
Touched up some stuff
Mar 25, 2018
626b8b6
Accidentally pushed old token fucking hell
Mar 25, 2018
d31e269
Finishing touches for now. Will still need fine-tuning though
Mar 25, 2018
78ad193
Added my own version. Someone, don't hurt me :(
Mar 25, 2018
e395e6b
Added a comment for clarification :D
Mar 25, 2018
93d1d8e
Improved special cases
Mar 25, 2018
b9ee9c0
Improved special cases
Mar 25, 2018
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: 2 additions & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ name = "pypi"
[packages]
"72eb2aa" = {file = "https://github.com/Rapptz/discord.py/archive/rewrite.zip"}
aiodns = "*"
aiohttp = "<2.3.0,>=2.0.0"
aiohttp = "==2.0.0"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why?

websockets = ">=4.0,<5.0"
google-api-python-client = "*"

[dev-packages]
"flake8" = "*"
Expand Down
144 changes: 107 additions & 37 deletions Pipfile.lock

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

134 changes: 115 additions & 19 deletions bot/cogs/snakes.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,39 @@
# coding=utf-8
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ya want to explain this? Why delete that file?


import async_timeout
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This isn't declared in your Pipfile.

import random
import difflib
import logging
from typing import Any, Dict
import urllib.parse
import ast

import aiohttp

from typing import Dict, List
from discord import Embed
from discord.ext.commands import AutoShardedBot, Context, command


log = logging.getLogger(__name__)

# Probably should move these somewhere

WIKI = "https://en.wikipedia.org/w/api.php?"
BASEURL = WIKI + "format=json&action=query&prop=extracts|pageimages&exintro=&explaintext=&titles={}&redirects=1"
FAILIMAGE = "http://i.imgur.com/HtIPyLy.png/beep"
PYTHON = {
"name": "Python",
"info": """Python is a species of programming language, \
commonly used by coding beginners and experts alike. It was first discovered \
in 1989 by Guido van Rossum in the Netherlands, and was released to the wild \
two years later. Its use of dynamic typing is one of many distinct features, \
alongside significant whitespace, heavy emphasis on readability, and, above all, \
absolutely pain-free software distribution... *sigh*""",
"image": "https://www.python.org/static/community_logos/python-logo-master-v3-TM-flattened.png"
}
with open("bot/snakes.txt") as f:
SNAKES = [line.strip() for line in f.readlines()]


class Snakes:
"""
Expand All @@ -15,31 +43,99 @@ 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
@staticmethod
def parse_kwarg(kwarg: str):
"""Return the value of a kwarg (needs manual assignment)"""
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I don't understand - what is this supposed to be doing, and why?

try:
items = kwarg.split("=")
value = items[1]
except (IndexError, AttributeError):
value = kwarg

try:
parsed = ast.literal_eval(value)
except (NameError, ValueError):
parsed = value

return parsed

@staticmethod
def snake_url(name: str):
"""Get the URL of a snake"""

def format_url(text: str):
"""Get the full URL with that snake :D"""
return BASEURL.format(urllib.parse.quote_plus(text))

# Check if the snake name is valid
if name.upper() in [name.upper() for name in SNAKES]:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Instead of upper()ing all the names every time you do this, maybe they could be stored that way?

return format_url(name)

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!
# Get the most similar name if a match wasn't found
return difflib.get_close_matches(name, SNAKES, n=5, cutoff=0)

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!
@staticmethod
async def fetch(session, url: str):
"""Fetch the contents of a URL as a json"""
async with async_timeout.timeout(10):
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why not just with aiohttp.Timeout(10):?

async with session.get(url) as response:
return await response.json()

: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
"""
async def get_snek(self, name: str = None, autocorrect: str = None, details: List[str] = None) -> Dict[str, str]:
"""If a name is provided, this gets a specific snake. Otherwise, it gets a random snake."""

autocorrect = self.parse_kwarg(autocorrect) or False
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

?????????

details = self.parse_kwarg(details) or []

if name is None:
name = random.choice(SNAKES)

if name.upper() == "PYTHON":
return PYTHON

# Get snake information
async with aiohttp.ClientSession() as session:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You used a timeout above, but not here. Maybe you meant to have one here?

url = self.snake_url(name)

if isinstance(url, list):
if autocorrect:
return await self.get_snek(url[0])

return {
"name": "Oops!",
"info": "We couldn't find that snake, but here are some with similar names:\n\n" + "\n".join(url),
}

# Get the content
response = await self.fetch(session, url)
page = response["query"]["pages"]
content = next(iter(page.values()))
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Surely there's a simpler way to do that.


# Parse the full-res image from the thumbnail
thumb = content.get("thumbnail", {}).get("source", FAILIMAGE)
image = "/".join(thumb.replace("thumb/", "").split("/")[:-1])
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

split() takes another parameter for the number of times the string should be split. Take a look at that, maybe?


return {
"name": content["title"],
"info": content.get("extract", "I don't know about that snake!"),
"image": image
}

@command()
async def get(self, ctx: Context, name: str = None):
"""
Go online and fetch information about a snake
async def get(self, ctx: Context, name: str = None, autocorrect: str = None, details: str = None):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You're missing a docstring here.

content = await self.get_snek(name, autocorrect, details)
# Just a temporary thing to make sure it's working
embed = Embed(
title=content["name"],
description=content["info"][:1970],
color=0x7289da
)

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.
if "image" in content:
embed.set_image(url=content.get("image"))

: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
"""
await ctx.send(embed=embed)

# Any additional commands can be placed here. Be creative, but keep it to a reasonable amount!

Expand Down
1 change: 1 addition & 0 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,6 @@
bot.load_extension("bot.cogs.snakes")

bot.run(os.environ.get("BOT_TOKEN"))
#bot.run('bot token goes here for testing')
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You should remove this line.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

We explained exactly how this works in the docs.


bot.http_session.close() # Close the aiohttp session when the bot finishes running
Loading