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 29 commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
eb1a327
Merge pull request #1 from discord-python/master
biskette Mar 23, 2018
6f85d43
Stone by stone we'll build our castle walls...
biskette Mar 23, 2018
895fefa
We'll build them on common ground, and how!
biskette Mar 23, 2018
f56b6c8
Merge pull request #2 from discord-python/master
biskette Mar 23, 2018
8716582
We all live in the space age, coming down with road rage...
biskette Mar 23, 2018
e4c4190
Merge remote-tracking branch 'origin/master'
biskette Mar 23, 2018
aa0aca1
Travis is a bellend.
biskette Mar 23, 2018
2694897
Square peg, round hole.
biskette Mar 23, 2018
640e889
Used wikipedia library to get initial data for testing
runew0lf Mar 23, 2018
dc6aff5
Now uses our own code for getting wikipedia api data
runew0lf Mar 23, 2018
d838411
Created function to grab json instead of repeating code
runew0lf Mar 23, 2018
b8d7356
Wtf am i doing
biskette Mar 23, 2018
996570d
Merge remote-tracking branch 'origin/master'
biskette Mar 23, 2018
c66cdd8
Created function to grab json instead of repeating code
runew0lf Mar 23, 2018
98e4d6e
Merge remote-tracking branch 'origin/master'
runew0lf Mar 23, 2018
751603b
writing bollocks
biskette Mar 23, 2018
012aff8
Merge remote-tracking branch 'origin/master'
biskette Mar 23, 2018
c640b7a
fucking git eh?
biskette Mar 23, 2018
f31430a
Split out everything, fixed things, added things!
runew0lf Mar 23, 2018
d900240
Merge remote-tracking branch 'origin/master'
runew0lf Mar 23, 2018
642762a
linted code and added comments
runew0lf Mar 23, 2018
84a773a
Mostly finished snake list
biskette Mar 23, 2018
4081ecf
Merge remote-tracking branch 'origin/master'
biskette Mar 23, 2018
da1c851
Mostly finished snake list
biskette Mar 23, 2018
f7da5b8
Trimmed to necessary for integration
biskette Mar 23, 2018
d9095e7
Added bisks snake lookup
runew0lf Mar 23, 2018
fb0423f
Caches snakelist on startup
runew0lf Mar 23, 2018
b33bf1f
Added check to make sure we're selecting a snake
runew0lf Mar 23, 2018
7015863
Removed wtfisthis
runew0lf Mar 23, 2018
c546445
Linted code
runew0lf Mar 24, 2018
b93ae6a
Linted code and started on antidote game
runew0lf Mar 24, 2018
3994f68
Trimmed to necessary for integration
biskette Mar 24, 2018
95cf6f3
Merge branches 'bisk' and 'master' of https://github.com/biskette/cod…
biskette Mar 24, 2018
0f3acb4
Linted code and started on antidote game
runew0lf Mar 24, 2018
684e921
Linted code and started on antidote game
runew0lf Mar 24, 2018
3c7e1cd
Merge pull request #3 from discord-python/master
biskette Mar 24, 2018
75fb50c
Linted code and finished basic game
runew0lf Mar 24, 2018
bd44a3f
Linted code and finished basic game
runew0lf Mar 24, 2018
96551b3
Working on nicer return for ambiguous searches
biskette Mar 24, 2018
631d2ce
Making some checks for in snake_cache but -1 pageid
biskette Mar 24, 2018
a402c17
Stuff about a snake being in list but no page
biskette Mar 24, 2018
dac90dd
Cleaned up and tested get_snek function
biskette Mar 24, 2018
34ec1f8
Merge branches 'bisk' and 'master' of https://github.com/biskette/cod…
biskette Mar 24, 2018
d307309
Fixed the flakey flake8.
biskette Mar 24, 2018
c7912d0
Wrote a doc string for get_snek
biskette Mar 24, 2018
2b9752a
Wrote a bunch of comments explaining the Snake Finder General
biskette Mar 24, 2018
9f8b102
Commented code to make it more legible to bisk
runew0lf Mar 24, 2018
44e0f30
Merge remote-tracking branch 'origin/master'
runew0lf Mar 24, 2018
9b770ea
Finished Game and added Win / Lose Messages
runew0lf Mar 25, 2018
d3300d1
Fixed some issues that lemon highlighted
runew0lf Mar 25, 2018
644f51f
Linted code
runew0lf Mar 25, 2018
285ec33
Linted code and finished basic game
runew0lf Mar 25, 2018
1744c07
Fixed while loop to include win / tries
runew0lf Mar 25, 2018
128234c
Wrote a bunch of comments explaining the Snake Finder General
biskette Mar 25, 2018
af7b064
Remove cache
runew0lf Mar 25, 2018
4b53d9b
Re-added cache because i broke something
runew0lf Mar 25, 2018
29ad19d
Wrote a bunch of comments explaining the Snake Finder General
biskette Mar 25, 2018
e1c5b03
Tidying up doc strings and comments
biskette Mar 25, 2018
cb26052
Changed win screen to look tidy + include solution
biskette 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
20 changes: 20 additions & 0 deletions bot/cogs/data/quote.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
I like penis.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Any context behind this line?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I noticed Runew0lf added some weird quote thing and appended something important.

Copy link
Copy Markdown

@lemonsaurus lemonsaurus Mar 24, 2018

Choose a reason for hiding this comment

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

can you unappend something important? also you should really know what that weird quote thing is. open your python interpreter and type import this

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

God damnit bisk!
FIXED!

131 changes: 131 additions & 0 deletions bot/cogs/snakes.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
# coding=utf-8
import logging
from typing import Any, Dict
import aiohttp
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.

You could just use aiohttp.Timeout

import random
import asyncio
import pprint

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

log = logging.getLogger(__name__)

SNEKFILE = 'bot/cogs/data/quote.txt'

FIRST_EMOJI = "💉"
SECOND_EMOJI = "💊"
THIRD_EMOJI = "🌡️"
FOURTH_EMOJI = "☠️"
FIFTH_EMOJI = "⚗️"

snakelist = []


class Snakes:
"""
Expand All @@ -15,6 +31,52 @@ class Snakes:
def __init__(self, bot: AutoShardedBot):
self.bot = bot

async def cache_snakelist(self):
global snakelist
snakelist = await self.get_snake_list()

async def get_wiki_json(self, params):
async with aiohttp.ClientSession(headers={'User-Agent': 'DevBot v.10'}) as cs:
async with async_timeout.timeout(20):
async with cs.get("https://en.wikipedia.org/w/api.php", params=params) as r:
log.info(f"{r.url}: {r.status}: {r.reason}")
return await r.json()

async def cont_query(self, params):
last_continue = {}

while True:
req = params.copy()
req.update(last_continue)

request = await self.get_wiki_json(req)

if 'query' not in request:
break

pages = request['query']['pages']['13205433']['links']
yield pages

if 'continue' not in request:
break

last_continue = request['continue']

async def get_snake_list(self):
ambiguous = ["(disambiguation)", "Wikipedia:", "Help:", "Category:"]

snake_list = []
result = self.cont_query(
{'action': 'query', 'titles': 'list_of_snakes_by_common_name', 'prop': 'links', 'format': 'json'})
async for dicks in result:
listed = dicks
for item in listed:
if not any(s in item['title'] for s in ambiguous):
snake_list.append(item['title'])

snake_list.append("trouser snake")
return snake_list

async def get_snek(self, name: str = None) -> Dict[str, Any]:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

the docstring for this method is bad.

"""
Go online and fetch information about a snake
Expand All @@ -28,9 +90,60 @@ async def get_snek(self, name: str = None) -> Dict[str, Any]:
: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
"""
global snakelist
snake_name = name
name = name.replace(" ", "_") # sanitize name

text_params = {'action': 'query',
'titles': name,
'prop': 'extracts',
'exsentences': '2',
'explaintext': '1',
'autosuggest': '1',
'redirects': '1',
'format': 'json'}

image_name_params = {'action': 'query',
'titles': name,
'prop': 'images',
'redirects': '1',
'autosuggest': '1',
'imlimit': '1',
'format': 'json'}

text_json = await self.get_wiki_json(text_params)
image_name_json = await self.get_wiki_json(image_name_params)
snake_image = "https://pbs.twimg.com/profile_images/662615956670144512/dqsVK6Nw_400x400.jpg"

page_id = list(text_json['query']['pages'].keys())[0]
if page_id == "-1" or snake_name not in snakelist: # No entry on the wiki
snake_dict = {"name": snake_name,
"snake_text": "You call that a snake?\nTHIS is a snake!",
"snake_image": snake_image}
return snake_dict

image_id = image_name_json['query']['pages'][page_id]['images'][0]['title']

image_url_params = {'action': 'query',
'titles': image_id,
'prop': 'imageinfo',
'redirects': '1',
'autosuggest': '1',
'iiprop': 'url',
'format': 'json'}

image_url_json = await self.get_wiki_json(image_url_params)

snake_image_id = list(image_url_json['query']['pages'].keys())[0]
snake_image = image_url_json['query']['pages'][snake_image_id]['imageinfo'][0]['url']
snake_text = text_json['query']['pages'][page_id]['extract']

snake_dict = {"name": snake_name, "snake_text": snake_text, "snake_image": snake_image}
return snake_dict

@command()
async def get(self, ctx: Context, name: str = None):
global snakelist
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This code is invalid as Python docstrings will only work when on the first line of a function, take a look at this example:

>>> def func():
...     """Hello this is my docstring"""
...     print("Hello")
... 
>>> func.__doc__
'Hello this is my docstring'
>>> def func():
...     print("Hello")
...     """Hello this is my docstring"""
... 
>>> func.__doc__
None
>>> 

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Runew0lf wrote it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Runew0lf fixed it

"""
Go online and fetch information about a snake

Expand All @@ -40,10 +153,28 @@ async def get(self, ctx: Context, name: str = None):
: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
"""
if name is None:
name = random.choice(snakelist)
elif name == "snakes on a plane":
await ctx.send("https://media.giphy.com/media/5xtDartXnQbcW5CfM64/giphy.gif")
elif name == "python":
with open(SNEKFILE, 'r') as file:
text = file.read()
snake_embed = Embed(color=ctx.me.color, title="SNEK")
snake_embed.add_field(name="Python", value=f"*{text}*")
snake_embed.set_thumbnail(url="http://www.pngall.com/wp-content/uploads/2016/05/Python-Logo-Free-PNG-Image.png")
await ctx.send(embed=snake_embed)

snake = await self.get_snek(name)
snake_embed = Embed(color=ctx.me.color, title="SNEK")
snake_embed.add_field(name=snake['name'], value=snake['snake_text'])
snake_embed.set_thumbnail(url=snake['snake_image'])
await ctx.send(embed=snake_embed)

# 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")
bot.loop.create_task(Snakes(bot).cache_snakelist())
Copy link
Copy Markdown
Member

@jb3 jb3 Mar 24, 2018

Choose a reason for hiding this comment

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

Instead of creating two instances of the same class, the __init__ method of the class should create the task to cache the data.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Runew0lf wrote it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ruinew0lf fixed it.

1 change: 1 addition & 0 deletions bot/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import logging
from typing import Iterable, Optional


from discord import Embed, Member, Reaction
from discord.abc import User
from discord.ext.commands import Context, Paginator
Expand Down