From dcaebf45a742fe0e5c554daeeab6941be4f51337 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20D=C3=ADaz=20P=C3=A9rez?= Date: Fri, 23 Mar 2018 08:38:46 +0100 Subject: [PATCH 1/7] Add .vscode to .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 2895fff3..afb0533d 100644 --- a/.gitignore +++ b/.gitignore @@ -102,3 +102,4 @@ ENV/ # PyCharm .idea/ +.vscode/settings.json From eb4e4860015a6bf231f62712b376c174b930d8d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20D=C3=ADaz=20P=C3=A9rez?= Date: Fri, 23 Mar 2018 08:39:03 +0100 Subject: [PATCH 2/7] Add wikipedia to modules --- Pipfile | 1 + Pipfile.lock | 38 +++++++++++++++++++++++++++++++++++++- bot/cogs/snakes.py | 11 +++++++++-- 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/Pipfile b/Pipfile index 096fb9b3..3feb1dec 100644 --- a/Pipfile +++ b/Pipfile @@ -8,6 +8,7 @@ name = "pypi" aiodns = "*" aiohttp = "<2.3.0,>=2.0.0" websockets = ">=4.0,<5.0" +wikipedia = "*" [dev-packages] "flake8" = "*" diff --git a/Pipfile.lock b/Pipfile.lock index 4e5214bb..0399cdb0 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -1,7 +1,7 @@ { "_meta": { "hash": { - "sha256": "d797e580ddcddc99bf058109ab0306ad584c2902752a3d4076ba713fdc580fb7" + "sha256": "738768c7b3fa9b26b2b995f90b9324d0d058394442c75e2407bc3b010d290de3" }, "pipfile-spec": 6, "requires": { @@ -53,6 +53,21 @@ ], "version": "==2.0.1" }, + "beautifulsoup4": { + "hashes": [ + "sha256:11a9a27b7d3bddc6d86f59fb76afb70e921a25ac2d6cc55b40d072bd68435a76", + "sha256:7015e76bf32f1f574636c4288399a6de66ce08fb7b2457f628a8d70c0fbabb11", + "sha256:808b6ac932dccb0a4126558f7dfdcf41710dd44a4ef497a0bb59a77f9f078e89" + ], + "version": "==4.6.0" + }, + "certifi": { + "hashes": [ + "sha256:14131608ad2fd56836d33a71ee60fa1c82bc9d2c8d98b7bdbc631fe1b3cd1296", + "sha256:edbc3f203427eef571f79a7692bb160a2b0f7ccaa31953e99bd17e307cf63f7d" + ], + "version": "==2018.1.18" + }, "chardet": { "hashes": [ "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", @@ -120,6 +135,20 @@ ], "version": "==2.3.0" }, + "requests": { + "hashes": [ + "sha256:6a1b267aa90cac58ac3a765d067950e7dbbf75b1da07e895d1f594193a40a38b", + "sha256:9c443e7324ba5b85070c4a818ade28bfabedf16ea10206da1132edaa6dda237e" + ], + "version": "==2.18.4" + }, + "urllib3": { + "hashes": [ + "sha256:06330f386d6e4b195fbfc736b297f58c5a892e4440e54d294d7004e3a9bbea1b", + "sha256:cc44da8e1145637334317feebd728bd869a35285b93cbb4cca2577da7e62db4f" + ], + "version": "==1.22" + }, "websockets": { "hashes": [ "sha256:0c31bc832d529dc7583d324eb6c836a4f362032a1902723c112cf57883488d8c", @@ -142,6 +171,13 @@ "index": "pypi", "version": "==4.0.1" }, + "wikipedia": { + "hashes": [ + "sha256:db0fad1829fdd441b1852306e9856398204dc0786d2996dd2e0c8bb8e26133b2" + ], + "index": "pypi", + "version": "==1.4.0" + }, "yarl": { "hashes": [ "sha256:045dbba18c9142278113d5dc62622978a6f718ba662392d406141c59b540c514", diff --git a/bot/cogs/snakes.py b/bot/cogs/snakes.py index c9ed8042..85f3ef92 100644 --- a/bot/cogs/snakes.py +++ b/bot/cogs/snakes.py @@ -4,6 +4,8 @@ from discord.ext.commands import AutoShardedBot, Context, command +from .snakegame import SnakeGame + log = logging.getLogger(__name__) @@ -12,8 +14,9 @@ class Snakes: Snake-related commands """ - def __init__(self, bot: AutoShardedBot): + def __init__(self, bot: AutoShardedBot, game: SnakeGame): self.bot = bot + self.game = game async def get_snek(self, name: str = None) -> Dict[str, Any]: """ @@ -42,8 +45,12 @@ async def get(self, ctx: Context, name: str = None): """ # Any additional commands can be placed here. Be creative, but keep it to a reasonable amount! + @command() + async def play(self, ctx: Context, order): + if order == "left": + await ctx.send(self.game) def setup(bot): - bot.add_cog(Snakes(bot)) + bot.add_cog(Snakes(bot, SnakeGame((5, 5)))) log.info("Cog loaded: Snakes") From aa40d32470623bfebbf91b9814c9f47fc3b3da56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20D=C3=ADaz=20P=C3=A9rez?= Date: Fri, 23 Mar 2018 10:52:08 +0100 Subject: [PATCH 3/7] Snake game created --- bot/cogs/snakegame.py | 162 ++++++++++++++++++++++++++++++++++++++++++ bot/cogs/snakes.py | 38 ++++++++-- 2 files changed, 196 insertions(+), 4 deletions(-) create mode 100644 bot/cogs/snakegame.py diff --git a/bot/cogs/snakegame.py b/bot/cogs/snakegame.py new file mode 100644 index 00000000..81f0b8e5 --- /dev/null +++ b/bot/cogs/snakegame.py @@ -0,0 +1,162 @@ +from random import randint + + +class SnakeGame: + """ + Simple Snake game + """ + + def __init__(self, board_dimensions): + self.board_dimensions = board_dimensions + self.restart() + + def restart(self): + """ + Restores game to default state + """ + + self.snake = Snake(positions=[[2, 2], [2, 1]]) + self.putFood() + self.score = 0 + + def __str__(self): + """ + Draw the board + """ + # create empty board + board_string = "+" + "-" * (self.board_dimensions[1]) + "+" + "\n" + for i in range(self.board_dimensions[0]): + row_string = "|" + # draw snake + for j in range(self.board_dimensions[1]): + if [i, j] == self.snake.positions[0]: + row_string += "□" # head + elif [i, j] in self.snake.positions: + row_string += "■" + elif [i, j] == self.food: + row_string += "." + else: + row_string += " " + row_string += "|\n" + board_string += row_string + board_string += "+" + "-" * (self.board_dimensions[1]) + "+\n" + + return board_string + + def move(self, direction): + """ + Executes one movement. + Returns information about the movement: + "ok", "forbidden", "lost", "food". + """ + + direction_dict = { + "right": (0, 1), + "left": (0, -1), + "up": (-1, 0), + "down": (1, 0) + } + move_status = self.snake.move(direction_dict[direction]) + + if self.isLost(): + move_status = "lost" + self.restart() + + if self.isEating(): + self.snake.grow() + move_status = "grow" + self.putFood() + self.score += 1 + + return move_status + + def isLost(self): + head = self.snake.head + + if (head[0] == -1 or + head[1] == -1 or + head[0] == self.board_dimensions[0] or + head[1] == self.board_dimensions[1]): + + return True + return False + + def putFood(self): + valid = False + while not valid: + i = randint(0, self.board_dimensions[0] - 1) + j = randint(0, self.board_dimensions[1] - 1) + + if [i, j] not in self.snake.positions: + valid = True + + self.food = [i, j] + + def isEating(self): + if self.snake.head == self.food: + return True + return False + + +class Snake: + """ + Actual snake in the game. + """ + + def __init__(self, positions): + self.positions = positions + self.head = positions[0] + + def move(self, velocity): + """ + Executes one movement. + + Returns information about the movement: + "ok", "forbidden" + """ + if not self.isPossible(velocity): + print("Movement not allowed") + return "forbidden" + + # delete tail but store it, as we might want the snake to grow + self.deletedTail = self.positions[-1] + self.positions = self.positions[:-1] + + # move head + self.head = [self.head[0] + velocity[0], + self.head[1] + velocity[1]] + self.positions.insert(0, self.head) + + return "ok" + + def isPossible(self, velocity): + """ + Check Snake is trying to do an 180º turn. + """ + newHead = [self.head[0] + velocity[0], + self.head[1] + velocity[1]] + if newHead == self.positions[1]: + return False + return True + + def grow(self): + """ + Makes the snake grow one square. + """ + self.positions.append(self.deletedTail) + + +if __name__ == "__main__": + game = SnakeGame((5, 5)) + print(game) + game.move("right") + print(game) + game.move("right") + print(game) + game.move("right") + print(game) + game.move("right") + print(game) + game.move("right") + print(game) + game.move("right") diff --git a/bot/cogs/snakes.py b/bot/cogs/snakes.py index 85f3ef92..f30709a3 100644 --- a/bot/cogs/snakes.py +++ b/bot/cogs/snakes.py @@ -1,7 +1,9 @@ # coding=utf-8 import logging +from time import time from typing import Any, Dict +from discord import Embed from discord.ext.commands import AutoShardedBot, Context, command from .snakegame import SnakeGame @@ -14,9 +16,14 @@ class Snakes: Snake-related commands """ - def __init__(self, bot: AutoShardedBot, game: SnakeGame): + def __init__(self, bot: AutoShardedBot, game: SnakeGame, wait_time: int): self.bot = bot self.game = game + self.debug = True + self.mods = ["kr4n3x#5014", "(PC) Refisio#9732"] + self.last_movement = time() + self.movement_command = {"left": 0, "right": 0, "up": 0, "down": 0} + self.wait_time = wait_time async def get_snek(self, name: str = None) -> Dict[str, Any]: """ @@ -47,10 +54,33 @@ async def get(self, ctx: Context, name: str = None): # Any additional commands can be placed here. Be creative, but keep it to a reasonable amount! @command() async def play(self, ctx: Context, order): - if order == "left": - await ctx.send(self.game) + if order in self.movement_command.keys(): + self.movement_command[order] += 1 + + if time() - self.last_movement > self.wait_time: + direction = max(self.movement_command, + key=self.movement_command.get) + move_status = self.game.move(direction) + + if move_status == "lost": + await ctx.send("We made the snake cry! :snake: :cry:") + + self.last_movement = time() + self.movement_command = {"left": 0, + "right": 0, "up": 0, "down": 0} + + embed = Embed() + embed.add_field(name="Score", value=self.game.score) + embed.add_field(name="Winner movement", value="We moved " + direction) + embed.add_field(name="Board", value="```" + + str(self.game) + "```", inline=False) + if self.debug: + embed.add_field( + name="Debug", value="Debug - move_status: " + move_status, inline=False) + + await ctx.send(embed=embed) def setup(bot): - bot.add_cog(Snakes(bot, SnakeGame((5, 5)))) + bot.add_cog(Snakes(bot, SnakeGame((5, 5)), 2)) log.info("Cog loaded: Snakes") From 1f221eaafdfb579ea49bbf361b34a0815a95ae51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20D=C3=ADaz=20P=C3=A9rez?= Date: Fri, 23 Mar 2018 11:34:06 +0100 Subject: [PATCH 4/7] move snakegame to the bot folder --- bot/{cogs => }/snakegame.py | 16 ---------------- 1 file changed, 16 deletions(-) rename bot/{cogs => }/snakegame.py (92%) diff --git a/bot/cogs/snakegame.py b/bot/snakegame.py similarity index 92% rename from bot/cogs/snakegame.py rename to bot/snakegame.py index 81f0b8e5..ab2763cc 100644 --- a/bot/cogs/snakegame.py +++ b/bot/snakegame.py @@ -144,19 +144,3 @@ def grow(self): Makes the snake grow one square. """ self.positions.append(self.deletedTail) - - -if __name__ == "__main__": - game = SnakeGame((5, 5)) - print(game) - game.move("right") - print(game) - game.move("right") - print(game) - game.move("right") - print(game) - game.move("right") - print(game) - game.move("right") - print(game) - game.move("right") From fd7a4689d574bfb9f7cdf9d4a3053f5a5c358bc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20D=C3=ADaz=20P=C3=A9rez?= Date: Fri, 23 Mar 2018 11:34:36 +0100 Subject: [PATCH 5/7] Add documentation and fix snake -> snek --- bot/cogs/snakes.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/bot/cogs/snakes.py b/bot/cogs/snakes.py index f30709a3..b58c05c4 100644 --- a/bot/cogs/snakes.py +++ b/bot/cogs/snakes.py @@ -6,7 +6,7 @@ from discord import Embed from discord.ext.commands import AutoShardedBot, Context, command -from .snakegame import SnakeGame +from bot.snakegame import SnakeGame log = logging.getLogger(__name__) @@ -16,14 +16,14 @@ class Snakes: Snake-related commands """ - def __init__(self, bot: AutoShardedBot, game: SnakeGame, wait_time: int): + def __init__(self, bot: AutoShardedBot): self.bot = bot - self.game = game + self.game = SnakeGame((5, 5)) self.debug = True self.mods = ["kr4n3x#5014", "(PC) Refisio#9732"] self.last_movement = time() self.movement_command = {"left": 0, "right": 0, "up": 0, "down": 0} - self.wait_time = wait_time + self.wait_time = 2 async def get_snek(self, name: str = None) -> Dict[str, Any]: """ @@ -54,6 +54,15 @@ async def get(self, ctx: Context, name: str = None): # Any additional commands can be placed here. Be creative, but keep it to a reasonable amount! @command() async def play(self, ctx: Context, order): + """ + DiscordPlaysSnek + + Move the snek around the field and collect food. + + Valid use: `bot.play {direction}` + + With 'left', 'right', 'up' and 'down' as valid directions. + """ if order in self.movement_command.keys(): self.movement_command[order] += 1 @@ -63,7 +72,7 @@ async def play(self, ctx: Context, order): move_status = self.game.move(direction) if move_status == "lost": - await ctx.send("We made the snake cry! :snake: :cry:") + await ctx.send("We made the snek cry! :snake: :cry:") self.last_movement = time() self.movement_command = {"left": 0, @@ -71,7 +80,8 @@ async def play(self, ctx: Context, order): embed = Embed() embed.add_field(name="Score", value=self.game.score) - embed.add_field(name="Winner movement", value="We moved " + direction) + embed.add_field(name="Winner movement", + value="We moved " + direction) embed.add_field(name="Board", value="```" + str(self.game) + "```", inline=False) if self.debug: @@ -82,5 +92,5 @@ async def play(self, ctx: Context, order): def setup(bot): - bot.add_cog(Snakes(bot, SnakeGame((5, 5)), 2)) + bot.add_cog(Snakes(bot)) log.info("Cog loaded: Snakes") From 6191f2f8704bc77c9724171deff416525a9bcae6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20D=C3=ADaz=20P=C3=A9rez?= Date: Fri, 23 Mar 2018 12:45:11 +0100 Subject: [PATCH 6/7] Move to using emojis --- bot/cogs/snakes.py | 32 ++++++++++++++++++++------------ bot/snakegame.py | 25 ++++++++++++++----------- 2 files changed, 34 insertions(+), 23 deletions(-) diff --git a/bot/cogs/snakes.py b/bot/cogs/snakes.py index b58c05c4..972f7b06 100644 --- a/bot/cogs/snakes.py +++ b/bot/cogs/snakes.py @@ -3,7 +3,7 @@ from time import time from typing import Any, Dict -from discord import Embed +from discord import Embed, Color from discord.ext.commands import AutoShardedBot, Context, command from bot.snakegame import SnakeGame @@ -63,32 +63,40 @@ async def play(self, ctx: Context, order): With 'left', 'right', 'up' and 'down' as valid directions. """ + if order in self.movement_command.keys(): self.movement_command[order] += 1 + # check if it's time to move the snek if time() - self.last_movement > self.wait_time: direction = max(self.movement_command, key=self.movement_command.get) + percentage = 100*self.movement_command[direction]/sum(self.movement_command.values()) move_status = self.game.move(direction) + # end game if move_status == "lost": await ctx.send("We made the snek cry! :snake: :cry:") - self.last_movement = time() - self.movement_command = {"left": 0, - "right": 0, "up": 0, "down": 0} + # prepare snek message + snekembed = Embed(color=Color.red()) + snekembed.add_field(name="Score", value=self.game.score) + snekembed.add_field(name="Winner movement", + value="{dir}: {per:.2f}%".format(dir=direction, per=percentage)) - embed = Embed() - embed.add_field(name="Score", value=self.game.score) - embed.add_field(name="Winner movement", - value="We moved " + direction) - embed.add_field(name="Board", value="```" + - str(self.game) + "```", inline=False) + snek_head = next(emoji for emoji in ctx.guild.emojis if emoji.name == 'python') + + game_string = str(self.game).replace(":python:", str(snek_head)) + snekembed.add_field(name="Board", value=game_string, inline=False) if self.debug: - embed.add_field( + snekembed.add_field( name="Debug", value="Debug - move_status: " + move_status, inline=False) - await ctx.send(embed=embed) + # prepare next movement + self.last_movement = time() + self.movement_command = {"left": 0, + "right": 0, "up": 0, "down": 0} + await ctx.send(embed=snekembed) def setup(bot): diff --git a/bot/snakegame.py b/bot/snakegame.py index ab2763cc..b3520a0b 100644 --- a/bot/snakegame.py +++ b/bot/snakegame.py @@ -24,22 +24,24 @@ def __str__(self): Draw the board """ # create empty board - board_string = "+" + "-" * (self.board_dimensions[1]) + "+" + "\n" + # board_string = "+" + "-" * (self.board_dimensions[1]) + "+" + "\n" + board_string = "" for i in range(self.board_dimensions[0]): - row_string = "|" + # row_string = "|" + row_string = "" # draw snake for j in range(self.board_dimensions[1]): if [i, j] == self.snake.positions[0]: - row_string += "□" # head + row_string += ":python:" # head elif [i, j] in self.snake.positions: - row_string += "■" + row_string += "🐍" elif [i, j] == self.food: - row_string += "." + row_string += "🍕" else: - row_string += " " - row_string += "|\n" - board_string += row_string - board_string += "+" + "-" * (self.board_dimensions[1]) + "+\n" + row_string += "◻️" + # row_string += "|\n" + board_string += row_string + "\n" + # board_string += "+" + "-" * (self.board_dimensions[1]) + "+\n" return board_string @@ -76,9 +78,10 @@ def isLost(self): if (head[0] == -1 or head[1] == -1 or head[0] == self.board_dimensions[0] or - head[1] == self.board_dimensions[1]): - + head[1] == self.board_dimensions[1] or + head in self.snake.positions[1:]): return True + return False def putFood(self): From 922e65a43cca4d3efa4239eb0c7898522762aa9e Mon Sep 17 00:00:00 2001 From: refisio Date: Sat, 24 Mar 2018 00:22:45 -0400 Subject: [PATCH 7/7] Created 'get_snek' function and 'get' command. First commit by Refisio to the PR. Wew lad. Alright. Let's go. - Set up the basis for pulling information from the MediaWiki API - Set up the basis for the list that will be checked for command caching - Took down some notes for continuing with the project in the morning. All of these are findable in the comments within the functions. - Pretty much have the 'get_snek' function done. Just have a few things I would like to flesh out. - Cleared the Wikipedia module from 'Pipfile' and 'Pipfile.lock'. Let's hope I didn't screw anything up with that one. --- Pipfile | 1 - Pipfile.lock | 38 +---------------------------------- bot/cogs/snakes.py | 50 ++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 49 insertions(+), 40 deletions(-) diff --git a/Pipfile b/Pipfile index 3feb1dec..096fb9b3 100644 --- a/Pipfile +++ b/Pipfile @@ -8,7 +8,6 @@ name = "pypi" aiodns = "*" aiohttp = "<2.3.0,>=2.0.0" websockets = ">=4.0,<5.0" -wikipedia = "*" [dev-packages] "flake8" = "*" diff --git a/Pipfile.lock b/Pipfile.lock index 0399cdb0..4e5214bb 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -1,7 +1,7 @@ { "_meta": { "hash": { - "sha256": "738768c7b3fa9b26b2b995f90b9324d0d058394442c75e2407bc3b010d290de3" + "sha256": "d797e580ddcddc99bf058109ab0306ad584c2902752a3d4076ba713fdc580fb7" }, "pipfile-spec": 6, "requires": { @@ -53,21 +53,6 @@ ], "version": "==2.0.1" }, - "beautifulsoup4": { - "hashes": [ - "sha256:11a9a27b7d3bddc6d86f59fb76afb70e921a25ac2d6cc55b40d072bd68435a76", - "sha256:7015e76bf32f1f574636c4288399a6de66ce08fb7b2457f628a8d70c0fbabb11", - "sha256:808b6ac932dccb0a4126558f7dfdcf41710dd44a4ef497a0bb59a77f9f078e89" - ], - "version": "==4.6.0" - }, - "certifi": { - "hashes": [ - "sha256:14131608ad2fd56836d33a71ee60fa1c82bc9d2c8d98b7bdbc631fe1b3cd1296", - "sha256:edbc3f203427eef571f79a7692bb160a2b0f7ccaa31953e99bd17e307cf63f7d" - ], - "version": "==2018.1.18" - }, "chardet": { "hashes": [ "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", @@ -135,20 +120,6 @@ ], "version": "==2.3.0" }, - "requests": { - "hashes": [ - "sha256:6a1b267aa90cac58ac3a765d067950e7dbbf75b1da07e895d1f594193a40a38b", - "sha256:9c443e7324ba5b85070c4a818ade28bfabedf16ea10206da1132edaa6dda237e" - ], - "version": "==2.18.4" - }, - "urllib3": { - "hashes": [ - "sha256:06330f386d6e4b195fbfc736b297f58c5a892e4440e54d294d7004e3a9bbea1b", - "sha256:cc44da8e1145637334317feebd728bd869a35285b93cbb4cca2577da7e62db4f" - ], - "version": "==1.22" - }, "websockets": { "hashes": [ "sha256:0c31bc832d529dc7583d324eb6c836a4f362032a1902723c112cf57883488d8c", @@ -171,13 +142,6 @@ "index": "pypi", "version": "==4.0.1" }, - "wikipedia": { - "hashes": [ - "sha256:db0fad1829fdd441b1852306e9856398204dc0786d2996dd2e0c8bb8e26133b2" - ], - "index": "pypi", - "version": "==1.4.0" - }, "yarl": { "hashes": [ "sha256:045dbba18c9142278113d5dc62622978a6f718ba662392d406141c59b540c514", diff --git a/bot/cogs/snakes.py b/bot/cogs/snakes.py index 972f7b06..6eaf6b69 100644 --- a/bot/cogs/snakes.py +++ b/bot/cogs/snakes.py @@ -1,5 +1,8 @@ # coding=utf-8 import logging +import json +from aiohttp import ClientSession +from random import choice from time import time from typing import Any, Dict @@ -20,11 +23,13 @@ def __init__(self, bot: AutoShardedBot): self.bot = bot self.game = SnakeGame((5, 5)) self.debug = True - self.mods = ["kr4n3x#5014", "(PC) Refisio#9732"] + # changed this to (User.id: int) in order to make it easier down the line to call. >(PC) + self.mods = [255254195505070081, 98694745760481280] self.last_movement = time() self.movement_command = {"left": 0, "right": 0, "up": 0, "down": 0} self.wait_time = 2 + # docstring for get_snek needs to be cleaned up >(PC) async def get_snek(self, name: str = None) -> Dict[str, Any]: """ Go online and fetch information about a snake @@ -39,6 +44,16 @@ async def get_snek(self, name: str = None) -> Dict[str, Any]: :return: A dict containing information on a snake """ + url = f'https://en.wikipedia.org/w/api.php?action=query&titles={name}' \ + f'&prop=extracts&exlimit=1&explaintext&format=json&formatversion=2' + + # account for snakes without a page somewhere. >(PC) + async with ClientSession() as session: + async with session.get(url) as response: + resp = json.loads(str(await response.read(), 'utf-8')) + return resp + + # docstring for get needs to be cleaned up. >(PC) @command() async def get(self, ctx: Context, name: str = None): """ @@ -50,6 +65,35 @@ 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 """ + # Everything with snek_list should be cached >(PC) + # SELF.BOT.SNEK_LIST OMG OMG OMG >(PC) + # Since, on restart, the bot will forget this, it will be re-cached every time. Problem Solved in theory. >(PC) + possible_names = 'https://en.wikipedia.org/w/api.php?action=query&titles=List_of_snakes_by_common_name' \ + '&prop=extracts&exlimit=1&explaintext&format=json&formatversion=2' + + async with ClientSession() as session: + async with session.get(possible_names) as all_sneks: + resp = str(await all_sneks.read(), 'utf-8') + + # can we find a better way to do this? Doesn't seem too reliable, even though MW won't change their api. >(PC) + snek_list = resp[409:].lower().split('\\n') + + # if name is None, choose a random snake. Need to clean up snek_list. >(PC) + if name is None: + name = choice(snek_list) + + # stops the command if the snek is not on the list >(PC) + elif name.lower() not in snek_list: + await ctx.send('This is not a valid snake. Please request one that exists.\n' + 'You can find a list of existing snakes here: ') + return + + # accounting for the spaces in the names of some snakes. Allows for parsing of spaced names. >(PC) + if name.split(' '): + name = '%20'.join(name.split(' ')) + + # leaving off here for the evening. Building the embed is easy. Pulling the information is hard. /s >(PC) + # snek_dict = await self.get_snek(name) # Any additional commands can be placed here. Be creative, but keep it to a reasonable amount! @command() @@ -64,6 +108,8 @@ async def play(self, ctx: Context, order): With 'left', 'right', 'up' and 'down' as valid directions. """ + # Maybe one game at a given time, and maybe editing the original message instead of constantly posting + # new ones? Maybe we could also ask nicely for DMs to be allowed for this if they aren't. >(PC) if order in self.movement_command.keys(): self.movement_command[order] += 1 @@ -85,7 +131,7 @@ async def play(self, ctx: Context, order): value="{dir}: {per:.2f}%".format(dir=direction, per=percentage)) snek_head = next(emoji for emoji in ctx.guild.emojis if emoji.name == 'python') - + game_string = str(self.game).replace(":python:", str(snek_head)) snekembed.add_field(name="Board", value=game_string, inline=False) if self.debug: