First commit of cogs from old branch with some smaller files

This commit is contained in:
TrustyJAID committed 2018-12-05 21:10:56 -07:00
1 parent 9a6dec1b0a
commit 7e8150dec6
254 files changed
+42000 -1

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
+51
View File
@@ -0,0 +1,51 @@
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# =========================
# Operating System Files
# =========================
# OSX
# =========================
.DS_Store
.AppleDouble
.LSOverride
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
__pycache__/
audiotest/
trusty-cogs.sublime-workspace
*.sublime-workspace
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 TrustyJAID
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+85 -1
View File
@@ -1 +1,85 @@
# Trusty-cogs
# Trusty-cogs V3
TrustyJAID's Cogs for [Red-DiscordBot](https://github.com/Cog-Creators/Red-DiscordBot/tree/V3/develop).
To add the cogs to your instance please do: `[p]repo add Trusty-cogs https://github.com/TrustyJAID/Trusty-cogs/ V3`
## About Cogs
| Name | Status | Description (Click to see full status)
| --- | --- | --- |
| Hockey | **Release** | <details><summary>A cog to gather hockey scores, schedules, player data and more!</summary> If you would like to use the built in emoljis, ask me (TrustyJAID#0001) on discord to add your bot to my server hosting the emojis used in this cog.</details>|
| Tarot | **Release** | Find your tarot reading, your life reading, or pull a random tarot card! Can also search for a card. |
| Faces | **Release** | Find your own Japanese style emoji face courtesy of the CIA. |
| REKT | **Release** | a command to see how rekt someone is. |
| Weather | **Release** | check the current weather in many cities around the world including in Kelvin. |
| Starboad | **Release** | add a starboard channel with custom reaction's. |
| Imgflip | **release** | A recreation of the meme generator from red V1. |
| Imagemaker | **Release** | <details><summary>A cog to paste avatars onto images like beautiful and pepe.</summary> Requirements: pillow, opencv-python, and numpy</details> |
| Conversions | **Release** | Currency, crypto, and stocks commands. |
| Emojireact | **Release** | Have your bot react to emojis in messages with the emoji! |
| Badges | **Release** | <details><summary>Create your own badge with from discord information.</summary> Includes templates for fake CIA, NSA, FBI, Discord, and every NHL hockey team. Requirements: pillow, pybarcode</details> |
| Tweets | **Release** | <details><summary>A modified version of Palmtree5's twitter cog utilising twitter streams to setup a twitter channel to post user tweets.</summary> Requirements: tweepy</details> |
| Mock | **Release** | <details><summary>Mock the user who last posted!</summary>Note: This requires not having the `--dev` flag enabled, however if you need both install the dev cog in my repo.</details> |
| Translate | **Release** | Add flag emojis to messages to translate to that language or translate messages by command. (Uses Google Translate and may incur some fees) |
| AddImage | **Release** | <details><summary>Allows you to add images to be posted on command.</summary> Stores the image in the bot folder then uploads the image directly. Owners may add images globally.</details> |
| Triggersize | **Release** | <details><summary>Posts various sized images based on specific triggered command lengths.</summary> May be customized manually for different images or by default express ones true rage.</details> |
| Encoding | **Release** | Allows one to encode or decode in Binary and DNA sequencing (ACGT). As well has hashing strings and caeser cipher text. |
| Compliment | **Release** | Compliment a user! |
| ServerStats | **Release** | This cog provides a ton of useful development functions for gathering channel data and user data as well as providing a way to setup a channel to monitor which servers are adding the bot. |
| Runescape | **Beta** | a cog to grab Runescape 3 stats and profile information. |
| Fun | **Release**| The fun cog from Appu's Selfbot rewritten for redbot V3 including adding reactions and other "fun" commands. |
| Gabai | **Beta** | A cog to verify a user is on gab before letting them join the server. |
| Notsobot | **Beta**| Working cog for many of NotSoBot's commands. Has lots of requirements, view the cog README.md for details. |
| Spoiler | **Beta**| Post spoiler messages in chat and react to the message to view the spoilers. |
| ReTrigger | **Release** | <details><summary>Trigger events based on regex!</summary>Note: This repo requires pillow to allow resizing of images similar to triggersize cog.</details> |
## Works in Progress
*These Cogs are a work in progress and have limited to no functionality at the moment. Feel free to leave ideas or suggestions!*
| Name | Status | Description (Click to see full status)
| --- | --- | --- |
| Anime | **Alpha**| <details><summary>A cog that gets what current anime episodes are airing and posts them on discord when they start airing.</summary> There was an update to the API being used and I need to rewrite for the new API.</details> |
| Halo | **Work in Progress**| Cogs for accessing information from the Halo video games API systems. |
| Chatterbot | **Alpha** | Teach your bot how to talk by watching conversations on servers and reply. Uses chatterbot library. NOTE: This cog is not recommended to be used at this time. After a month of usage it caused the whole bot to slow down while it searched for responses. I recommend looking at cleverbot for the time being. |
## Rewritten Cogs Originally Made by others
*These cogs were originally written by others for V2. As they were used frequently on TrustyBot I ported them over quickly for V3. A better version may be available.*
| Name | Status | Description (Click to see full status)
| --- | --- | --- |
| Autorole | **Release**| Automatically apply roles when a user joins the server. |
| Stickyroles | **Release**| Keep user roles when they leave the server and re-join. Useful for muted roles. |
| Welcome | **Beta**| Welcomes users to the server. |
| Modlogs | **Beta**| A more in-depth modlog cog for more information about users joining/leaving and messages edited/deleted. |
| Cleverbot | **Release**| <details><summary>Have your bot respond with cleverbot responses.</summary>Cleverbot.com requires a paid API key, cleverbot.io is supported </details> |
| Insult | **Release**| Insult a user! |
## Special cogs
*These cogs are not meant for mainstream use but may provide some useful functions for some people. Support may be limited.*
| Name | Status | Description (Click to see full status)
| --- | --- | --- |
| Backup | **Release** | Backs up all messages on a server. Use with caution and ensure any backups are stored on an encrypted drive. |
| Juche | **Release** | Corrects dates posted in discord with the current Juche year. |
| Dev | **Release** | A copy of the developer commands in redbot with `sudo` replacing `mock` like V2. NOTE:This bypasses the `--dev` flag and is not recommended unless you know what you're doing. |
| Hue | **Release** | A cog to control Philips Hue lights through discord. Not tested with bots outside the home network. |
Any questions you can find me and TrustyBot over on [my server](https://discord.gg/wVVrqej) or on the [Redbot Cog Support server](https://discord.gg/GET4DVk)
## Credits
* Twentysix - Cleverbot cog, imgflip cog, Stickyroles cog
* Lunar Dust - Autorole cog
* Arien - Compliments cog, Insult cog
* JennJenn - Compliments cog, Insult cog
* Appu - Fun cog
* Ivan Seidel (isnowillegal.com) - Trump command
* Bruno Lemos (isnowillegal.com) - Trump command
* João Pedro (isnowillegal.com) - Trump command
* RePulsR - Modlogs cog
* NotSoSuper - Notsobot cog
* Aziz - Translate cog
* Palmtree5 - Tweets cog
* irdumb - Welcome cog
+22
View File
@@ -0,0 +1,22 @@
# TODO list for Trusty-cogs
*These are planned updates I would like to complete for each cog*
## Hockey
> Image only based on channel permissions
> Game day threads from associated subreddit
## Anime
> Rewrite for new API
## Activity
>Check for users last post on refresh and startup (allows for quicker kicking of inactive users)
## Badges
> Allow creation of templates through discord
## Starboard
> Allow multiple starboards per server
## Chatter
> Optimize for v3 and utilize async to get responses
+5
View File
@@ -0,0 +1,5 @@
from .addimage import AddImage
def setup(bot):
n = AddImage(bot)
bot.add_cog(n)
+419
View File
@@ -0,0 +1,419 @@
from random import choice, randint
import random
import aiohttp
import discord
import asyncio
from redbot.core import commands
from redbot.core import checks
from redbot.core import Config
from redbot.core.data_manager import cog_data_path
from pathlib import Path
import os
import string
from redbot.core.i18n import Translator
_ = Translator("Alias", __file__)
class AddImage(getattr(commands, "Cog", object)):
def __init__(self, bot):
self.bot = bot
self.session = aiohttp.ClientSession(loop=self.bot.loop)
temp_folder = cog_data_path(self) /"global"
temp_folder.mkdir(exist_ok=True, parents=True)
default_global = {"images":[]}
default_guild = {"images":[]}
self.config = Config.get_conf(self, 16446735546)
self.config.register_global(**default_global)
self.config.register_guild(**default_guild)
async def first_word(self, msg):
return msg.split(" ")[0].lower()
async def get_prefix(self, message: discord.Message) -> str:
"""
From Redbot Alias Cog
Tries to determine what prefix is used in a message object.
Looks to identify from longest prefix to smallest.
Will raise ValueError if no prefix is found.
:param message: Message object
:return:
"""
content = message.content
prefix_list = await self.bot.command_prefix(self.bot, message)
prefixes = sorted(prefix_list,
key=lambda pfx: len(pfx),
reverse=True)
for p in prefixes:
if content.startswith(p):
return p
raise ValueError(_("No prefix found."))
async def part_of_existing_command(self, alias):
'''Command or alias'''
command = self.bot.get_command(alias)
return command is not None
async def make_guild_folder(self, directory):
if not directory.is_dir():
print("Creating guild folder")
directory.mkdir(exist_ok=True, parents=True)
async def get_image(self, alias, guild=None)-> dict:
if guild is None:
list_images = await self.config.images()
for image in await self.config.images():
if image["command_name"].lower() == alias.lower():
return image
else:
list_images = await self.config.guild(guild).images()
for image in await self.config.guild(guild).images():
# print(image)
if image["command_name"].lower() == alias.lower():
return image
async def local_perms(self, message):
"""Check the user is/isn't locally whitelisted/blacklisted.
https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/release/3.0.0/redbot/core/global_checks.py
"""
if await self.bot.is_owner(message.author):
return True
elif message.guild is None:
return True
guild_settings = self.bot.db.guild(message.guild)
local_blacklist = await guild_settings.blacklist()
local_whitelist = await guild_settings.whitelist()
_ids = [r.id for r in message.author.roles if not r.is_default()]
_ids.append(message.author.id)
if local_whitelist:
return any(i in local_whitelist for i in _ids)
return not any(i in local_blacklist for i in _ids)
async def global_perms(self, message):
"""Check the user is/isn't globally whitelisted/blacklisted.
https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/release/3.0.0/redbot/core/global_checks.py
"""
if await self.bot.is_owner(message.author):
return True
whitelist = await self.bot.db.whitelist()
if whitelist:
return message.author.id in whitelist
return message.author.id not in await self.bot.db.blacklist()
async def check_ignored_channel(self, message):
"""https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/release/3.0.0/redbot/cogs/mod/mod.py#L1273"""
channel = message.channel
guild = channel.guild
author = message.author
mod = self.bot.get_cog("Mod")
perms = channel.permissions_for(author)
surpass_ignore = (
isinstance(channel, discord.abc.PrivateChannel)
or perms.manage_guild
or await self.bot.is_owner(author)
or await self.bot.is_admin(author)
)
if surpass_ignore:
return True
guild_ignored = await mod.settings.guild(guild).ignored()
chann_ignored = await mod.settings.channel(channel).ignored()
return not (guild_ignored or chann_ignored and not perms.manage_channels)
async def on_message(self, message):
if len(message.content) < 2 or message.guild is None:
return
msg = message.content
guild = message.guild
channel = message.channel
try:
prefix = await self.get_prefix(message)
except ValueError:
return
alias = await self.first_word(msg[len(prefix):])
if not await self.local_perms(message):
return
if not await self.global_perms(message):
return
if not await self.check_ignored_channel(message):
return
if alias in [x["command_name"] for x in await self.config.images()]:
if channel.permissions_for(channel.guild.me).attach_files:
await channel.trigger_typing()
image = await self.get_image(alias)
list_images = await self.config.images()
list_images.remove(image)
image["count"] += 1
list_images.append(image)
await self.config.images.set(list_images)
file = discord.File(image["file_loc"])
await channel.send(file=file)
elif alias in [x["command_name"] for x in await self.config.guild(guild).images()]:
if channel.permissions_for(channel.guild.me).attach_files:
await channel.trigger_typing()
image = await self.get_image(alias, guild)
guild_images = await self.config.guild(guild).images()
guild_images.remove(image)
image["count"] += 1
guild_images.append(image)
await self.config.guild(guild).images.set(guild_images)
file = discord.File(image["file_loc"])
await channel.send(file=file)
async def check_command_exists(self, command, guild):
if command in [x["command_name"] for x in await self.config.guild(guild).images()]:
return True
elif await self.part_of_existing_command(command):
return True
elif command in [x["command_name"] for x in await self.config.images()]:
return True
else:
return False
async def image_menu(self, ctx:commands.Context, post_list: list,
message: discord.Message=None,
page=0, timeout: int=30):
"""menu control logic for this taken from
https://github.com/Lunar-Dust/Dusty-Cogs/blob/master/menu/menu.py"""
post = post_list[page]
if ctx.channel.permissions_for(ctx.me).embed_links:
em = discord.Embed(timestamp=ctx.message.created_at)
for image in post:
info = "__Author__: <@{}>\n__Count__: **{}**".format(image["author"], image["count"])
em.add_field(name=image["command_name"], value=info)
em.set_author(name=self.bot.user.display_name, icon_url=self.bot.user.avatar_url)
em.set_footer(text="Page {}/{}".format(page+1, len(post_list)))
else:
await ctx.send("I need embed_links permission to use this command.")
return
if len(post_list) == 1:
# No need to offer multiple pages if they don't exist
await ctx.send(embed=em)
return
if not message:
message = await ctx.send(embed=em)
await message.add_reaction("⬅")
await message.add_reaction("❌")
await message.add_reaction("➡")
else:
# message edits don't return the message object anymore lol
await message.edit(embed=em)
check = lambda react, user:user == ctx.message.author and react.emoji in ["➡", "⬅", "❌"] and react.message.id == message.id
try:
react, user = await ctx.bot.wait_for("reaction_add", check=check, timeout=timeout)
except asyncio.TimeoutError:
await message.remove_reaction("⬅", ctx.guild.me)
await message.remove_reaction("❌", ctx.guild.me)
await message.remove_reaction("➡", ctx.guild.me)
return None
else:
if react.emoji == "➡":
next_page = 0
if page == len(post_list) - 1:
next_page = 0 # Loop around to the first item
else:
next_page = page + 1
try:
await message.remove_reaction("➡", ctx.message.author)
except:
pass
return await self.image_menu(ctx, post_list, message=message,
page=next_page, timeout=timeout)
elif react.emoji == "⬅":
next_page = 0
if page == 0:
next_page = len(post_list) - 1 # Loop around to the last item
else:
next_page = page - 1
try:
await message.remove_reaction("⬅", ctx.message.author)
except:
pass
return await self.image_menu(ctx, post_list, message=message,
page=next_page, timeout=timeout)
else:
return await message.delete()
@commands.group()
@commands.guild_only()
async def addimage(self, ctx):
"""
Add an image for the bot to directly upload
"""
pass
@addimage.command(name="list")
async def listimages(self, ctx, image_loc="guild", server_id:int=None):
"""List images added to bot"""
msg = ""
if image_loc in ["global"]:
image_list = await self.config.images()
elif image_loc in ["guild", "server"]:
if server_id is None:
guild = ctx.message.guild
else:
guild = self.bot.get_guild(server_id)
image_list = await self.config.guild(guild).images()
if image_list == []:
await ctx.send("{} does not have any images saved!".format(self.bot.user.display_name))
return
post_list = [image_list[i:i + 25] for i in range(0, len(image_list), 25)]
await self.image_menu(ctx, post_list)
@addimage.command()
async def clear_list(self, ctx):
await self.config.images.set([])
await self.config.guild(ctx.guild).images.set([])
@addimage.command(name="delete", aliases=["remove", "rem", "del"])
async def remimage(self, ctx, cmd):
"""Remove a selected images"""
author = ctx.message.author
guild = ctx.message.guild
channel = ctx.message.channel
cmd = cmd.lower()
if cmd not in [x["command_name"] for x in await self.config.guild(guild).images()]:
await ctx.send("{} is not an image for this guild!".format(cmd))
return
await channel.trigger_typing()
all_imgs = await self.config.guild(guild).images()
image = await self.get_image(cmd, guild)
all_imgs.remove(image)
try:
os.remove(image.file_loc)
except:
pass
await self.config.guild(guild).images.set(all_imgs)
await ctx.send("{} has been deleted from this guild!".format(cmd))
@checks.is_owner()
@addimage.command(hidden=True, name="deleteglobal", aliases=["dg", "delglobal"])
async def rem_image_global(self, ctx, cmd):
"""Remove a selected images"""
author = ctx.message.author
guild = ctx.message.guild
channel = ctx.message.channel
cmd = cmd.lower()
if cmd not in [x["command_name"] for x in await self.config.images()]:
await ctx.send("{} is not a global image!".format(cmd))
return
await channel.trigger_typing()
all_imgs = await self.config.images()
image = await self.get_image(cmd)
all_imgs.remove(image)
try:
os.remove(image.file_loc)
except:
pass
await self.config.images.set(all_imgs)
await ctx.send("{} has been deleted globally!".format(cmd))
async def save_image_location(self, msg, cmd, guild=None):
seed = ''.join(random.sample(string.ascii_uppercase + string.digits, k=5))
filename = "{}-{}".format(seed, msg.attachments[0].filename)
if guild is not None:
directory = cog_data_path(self) /str(guild.id)
cur_images = await self.config.guild(guild).images()
else:
directory = cog_data_path(self) /"global"
cur_images = await self.config.images()
await self.make_guild_folder(directory)
cmd = cmd.lower()
file_path = "{}/{}".format(str(directory), filename)
new_entry = {"command_name": cmd,
"count": 0,
"file_loc": file_path,
"author": msg.author.id}
cur_images.append(new_entry)
async with self.session.get(msg.attachments[0].url) as resp:
test = await resp.read()
with open(file_path, "wb") as f:
f.write(test)
if guild is not None:
await self.config.guild(guild).images.set(cur_images)
else:
await self.config.images.set(cur_images)
async def wait_for_image(self, ctx):
msg = None
while msg is None:
check = lambda m: m.author == ctx.message.author and m.attachments != []
try:
msg = await self.bot.wait_for("message", check=check, timeout=60)
except asyncio.TimeoutError:
await ctx.send("Image adding timed out.")
break
if msg.content.lower().strip() == "exit":
await ctx.send("Image adding cancelled.")
break
return msg
@addimage.command(pass_context=True, name="add")
async def add_image_guild(self, ctx, cmd):
"""Add an image to direct upload."""
author = ctx.message.author
guild = ctx.message.guild
channel = ctx.message.channel
if cmd.lower() == "global":
await ctx.send("global is not a valid command name! Try something else.")
return
if await self.check_command_exists(cmd, guild):
await ctx.send("{} is already in the list, try another!".format(cmd))
return
else:
await ctx.send("{} added as the command!".format(cmd))
if ctx.message.attachments == []:
await ctx.send("Upload an image for me to use! Type `exit` to cancel.")
msg = await self.wait_for_image(ctx)
if msg is None:
return
await self.save_image_location(msg, cmd, guild)
await ctx.send("{} has been added to my files!".format(cmd))
else:
await self.save_image_location(ctx.message, cmd, guild)
@checks.is_owner()
@addimage.command(hidden=True, pass_context=True, name="addglobal")
async def add_image_global(self, ctx, cmd):
"""Add an image to direct upload."""
author = ctx.message.author
guild = ctx.message.guild
channel = ctx.message.channel
msg = ctx.message
if cmd.lower() == "global":
await ctx.send("global is not a valid command name! Try something else.")
return
if await self.check_command_exists(cmd, guild):
await ctx.send("{} is already in the list, try another!".format(cmd))
return
else:
await ctx.send("{} added as the command!".format(cmd))
if ctx.message.attachments == []:
await ctx.send("Upload an image for me to use! Type `exit` to cancel.")
msg = await self.wait_for_image(ctx)
if msg is None:
return
await self.save_image_location(msg, cmd)
await ctx.send("{} has been added to my files!".format(cmd))
else:
await self.save_image_location(ctx.message, cmd)
def __unload(self):
self.bot.loop.create_task(self.session.close())
+22
View File
@@ -0,0 +1,22 @@
{
"author":[
"TrustyJAID"
],
"description":"Add image for the bot to directly upload similar to alias.",
"install_msg":"[p]addimage to add an image to the guild. Owner can add global bot images.",
"min_python_version":[
3,
6,
2
],
"name":"AddImage",
"permissions":[
"attach_files"
],
"requirements":[],
"short":"Add images for direct upload per guild and globally.",
"tags":[
"utility",
"images"
]
}
+7
View File
@@ -0,0 +1,7 @@
from .autorole import Autorole
def setup(bot):
n = Autorole(bot)
bot.add_cog(n)
# bot.add_listener(n._roler, "on_member_join")
# bot.add_listener(n._verify_json, "on_error")
+339
View File
@@ -0,0 +1,339 @@
import discord
from redbot.core import commands, checks, Config
import random
import string
default_settings = {
"ENABLED": False,
"ROLE": [],
"AGREE_CHANNEL": None,
"AGREE_MSG": None,
"AGREE_KEY": None
}
class Autorole(getattr(commands, "Cog", object)):
"""
Autorole commands. Rewritten for V3 from
https://github.com/Lunar-Dust/Dusty-Cogs/blob/master/autorole/autorole.py
"""
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 45463543548)
self.config.register_guild(**default_settings)
self.users = {}
async def _no_perms(self, channel=None):
m = ("It appears that you haven't given this "
"bot enough permissions to use autorole. "
"The bot requires the \"Manage Roles\" and "
"the \"Manage Messages\" permissions in"
"order to use autorole. You can change the "
"permissions in the \"Roles\" tab of the "
"guild settings.")
if channel is None:
print(m)
return
if channel.permissions_for(channel.guild.me).send_messages:
await channel.send(m)
else:
print(m + f"\n I also don't have permission to speak in #{channel.name}")
async def on_message(self, message):
guild = message.guild
user = message.author
channel = message.channel
try:
agree_channel = guild.get_channel(await self.config.guild(guild).AGREE_CHANNEL())
except:
return
if guild is None:
return
if agree_channel is None:
return
if channel.id != agree_channel.id:
return
if user.bot:
return
if user.id in self.users:
if not guild.me.guild_permissions.manage_roles:
await self._no_perms(agree_channel)
return
if self.users[user.id].lower() in message.content.lower():
roles_id = await self.config.guild(guild).ROLE()
del self.users[user.id]
roles = [role for role in guild.roles if role.id in roles_id]
for role in roles:
await user.add_roles(role, reason="Agreed to the rules")
if agree_channel.permissions_for(guild.me).add_reactions:
await message.add_reaction("✅")
async def _agree_maker(self, member):
guild = member.guild
self.last_guild = guild
# await self._verify_json(None)
key = await self.config.guild(guild).AGREE_KEY()
if key is None:
key = ''.join(random.choice(string.ascii_uppercase +
string.digits) for _ in range(6))
# <3 Stackoverflow http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python/23728630#23728630
self.users[member.id] = key
ch = guild.get_channel(await self.config.guild(guild).AGREE_CHANNEL())
msg = await self.config.guild(guild).AGREE_MSG()
if msg is None:
msg = "{mention} please enter {key} in {channel}"
try:
msg = msg.format(key=key,
member=member,
name=member.name,
mention=member.mention,
guild=guild.name,
channel=ch.mention)
except Exception as e:
print(e)
try:
msg = await member.send(msg)
except discord.Forbidden:
msg = await ch.send(msg)
except discord.HTTPException:
return
async def _auto_give(self, member):
guild = member.guild
roles_id = await self.config.guild(guild).ROLE()
roles = [role for role in guild.roles if role.id in roles_id]
if not guild.me.guild_permissions.manage_roles:
await self._no_perms()
return
for role in roles:
await member.add_roles(role, reason="Joined the server")
async def on_member_join(self, member):
guild = member.guild
if await self.config.guild(guild).ENABLED():
if await self.config.guild(guild).AGREE_CHANNEL() is not None:
await self._agree_maker(member)
else: # Immediately give the new user the role
await self._auto_give(member)
@commands.group(name="autorole", no_pm=True)
async def autorole(self, ctx):
"""
Change settings for autorole
Requires the manage roles permission
"""
if ctx.invoked_subcommand is None:
guild = ctx.message.guild
enabled = await self.config.guild(guild).ENABLED()
roles = await self.config.guild(guild).ROLE()
msg = await self.config.guild(guild).AGREE_MSG()
key = await self.config.guild(guild).AGREE_KEY()
channel = await self.config.guild(guild).AGREE_CHANNEL()
chn_mention = guild.get_channel(channel).name if channel is not None else "None"
role_name = []
role_name_str = ", ".join(role.name for role in guild.roles if role.id in roles)
send_msg = ("```Current autorole state: {}\nCurrent Roles:{}\n"
"Agreement message: {}\n"
"Agreement key: {}\n"
"Agreement channel: {}```")
await ctx.send(send_msg.format(enabled, role_name_str, msg, key, chn_mention))
@autorole.command(no_pm=True)
@checks.admin_or_permissions(manage_roles=True)
async def toggle(self, ctx):
"""
Enables/Disables autorole
"""
guild = ctx.message.guild
if await self.config.guild(guild).ROLE() is None:
await ctx.send("You haven't set a role to give to new users! "
"Use `{}autorole role \"role\"` to set it!"
.format(ctx.prefix))
else:
if await self.config.guild(guild).ENABLED():
await self.config.guild(guild).ENABLED.set(False)
await ctx.send("Autorole is now disabled.")
else:
await self.config.guild(guild).ENABLED.set(True)
await ctx.send("Autorole is now enabled.")
@autorole.command(no_pm=True, name="add", aliases=["role"])
@checks.admin_or_permissions(manage_roles=True)
async def role(self, ctx, *, role: discord.Role):
"""
Add a role for autorole to assign.
You can use this command multiple times to add multiple roles.
"""
guild = ctx.message.guild
roles = await self.config.guild(guild).ROLE()
if not guild.me.guild_permissions.manage_roles:
await ctx.send("I don't have the manage roles permission to use these features!")
return
if role.id in roles:
await ctx.send("{} is already in the autorole list.".format(role.name))
return
if guild.me.top_role < role:
await ctx.send("{} is higher than my highest role in the Discord hierarchy.".format(role.name))
return
roles.append(role.id)
await self.config.guild(guild).ROLE.set(roles)
await ctx.send(f"Added the role `{role.name}` to the autorole.")
@autorole.command(no_pm=True)
@checks.admin_or_permissions(manage_roles=True)
async def remove(self, ctx, *, role: discord.Role):
"""
Remove a role from the autorole.
"""
guild = ctx.message.guild
roles = await self.config.guild(guild).ROLE()
if role.id not in roles:
await ctx.send("{} is not in the autorole list.".format(role.name))
return
roles.remove(role.id)
await self.config.guild(guild).ROLE.set(roles)
await ctx.send(f"Removed the role `{role.name}` from the autorole.")
@autorole.group(no_pm=True)
@checks.admin_or_permissions(manage_roles=True)
async def agreement(self, ctx):
"""
Set the channel and message that will be used for accepting the rules.
`channel` is the channel they must type the key in to get the role.
`key` is the message they must type to gain access and must be in quotes.
`msg` is the message DM'd to them when they join.
`{key}` must be included in the message so a user knows what to type in the channel.
Optional additions to the message include:
`{channel}` Mentions the channel where they must include the agreement message.
`{mention}` Mentions the user incase they have DM permissions turned off this should be used.
`{name}` Says the member name if you don't want to ping them.
`{guild}` Says the servers current name.
Entering nothing will disable these.
"""
@agreement.command(no_pm=True, name="channel")
@checks.admin_or_permissions(manage_roles=True)
async def set_agreement_channel(self, ctx, channel: discord.TextChannel=None):
"""
Set the agreement channel
Entering nothing will clear this.
"""
guild = ctx.message.guild
if await self.config.guild(guild).ROLE() == []:
await ctx.send("No roles have been set for autorole.")
return
if not await self.config.guild(guild).ENABLED():
await ctx.send("Autorole has been disabled, enable it first.")
return
if channel is None:
await self.config.guild(guild).AGREE_CHANNEL.set(None)
await ctx.send("Agreement channel cleared")
else:
await self.config.guild(guild).AGREE_CHANNEL.set(channel.id)
await ctx.send(f"Agreement channel set to {channel.mention}")
@agreement.command(no_pm=True, name="key")
@checks.admin_or_permissions(manage_roles=True)
async def set_agreement_key(self, ctx, *, key: str=None):
"""
Set the agreement key
Entering nothing will clear this.
"""
guild = ctx.message.guild
if await self.config.guild(guild).ROLE() == []:
await ctx.send("No roles have been set for autorole.")
return
if not await self.config.guild(guild).ENABLED():
await ctx.send("Autorole has been disabled, enable it first.")
return
if key is None:
await self.config.guild(guild).AGREE_KEY.set(None)
await ctx.send("Agreement key cleared")
else:
await self.config.guild(guild).AGREE_KEY.set(key)
await ctx.send(f"Agreement key set to {key}")
@agreement.command(no_pm=True, name="message", aliases=["msg"])
@checks.admin_or_permissions(manage_roles=True)
async def set_agreement_msg(self, ctx, *, message: str=None):
"""
Set the agreement message
`{key}` must be included in the message so a user knows what to type in the channel.
Optional additions to the message include:
`{channel}` Mentions the channel where they must include the agreement message.
`{mention}` Mentions the user incase they have DM permissions turned off this should be used.
`{name}` Says the member name if you don't want to ping them.
`{guild}` Says the servers current name.
Entering nothing will clear this.
"""
guild = ctx.message.guild
if await self.config.guild(guild).ROLE() == []:
await ctx.send("No roles have been set for autorole.")
return
if not await self.config.guild(guild).ENABLED():
await ctx.send("Autorole has been disabled, enable it first.")
return
if message is None:
await self.config.guild(guild).AGREE_MSG.set(None)
await ctx.send("Agreement message cleared")
else:
await self.config.guild(guild).AGREE_MSG.set(message)
await ctx.send(f"Agreement key set to {message}")
@agreement.command(no_pm=True, name="setup")
@checks.admin_or_permissions(manage_roles=True)
async def agreement_setup(self, ctx, channel: discord.TextChannel=None, key: str=None, *, msg: str=None):
"""
Set the channel and message that will be used for accepting the rules.
`channel` is the channel they must type the key in to get the role.
`key` is the message they must type to gain access and must be in quotes.
`msg` is the message DM'd to them when they join.
`{key}` must be included in the message so a user knows what to type in the channel.
Optional additions to the message include:
`{channel}` Mentions the channel where they must include the agreement message.
`{mention}` Mentions the user incase they have DM permissions turned off this should be used.
`{name}` Says the member name if you don't want to ping them.
`{guild}` Says the servers current name.
Entering nothing will disable this.
"""
guild = ctx.message.guild
if await self.config.guild(guild).ROLE() == []:
await ctx.send("No roles have been set for autorole.")
return
if not await self.config.guild(guild).ENABLED():
await ctx.send("Autorole has been disabled, enable it first.")
return
if channel is None:
await self.config.guild(guild).AGREE_CHANNEL.set(None)
await self.config.guild(guild).AGREE_MSG.set(None)
await self.config.guild(guild).AGREE_KEY.set(None)
await ctx.send("Agreement channel cleared")
else:
await self.config.guild(guild).AGREE_CHANNEL.set(channel.id)
await self.config.guild(guild).AGREE_MSG.set(msg)
await self.config.guild(guild).AGREE_KEY.set(key)
await ctx.send("Agreement channel set to {}".format(channel.mention))
+22
View File
@@ -0,0 +1,22 @@
{
"author":[
"Lunar Dust",
"TrustyJAID"
],
"description":"Automatically apply a role to new users",
"install_msg":"autorole",
"min_python_version":[
3,
6,
2
],
"name":"autorole",
"permissions":[
"manage_roles"
],
"requirements":[],
"short":"Automatically apply a role to new users",
"tags":[
"autorole"
]
}
+4
View File
@@ -0,0 +1,4 @@
from .backup import Backup
def setup(bot):
bot.add_cog(Backup(bot))
+145
View File
@@ -0,0 +1,145 @@
import discord
import asyncio
import aiohttp
from redbot.core import commands
from redbot.core import checks
from redbot.core.data_manager import cog_data_path
import datetime
import os
from random import randint
import json
import logging
from typing import Union
class GuildNotFoundError(Exception):
pass
class Backup(getattr(commands, "Cog", object)):
"""
Create a set of json backups of a server
"""
def __init__(self, bot):
self.bot = bot
self.session = aiohttp.ClientSession(loop=self.bot.loop)
def save_json(self, filename, data):
"""Atomically saves json file"""
rnd = randint(1000, 9999)
path, ext = os.path.splitext(filename)
tmp_file = "{}-{}.tmp".format(path, rnd)
self._save_json(tmp_file, data)
try:
self._read_json(tmp_file)
except json.decoder.JSONDecodeError:
self.logger.exception("Attempted to write file {} but JSON "
"integrity check on tmp file has failed. "
"The original file is unaltered."
"".format(filename))
return False
os.replace(tmp_file, filename)
return True
def _read_json(self, filename):
with open(filename, encoding='utf-8', mode="r") as f:
data = json.load(f)
return data
def _save_json(self, filename, data):
with open(filename, encoding='utf-8', mode="w") as f:
json.dump(data, f, indent=4,sort_keys=True,
separators=(',',' : '))
return data
async def check_folder(self, folder_name):
if not os.path.exists("{}/{}".format(str(cog_data_path(self)),folder_name)):
try:
os.makedirs("{}/{}".format(str(cog_data_path(self)),folder_name))
os.makedirs("{}/{}/files".format(str(cog_data_path(self)),folder_name))
return True
except:
return False
else:
return True
async def get_guild_obj(self, guild_name):
if type(guild_name) == int:
page_guild = [g for g in self.bot.guilds if int(guild_name) == g.id]
if type(guild_name) == str:
page_guild = [g for g in self.bot.guilds if guild_name.lower() in g.name.lower()]
try:
if guild_name is not None:
guilds = [g for g in self.bot.guilds]
guild = guilds[guilds.index(page_guild[0])]
except IndexError as e:
raise GuildNotFoundError
return guild
@commands.command(pass_context=True, aliases=["serverbackup"])
@checks.admin_or_permissions(manage_guild=True)
@commands.guild_only()
async def serverlogs(self, ctx, *, guild_name:Union[int, str]=None):
"""
Creat a backup of all server data as json files
`guild_name` is partial name or ID of the server you want to backup
defaults to the server the command was run in
"""
guild = ctx.guild
if guild_name is not None:
try:
guild = await self.get_guild_obj(guild_name)
except GuildNotFoundError:
await ctx.send("{} guild could not be found.".format(guild_name))
return
today = datetime.date.today().strftime("%Y-%m-%d")
channel = ctx.message.channel
is_folder = await self.check_folder(guild.name)
total_msgs = 0
files_saved = 0
if not is_folder:
print("{} folder doesn't exist!".format(guild.name))
return
for chn in guild.channels:
# await channel.send("backing up {}".format(chn.name))
message_list = []
try:
async for message in chn.history(limit=10000000):
data = {"timestamp":message.created_at.strftime("%Y-%m-%d %H:%M:%S"),
"tts":message.tts,
"author":{"name":message.author.name,
"display_name":message.author.display_name,
"discriminator":message.author.discriminator,
"id":message.author.id,
"bot":message.author.bot},
"content":message.content,
"channel":{"name":message.channel.name, "id":message.channel.id},
"mention_everyone":message.mention_everyone,
"mentions":[{"name":user.name,
"display_name":user.display_name,
"discriminator":user.discriminator,
"id":user.id,
"bot":user.bot} for user in message.mentions],
"channel_mentions":[{"name":channel.name,
"id":channel.id} for channel in message.channel_mentions],
"role_mentions":[{"name":role.name,
"id":role.id} for role in message.role_mentions],
"id":message.id,
"pinned":message.pinned}
message_list.append(data)
total_msgs += len(message_list)
if len(message_list) == 0:
continue
self.save_json("{}/{}/{}-{}.json".format(str(cog_data_path(self)),guild.name, chn.name, today), message_list)
await channel.send("{} messages saved from {}".format(len(message_list), chn.name))
except discord.errors.Forbidden:
await channel.send("0 messages saved from {}".format(chn.name))
pass
except AttributeError:
await channel.send("0 messages saved from {}".format(chn.name))
pass
await channel.send("{} messages saved from {}".format(total_msgs, guild.name))
def __unload(self):
self.bot.loop.create_task(self.session.close())
+22
View File
@@ -0,0 +1,22 @@
{
"author":[
"TrustyJAID"
],
"description":"Backup all channel messages on a server. Ensure all saved messages are stored on an encrypted drive!",
"install_msg":"Warning: Ensure all backups are used for personal use or data gathering. User messages are still owned by the original author. All externally saved data must be stored on an encrypted drive.",
"min_python_version":[
3,
6,
2
],
"name":"Backup",
"permissions":[
"read_message_history"
],
"requirements":[],
"short":"Backup all channel messages on a server.",
"tags":[
"utility",
"tools"
]
}
+7
View File
@@ -0,0 +1,7 @@
from .badges import Badges
from redbot.core import data_manager
def setup(bot):
cog = Badges(bot)
data_manager.load_bundled_data(cog, __file__)
bot.add_cog(cog)
+45
View File
@@ -0,0 +1,45 @@
import discord
class Badge:
def __init__(self, badge_name: str, code: str, image: str=None, watermark:str=None, file_name: str=None, is_inverted: bool=False):
super().__init__()
self.badge_name = badge_name
self.code = code
self.file_name = file_name
self.is_inverted = is_inverted
self.image = image
self.watermark = watermark
def to_json(self) -> dict:
return {
"badge_name": self.badge_name,
"code": self.code,
"image": self.image,
"watermark": self.watermark,
"file_name": self.file_name,
"is_inverted": self.is_inverted
}
@classmethod
async def from_json(cls, data: dict):
badge_name = data["badge_name"]
code = data["code"]
is_inverted = data["is_inverted"]
if "file_name" in data:
file_name = data["file_name"]
else:
file_name = None
if "image" in data:
image = data["image"]
else:
image = None
if "watermark" in data:
watermark = data["watermark"]
else:
watermark = None
return cls(badge_name, code, image, watermark, file_name, is_inverted)
+256
View File
@@ -0,0 +1,256 @@
import discord
from redbot.core import commands
import aiohttp
import os
from PIL import Image
from PIL import ImageColor
from PIL import ImageFont
from PIL import ImageDraw
from PIL import ImageSequence
from barcode import generate
from barcode.writer import ImageWriter
from redbot.core.data_manager import bundled_data_path
from redbot.core import Config
from io import BytesIO
from .templates import blank_template
from .badge_entry import Badge
import sys
import functools
import asyncio
class Badges(getattr(commands, "Cog", object)):
"""
Create fun fake badges based on your discord profile
"""
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 1545487348434)
default_guild = {"badges":[]}
default_global = {"badges": blank_template}
self.config.register_global(**default_global)
self.config.register_guild(**default_guild)
self.session = aiohttp.ClientSession(loop=self.bot.loop)
def remove_white_barcode(self, img):
"""https://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent"""
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
return img
def invert_barcode(self, img):
"""https://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent"""
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 0 and item[1] == 0 and item[2] == 0:
newData.append((255, 255, 255))
else:
newData.append(item)
img.putdata(newData)
return img
async def dl_image(self, url):
"""Download bytes like object of user avatar"""
async with self.session.get(url) as resp:
test = await resp.read()
return BytesIO(test)
def make_template(self, user, badge, template):
"""Build the base template before determining animated or not"""
if hasattr(user, "roles"):
department = "GENERAL SUPPORT" if user.top_role.name == "@everyone" else user.top_role.name.upper()
status = user.status
level = str(len(user.roles))
else:
department = "GENERAL SUPPORT"
status = "online"
level = "1"
if str(status) == "online":
status = "ACTIVE"
if str(status) == "offline":
status = "COMPLETING TASK"
if str(status) == "idle":
status = "AWAITING INSTRUCTIONS"
if str(status) == "dnd":
status = "MIA"
barcode = BytesIO()
temp_barcode = generate("code39", str(user.id), writer=ImageWriter(), output=barcode)
barcode = Image.open(barcode)
barcode = self.remove_white_barcode(barcode)
fill = (0, 0, 0) # text colour fill
if badge.is_inverted:
fill = (255, 255, 255)
barcode = self.invert_barcode(barcode)
template = Image.open(template)
template = template.convert("RGBA")
barcode = barcode.convert("RGBA")
barcode = barcode.resize((555,125), Image.ANTIALIAS)
template.paste(barcode, (400,520), barcode)
# font for user information
font_loc = str(bundled_data_path(self)/"arial.ttf")
try:
font1 = ImageFont.truetype(font_loc, 30)
font2 = ImageFont.truetype(font_loc, 24)
except Exception as e:
print(e)
font1 = None
font2 = None
# font for extra information
draw = ImageDraw.Draw(template)
# adds username
draw.text((225, 330), str(user.display_name), fill=fill, font=font1)
# adds ID Class
draw.text((225, 400), badge.code + "-" + str(user).split("#")[1], fill=fill, font=font1)
# adds user id
draw.text((250, 115), str(user.id), fill=fill, font=font2)
# adds user status
draw.text((250, 175), status, fill=fill, font=font2)
# adds department from top role
draw.text((250, 235), department, fill=fill, font=font2)
# adds user level
draw.text((420, 475), "LEVEL " + level, fill="red", font=font1)
# adds user level
if badge.badge_name != "discord" and user is discord.Member:
draw.text((60, 585), str(user.joined_at), fill=fill, font=font2)
else:
draw.text((60, 585), str(user.created_at), fill=fill, font=font2)
return template
def make_animated_gif(self, template, avatar):
"""Create animated badge from gif avatar"""
gif_list = [frame.copy() for frame in ImageSequence.Iterator(avatar)]
img_list = []
num = 0
for frame in gif_list:
temp2 = template.copy()
watermark = frame.copy()
watermark = watermark.convert("RGBA")
watermark = watermark.resize((100,100))
watermark.putalpha(128)
id_image = frame.resize((165, 165))
temp2.paste(watermark, (845,45, 945,145), watermark)
temp2.paste(id_image, (60,95, 225, 260))
temp2.thumbnail((500, 339), Image.ANTIALIAS)
img_list.append(temp2)
num += 1
temp = BytesIO()
temp2.save(temp, format="GIF", save_all=True, append_images=img_list, duration=0, loop=0)
temp.name = "temp.gif"
if sys.getsizeof(temp) > 7000000 and sys.getsizeof(temp) < 8000000:
break
return temp
def make_badge(self, template, avatar):
"""Create basic badge from regular avatar"""
watermark = avatar.convert("RGBA")
watermark.putalpha(128)
watermark = watermark.resize((100,100))
id_image = avatar.resize((165, 165))
template.paste(watermark, (845,45, 945,145), watermark)
template.paste(id_image, (60,95, 225, 260))
temp = BytesIO()
template.save(temp, format="PNG")
temp.name = "temp.gif"
return temp
async def create_badge(self, user, badge):
"""Async create badges handler"""
template_img = await self.dl_image(badge.file_name)
task = functools.partial(self.make_template, user=user, badge=badge, template=template_img)
task = self.bot.loop.run_in_executor(None, task)
try:
template = await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
return
if user.is_avatar_animated():
avatar = Image.open(await self.dl_image(user.avatar_url_as(format="gif")))
task = functools.partial(self.make_animated_gif, template=template, avatar=avatar)
task = self.bot.loop.run_in_executor(None, task)
try:
temp = await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
return
else:
avatar = Image.open(await self.dl_image(user.avatar_url_as(format="png")))
task = functools.partial(self.make_badge, template=template, avatar=avatar)
task = self.bot.loop.run_in_executor(None, task)
try:
temp = await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
return
temp.seek(0)
return temp
async def get_badge(self, badge_name, guild=None):
if guild is None:
guild_badges = []
else:
guild_badges = await self.config.guild(guild).badges()
all_badges = await self.config.badges() + guild_badges
to_return = None
for badge in all_badges:
if badge_name.lower() in badge["badge_name"].lower():
to_return = await Badge.from_json(badge)
return to_return
@commands.group(aliases=["badge"])
async def badges(self, ctx, *, badge):
"""
Creates a fun fake badge based on your discord profile
`badge` is the name of the badges
do `[p]listbadges` to see available badges
"""
guild = ctx.message.guild
user = ctx.message.author
if badge.lower() == "list":
await ctx.invoke(self.listbadges)
return
badge = await self.get_badge(badge, guild)
if badge is None:
await ctx.send_help()
return
async with ctx.channel.typing():
badge_img = await self.create_badge(user, badge)
if badge_img is None:
await ctx.send("Something went wrong sorry!")
return
image = discord.File(badge_img)
await ctx.send(file=image)
@commands.command()
async def listbadges(self, ctx):
"""
List the available badges that can be created
"""
guild = ctx.message.guild
global_badges = await self.config.badges()
guild_badges = await self.config.guild(guild).badges()
msg = ", ".join(badge["badge_name"] for badge in global_badges)
em = discord.Embed()
#for badge in await self.config.badges():
em.add_field(name="Global Badges", value=msg)
if guild_badges != []:
em.add_field(name="Global Badges", value=", ".join(badge["badge_name"] for badge in guild_badges))
await ctx.send(embed=em)
def __unload(self):
self.bot.loop.create_task(self.session.close())
Binary file not shown.
+26
View File
@@ -0,0 +1,26 @@
{
"author":[
"TrustyJAID"
],
"description":"Create your own 3 letter agency badge! Works with gif avatars too.",
"install_msg":"Type [p]badges to see what badges are available!",
"min_python_version":[
3,
6,
2
],
"name":"Badges",
"permissions":[
"attach_files"
],
"requirements":[
"pillow",
"pybarcode"
],
"short":"Create your own badge!",
"tags":[
"general",
"images",
"fun"
]
}
+47
View File
@@ -0,0 +1,47 @@
blank_template = [
{"badge_name":"cia","code":"CIA", "file_name":"https://i.imgur.com/QkDQoqh.png", "is_inverted":False},
{"badge_name":"discord","code":"DISCORD", "file_name":"https://i.imgur.com/undefined.png", "is_inverted":False},
{"badge_name":"cicada","code":"CICADA", "file_name":"https://i.imgur.com/DktANMF.png", "is_inverted":False},
{"badge_name":"ioi","code":"IOI", "file_name":"https://i.imgur.com/kYiSeFf.png", "is_inverted":False},
{"badge_name":"fbi","code":"FBI", "file_name":"https://i.imgur.com/5yM0hy8.png", "is_inverted":False},
{"badge_name":"nsa","code":"NSA", "file_name":"https://i.imgur.com/zW3nCgx.png", "is_inverted":False},
{"badge_name":"gab","code":"GAB", "file_name":"https://i.imgur.com/zS50DI0.png", "is_inverted":False},
{"badge_name":"dop","code":"DOP", "file_name":"https://i.imgur.com/GbX8MxD.png", "is_inverted":False},
{"badge_name":"shit","code":"SHIT", "file_name":"https://i.imgur.com/HK6ieKq.png", "is_inverted":False},
{"badge_name":"bunker","code":"BUNKER", "file_name":"https://i.imgur.com/BTVHKMb.png", "is_inverted":False},
{"badge_name":"dprk","code":"DPRK", "file_name":"https://i.imgur.com/PkmicXZ.png", "is_inverted":False},
{"badge_name":"kek","code":"KEK", "file_name": "https://i.imgur.com/SMyXZBg.png", "is_inverted":False},
{"badge_name":"q","code":"Q !ITPb.qbhqo", "file_name":"https://i.imgur.com/gQjSRpl.png", "is_inverted":True},
{"badge_name":"dhs","code":"SpaceX", "file_name":"https://i.imgur.com/ibtbEjr.png", "is_inverted":False},
{"badge_name":"unsc","code":"UNSC", "file_name": "https://i.imgur.com/OnnWRfL.png", "is_inverted":False},
{"badge_name":"Anahein Ducks","code":"ANA", "file_name": "https://i.imgur.com/cOELhhT.png", "is_inverted":False},
{"badge_name":"Arizona Coyotes","code":"ARI", "file_name": "https://i.imgur.com/IjXyvtM.png", "is_inverted":False},
{"badge_name":"Boston Bruins","code":"BOS", "file_name": "https://i.imgur.com/muRcEUm.png", "is_inverted":False},
{"badge_name":"Buffalo Sabres","code":"BUF", "file_name": "https://i.imgur.com/8RBNDzH.png", "is_inverted":False},
{"badge_name":"Calgary Flames","code":"CGY", "file_name": "https://i.imgur.com/Ps0m7ww.png", "is_inverted":False},
{"badge_name":"Carolina Hurricanes","code":"CAR", "file_name": "https://i.imgur.com/gWX73Fo.png", "is_inverted":False},
{"badge_name":"Chicago Blackhawks","code":"CHI", "file_name": "https://i.imgur.com/XBHEtej.png", "is_inverted":False},
{"badge_name":"Colorado Avalanche","code":"COL", "file_name": "https://i.imgur.com/oaZfakk.png", "is_inverted":False},
{"badge_name":"Columbus Blue Jackets","code":"CBJ", "file_name": "https://i.imgur.com/DStIvvx.png", "is_inverted":False},
{"badge_name":"Dallas Stars","code":"DAL", "file_name": "https://i.imgur.com/3ZxaXNG.png", "is_inverted":False},
{"badge_name":"Detroit Red Wings","code":"DET", "file_name":"https://i.imgur.com/c1wNMDg.png", "is_inverted":False},
{"badge_name":"Edmonton Oilers","code":"EDM", "file_name":"https://i.imgur.com/gAnvRNH.png", "is_inverted":False},
{"badge_name":"Florida Panthers","code":"FLA", "file_name": "https://i.imgur.com/D7XIS4S.png", "is_inverted":False},
{"badge_name":"Los Angeles Kings","code":"LAK", "file_name": "https://i.imgur.com/ljQJpO8.png", "is_inverted":False},
{"badge_name":"Minnesota Wild","code":"MIN", "file_name": "https://i.imgur.com/5sJiDKO.png", "is_inverted":False},
{"badge_name":"Montréal Canadiens","code":"MTL", "file_name": "https://i.imgur.com/Izikpfh.png", "is_inverted":False},
{"badge_name":"Nashville Predators","code":"NSH", "file_name": "https://i.imgur.com/acFYYjG.png", "is_inverted":False},
{"badge_name":"New Jersey Devils","code":"NJD", "file_name": "https://i.imgur.com/3iTGZ5g.png", "is_inverted":False},
{"badge_name":"New York Islanders","code":"NYI", "file_name": "https://i.imgur.com/hiFB2ol.png", "is_inverted":False},
{"badge_name":"New York Rangers","code":"NYR", "file_name": "https://i.imgur.com/sUGtyVT.png", "is_inverted":False},
{"badge_name":"Ottawa Senators","code":"OTT", "file_name": "https://i.imgur.com/eNCJ2Kw.png", "is_inverted":False},
{"badge_name":"Philadelphia Flyers","code":"PHI", "file_name": "https://i.imgur.com/X8rh7sw.png", "is_inverted":False},
{"badge_name":"Pittsburgh Penguins","code":"PIT", "file_name": "https://i.imgur.com/YXepjgK.png", "is_inverted":False},
{"badge_name":"San Jose Sharks","code":"SJS", "file_name": "https://i.imgur.com/KPlna0Y.png", "is_inverted":False},
{"badge_name":"St. Louis Blues","code":"STL", "file_name": "https://i.imgur.com/Qb7kpwc.png", "is_inverted":False},
{"badge_name":"Tampa Bay Lightning","code":"TBL", "file_name": "https://i.imgur.com/BwiKWwv.png", "is_inverted":False},
{"badge_name":"Toronto Maple Leafs","code":"TOR", "file_name": "https://i.imgur.com/MuiYOFx.png", "is_inverted":False},
{"badge_name":"Vancouver Canucks","code":"VAN", "file_name": "https://i.imgur.com/qGEH80F.png", "is_inverted":False},
{"badge_name":"Vegas Golden Knights","code":"VGK", "file_name": "https://i.imgur.com/SqUjpK7.png", "is_inverted":False},
{"badge_name":"Washington Capitals","code":"WSH", "file_name":"https://i.imgur.com/lToLSgL.png", "is_inverted":False},
{"badge_name":"Winnipeg Jets","code":"WPG", "file_name": "https://i.imgur.com/e6zr2O7.png", "is_inverted":False}]
+4
View File
@@ -0,0 +1,4 @@
from .chatter import Chatter
def setup(bot):
bot.add_cog(Chatter(bot))
+112
View File
@@ -0,0 +1,112 @@
from redbot.core import commands
from redbot.core import checks
from redbot.core import Config
import aiohttp
import discord
import chatterbot
from chatterbot.trainers import ListTrainer
import functools
import asyncio
class Chatter(getattr(commands, "Cog", object)):
"""Chatterbot"""
def __init__(self, bot):
self.bot = bot
default_guild = {"toggle": False, "channel": None}
default_channel = {"message": None, "author": None}
self.config = Config.get_conf(self, 3568777796)
self.config.register_guild(**default_guild)
self.config.register_channel(**default_channel)
self.chatbot = chatterbot.ChatBot("Redbot",
output_adapter="chatterbot.output.OutputAdapter",
storage_adapter="chatterbot.storage.MongoDatabaseAdapter",
output_format="text",
# database="data/chatterbot/db",
logic_adapters=[
"chatterbot.logic.BestMatch",
"chatterbot.logic.TimeLogicAdapter",
"chatterbot.logic.MathematicalEvaluation"]
)
self.chatbot.set_trainer(ListTrainer, show_training_progress=False)
@commands.group(no_pm=True, invoke_without_command=True, pass_context=True)
async def chatterbot(self, ctx, *, message):
"""Talk with cleverbot"""
author = ctx.message.author
channel = ctx.message.channel
response = self.chatbot.get_response(message)
await ctx.send(response)
@chatterbot.command(pass_context=True)
@checks.mod_or_permissions(manage_channels=True)
async def toggle(self, ctx):
"""Toggles reply on mention"""
guild = ctx.message.guild
cur_toggle = await self.config.guild(guild).toggle()
await self.config.guild(guild).toggle.set(not cur_toggle)
if cur_toggle:
await ctx.send("I won't reply on mention anymore.")
else:
await ctx.send("I will reply on mention.")
@chatterbot.command(pass_context=True)
@checks.mod_or_permissions(manage_channels=True)
async def channel(self, ctx, channel: discord.TextChannel=None):
"""Toggles channel for automatic replies"""
guild = ctx.message.guild
if channel is None:
await self.config.guild(guild).channel.set(channel)
else:
await self.config.guild(guild).channel.set(channel.id)
await ctx.send("I will reply in {}".format(channel.mention))
async def on_message(self, message):
guild = message.guild
channel = message.channel
author = message.author
conversation = []
if "http" in message.content or message.content == "" or author.bot:
return
last_author = await self.config.channel(channel).author()
last_message = await self.config.channel(channel).message()
if author.id == last_author and last_message != message.content:
await self.config.channel(channel).message.set(last_message + "\n" + message.content)
if author.id != last_author and author.id != self.bot.user.id and last_author is not None:
conversation.append(message.content)
conversation.append(last_message)
task = functools.partial(self.chatbot.train, conversation=conversation)
task = self.bot.loop.run_in_executor(None, task)
try:
response = await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
return
# self.chatbot.train(conversation)
await self.config.channel(channel).message.set(None)
await self.config.channel(channel).author.set(None)
if last_author is None and last_message is None:
await self.config.channel(channel).message.set(message.content)
await self.config.channel(channel).author.set(author.id)
if not await self.config.guild(guild).toggle() or message.guild is None:
return
if author.id != self.bot.user.id:
to_strip = "@" + author.guild.me.display_name + " "
text = message.clean_content
if not text.startswith(to_strip) and message.channel.id != await self.config.guild(guild).channel():
return
text = text.replace(to_strip, "", 1)
text = text.replace("@everyone ", "")
text = text.replace("@here", "")
async with message.channel.typing():
task = functools.partial(self.chatbot.get_response, input_item=text)
task = self.bot.loop.run_in_executor(None, task)
try:
response = await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
return
await message.channel.send(response)
+21
View File
@@ -0,0 +1,21 @@
{
"author":[
"TrustyJAID"
],
"description":"Talk to your bot and build a unique dataset for conversations!",
"install_msg":"Talk to your bot and have it learn how to talk in conversations! Recommended you unload the cleverbot cog before running.",
"min_python_version":[
3,
6,
2
],
"name":"Chatterbot",
"permissions":[],
"requirements":[
"chatterbot"
],
"short":"chatterbot",
"tags":[
"general"
]
}
+5
View File
@@ -0,0 +1,5 @@
from .cleverbot import Cleverbot
def setup(bot):
cog = Cleverbot(bot)
bot.add_cog(cog)
+221
View File
@@ -0,0 +1,221 @@
from redbot.core import commands
from redbot.core import checks
from redbot.core import Config
import os
import aiohttp
import discord
API_URL = "https://www.cleverbot.com/getreply"
IO_API_URL = "https://cleverbot.io/1.0"
class CleverbotError(Exception):
pass
class NoCredentials(CleverbotError):
pass
class InvalidCredentials(CleverbotError):
pass
class APIError(CleverbotError):
pass
class OutOfRequests(CleverbotError):
pass
class OutdatedCredentials(CleverbotError):
pass
class Cleverbot(getattr(commands, "Cog", object)):
"""Cleverbot rewritten for V3 from https://github.com/Twentysix26/26-Cogs/tree/master/cleverbot"""
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 127486454786)
default_global = {"api":None, "io_user":None, "io_key":None}
default_guild = {"channel":None, "toggle":False}
self.config.register_global(**default_global)
self.config.register_guild(**default_guild)
self.session = aiohttp.ClientSession(loop=self.bot.loop)
self.instances = {}
@commands.group(no_pm=True, invoke_without_command=True)
async def cleverbot(self, ctx, *, message):
"""Talk with cleverbot"""
author = ctx.message.author
channel = ctx.message.channel
async with channel.typing():
try:
result = await self.get_response(author, message)
except NoCredentials:
await ctx.send("The owner needs to set the credentials first.\n"
"See: `[p]cleverbot apikey` or `[p]cleverbot ioapikey`")
except APIError as e:
await ctx.send("Error contacting the API. Error code: {}".format(e))
except InvalidCredentials:
await ctx.send("The token that has been set is not valid.\n"
"See: `[p]cleverbot apikey`")
except OutOfRequests:
await ctx.send("You have ran out of requests for this month. "
"The free tier has a 5000 requests a month limit.")
except OutdatedCredentials:
await ctx.send("You need a valid cleverbot.com api key for this to "
"work. The old cleverbot.io service will soon be no "
"longer active. See `[p]help cleverbot apikey`")
else:
await ctx.send(result)
@cleverbot.command(pass_context=True)
@checks.mod_or_permissions(manage_channels=True)
async def toggle(self, ctx):
"""Toggles reply on mention"""
guild = ctx.message.guild
if not await self.config.guild(guild).toggle():
await self.config.guild(guild).toggle.set(True)
await ctx.send("I will reply on mention.")
else:
await self.config.guild(guild).toggle.set(False)
await ctx.send("I won't reply on mention anymore.")
@cleverbot.command(pass_context=True)
@checks.mod_or_permissions(manage_channels=True)
async def channel(self, ctx, channel: discord.TextChannel=None):
"""Toggles channel for automatic replies"""
guild = ctx.message.guild
if channel is None:
channel = ctx.message.channel
await self.config.guild(guild).channel.set(channel.id)
await ctx.send("I will reply in {}".format(channel))
@cleverbot.command()
@checks.is_owner()
async def apikey(self, ctx, key: str=None):
"""Sets token to be used with cleverbot.com
You can get it from https://www.cleverbot.com/api/
Use this command in direct message to keep your
token secret"""
await self.config.api.set(key)
await ctx.send("Credentials set.")
@cleverbot.command()
@checks.is_owner()
async def ioapikey(self, ctx, io_user: str=None, io_key: str=None):
"""Sets token to be used with cleverbot.io
You can get it from https://www.cleverbot.io/
Use this command in direct message to keep your
token secret"""
await self.config.io_user.set(io_user)
await self.config.io_key.set(io_key)
await ctx.send("Credentials set.")
async def get_response(self, author, text):
payload = {}
try:
payload["key"] = await self.get_credentials()
payload["cs"] = self.instances.get(str(author.id), "")
payload["input"] = text
return await self.get_cleverbotcom_response(payload, author)
except NoCredentials:
guild = author.guild
if guild is None:
return
payload["user"], payload["key"] = await self.get_io_credentials()
payload["nick"] = str("{}#{}".format(guild.me.name, guild.me.discriminator))
return await self.get_cleverbotio_response(payload, text)
async def make_cleverbotio_instance(self, payload):
"""Makes the cleverbot.io instance if one isn't created for the user"""
del payload["text"]
async with self.session.post(IO_API_URL+"/create", json=payload) as r:
if r.status == 200:
return
elif r.status == 400:
raise InvalidCredentials()
else:
raise APIError("Error making instance: " + str(r.status))
async def get_cleverbotio_response(self, payload, text):
payload["text"] = text
async with self.session.post(IO_API_URL+"/ask/", json=payload) as r:
if r.status == 200:
data = await r.json()
elif r.status == 400:
# Try to make the instance for the user first before raising the error
await self. make_cleverbotio_instance(payload)
return await self.get_cleverbotio_response(payload, text)
else:
raise APIError("Error getting response: " + str(r.status))
return data["response"]
async def get_cleverbotcom_response(self, payload, author):
async with self.session.get(API_URL, params=payload) as r:
# print(r.status)
if r.status == 200:
data = await r.json()
self.instances[str(author.id)] = data["cs"] # Preserves conversation status
elif r.status == 401:
raise InvalidCredentials()
elif r.status == 503:
raise OutOfRequests()
else:
raise APIError(str(r.status))
return data["output"]
async def get_credentials(self):
key = await self.config.api()
if key is None:
raise NoCredentials()
else:
return key
async def get_io_credentials(self):
io_key = await self.config.io_key()
io_user = await self.config.io_user()
if io_key is None:
raise NoCredentials()
else:
return io_user, io_key
async def on_message(self, message):
if not hasattr(message, "guild"):
return
guild = message.guild
if guild is None:
return
author = message.author
channel = message.channel
if message.author.id != self.bot.user.id:
to_strip = "@" + guild.me.display_name + " "
text = message.clean_content
if not text.startswith(to_strip) and message.channel.id != await self.config.guild(guild).channel():
return
if not await self.config.guild(guild).toggle():
return
async with channel.typing():
try:
response = await self.get_response(author, text)
except NoCredentials:
await channel.send("The owner needs to set the credentials first.\n"
"See: `[p]cleverbot apikey`")
except APIError as e:
await ctx.send("Error contacting the API. Error code: {}".format(e))
except InvalidCredentials:
await channel.send("The token that has been set is not valid.\n"
"See: `[p]cleverbot apikey`")
except OutOfRequests:
await channel.send("You have ran out of requests for this month. "
"The free tier has a 5000 requests a month limit.")
except OutdatedCredentials:
await channel.send("You need a valid cleverbot.com api key for this to "
"work. The old cleverbot.io service will soon be no "
"longer active. See `[p]help cleverbot apikey`")
else:
await channel.send(response)
def __unload(self):
if self.session:
self.bot.loop.create_task(self.session.close())
+22
View File
@@ -0,0 +1,22 @@
{
"author":[
"Twentysix",
"TrustyJAID"
],
"description":"Allows for interaction with cleverbot.com through mention/command",
"install_msg":"Needs to be setup with an API key first. See `[p]cleverbot apikey`\n[p]cleverbot <text>` to talk with cleverbot.\n`@Mention <text>` works too.\n`[p]cleverbot toggle` disables replies by mention.",
"min_python_version":[
3,
6,
2
],
"name":"Cleverbot",
"permissions":[],
"requirements":[],
"short":"Talk with Cleverbot!",
"tags":[
"chatbot",
"cleverbot",
"conversation"
]
}
+5
View File
@@ -0,0 +1,5 @@
from .compliment import Compliment
def setup(bot):
n = Compliment(bot)
bot.add_cog(n)
+33
View File
@@ -0,0 +1,33 @@
import discord
from redbot.core import commands
from random import choice
import os
from .compliments import compliments
class Compliment(getattr(commands, "Cog", object)):
"""Airenkun's Insult Cog"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def compliment(self, ctx, user : discord.Member=None):
"""
Compliment the user
`user` the user you would like to compliment
"""
msg = ' '
if user != None:
if user.id == self.bot.user.id:
user = ctx.message.author
msg = [" Hey, I appreciate the compliment! :smile:", "No ***YOU'RE*** awesome! :smile:"]
await ctx.send(user.mention + choice(msg))
else:
await ctx.send(user.mention + msg + choice(compliments))
else:
await ctx.send(ctx.message.author.mention + msg + choice(compliments))
+99
View File
@@ -0,0 +1,99 @@
compliments = ["Your smile is contagious.",
"You look great today.",
"You're a smart cookie.",
"I bet you make babies smile.",
"You have impeccable manners.",
"I like your style.",
"You have the best laugh.",
"I appreciate you.",
"You are the most perfect you there is.",
"You are enough.",
"You're strong.",
"Your perspective is refreshing.",
"You're an awesome friend.",
"You light up the room.",
"You deserve a hug right now.",
"You should be proud of yourself.",
"You're more helpful than you realize.",
"You have a great sense of humor.",
"You've got all the right moves!",
"Is that your picture next to \"charming\" in the dictionary?",
"Your kindness is a balm to all who encounter it.",
"You're all that and a super-size bag of chips.",
"On a scale from 1 to 10, you're an 11.",
"You are brave.",
"You're even more beautiful on the inside than you are on the outside.",
"You have the courage of your convictions.",
"Your eyes are breathtaking.",
"If cartoon bluebirds were real, a bunch of them would be sitting on your shoulders singing right now.",
"You are making a difference.",
"You're like sunshine on a rainy day.",
"You bring out the best in other people.",
"Your ability to recall random factoids at just the right time is impressive.",
"You're a great listener.",
"How is it that you always look great, even in sweatpants?",
"Everything would be better if more people were like you!",
"I bet you sweat glitter.",
"You were cool way before hipsters were cool.",
"That color is perfect on you.",
"Hanging out with you is always a blast.",
"You always know -- and say -- exactly what I need to hear when I need to hear it.",
"You smell really good.",
"You may dance like no one's watching, but everyone's watching because you're an amazing dancer!",
"Being around you makes everything better!",
"When you say, \"I meant to do that,\" I totally believe you.",
"When you're not afraid to be yourself is when you're most incredible.",
"Colors seem brighter when you're around.",
"You're more fun than a ball pit filled with candy. (And seriously, what could be more fun than that?)",
"That thing you don't like about yourself is what makes you so interesting.",
"You're wonderful.",
"You have cute elbows. For reals! (You're halfway through the list. Don't stop now! You should be giving at least one awesome compliment every day!)",
"Jokes are funnier when you tell them.",
"You're better than a triple-scoop ice cream cone. With sprinkles.",
"Your hair looks stunning.",
"You're one of a kind!",
"You're inspiring.",
"If you were a box of crayons, you'd be the giant name-brand one with the built-in sharpener.",
"You should be thanked more often. So thank you!!",
"Our community is better because you're in it.",
"Someone is getting through something hard right now because you've got their back.",
"You have the best ideas.",
"You always know how to find that silver lining.",
"Everyone gets knocked down sometimes, but you always get back up and keep going.",
"You're a candle in the darkness.",
"You're a great example to others.",
"Being around you is like being on a happy little vacation.",
"You always know just what to say.",
"You're always learning new things and trying to better yourself, which is awesome.",
"If someone based an Internet meme on you, it would have impeccable grammar.",
"You could survive a Zombie apocalypse.",
"You're more fun than bubble wrap.",
"When you make a mistake, you fix it.",
"Who raised you? They deserve a medal for a job well done.",
"You're great at figuring stuff out.",
"Your voice is magnificent.",
"The people you love are lucky to have you in their lives.",
"You're like a breath of fresh air.",
"You're gorgeous -- and that's the least interesting thing about you, too.",
"You're so thoughtful.",
"Your creative potential seems limitless.",
"Your name suits you to a T.",
"You're irresistible when you blush.",
"Actions speak louder than words, and yours tell an incredible story.",
"Somehow you make time stop and fly at the same time.",
"When you make up your mind about something, nothing stands in your way.",
"You seem to really know who you are.",
"Any team would be lucky to have you on it.",
"In high school I bet you were voted \"most likely to keep being awesome.\"",
"I bet you do the crossword puzzle in ink.",
"Babies and small animals probably love you.",
"If you were a scented candle they'd call it Perfectly Imperfect (and it would smell like summer).",
"There's ordinary, and then there's you.",
"You're someone's reason to smile.",
"You're even better than a unicorn, because you're real.",
"How do you keep being so funny and making everyone laugh?",
"You have a good head on your shoulders.",
"Has anyone ever told you that you have great posture?",
"The way you treasure your loved ones is incredible.",
"You're really something special.",
"You're a gift to those around you."]
+22
View File
@@ -0,0 +1,22 @@
{
"author":[
"Airen",
"JennJenn",
"TrustyJAID"
],
"description":"Compliment people in a creative way",
"install_msg":"Usage: `[p]compliment <user>`",
"min_python_version":[
3,
6,
2
],
"name":"Compliment",
"permissions":[],
"requirements":[],
"short":"Compliment people in a creative way",
"tags":[
"compliments",
"fun"
]
}
+6
View File
@@ -0,0 +1,6 @@
from .conversions import Conversions
def setup(bot):
n = Conversions(bot)
bot.add_cog(n)
+353
View File
@@ -0,0 +1,353 @@
import discord
from redbot.core import commands
import datetime
import aiohttp
import asyncio
import json
import re
class Conversions(getattr(commands, "Cog", object)):
"""
Gather information about various crypto currencies,
rare metals, stocks, and converts to different currencies
"""
def __init__(self, bot):
self.bot = bot
self.session = aiohttp.ClientSession(loop=self.bot.loop)
@commands.command(pass_context=True, aliases=["bitcoin", "BTC"])
async def btc(self, ctx, ammount:float=1.0, currency="USD", full=True):
"""
converts from BTC to a given currency.
`amount` is any number to convert the value of defaults to 1 coin
`currency` is the desired currency you want to convert defaults to USD
`full` is a True/False value whether to display just the converted amount
or the full display for the currency
"""
if ammount == 1.0:
embed = await self.crypto_embed(ctx, "BTC", ammount, currency, full)
else:
embed = await self.crypto_embed(ctx, "BTC", ammount, currency, False)
if type(embed) is str:
await ctx.send(embed)
else:
await ctx.send(embed=embed)
@commands.command(pass_context=True, aliases=["ethereum", "ETH"])
async def eth(self, ctx, ammount:float=1.0, currency="USD", full=True):
"""
converts from ETH to a given currency.
`amount` is any number to convert the value of defaults to 1 coin
`currency` is the desired currency you want to convert defaults to USD
`full` is a True/False value whether to display just the converted amount
or the full display for the currency
"""
if ammount == 1.0:
embed = await self.crypto_embed(ctx, "ETH", ammount, currency, full)
else:
embed = await self.crypto_embed(ctx, "ETH", ammount, currency, False)
if type(embed) is str:
await ctx.send(embed)
else:
await ctx.send(embed=embed)
@commands.command(pass_context=True, aliases=["litecoin", "LTC"])
async def ltc(self, ctx, ammount:float=1.0, currency="USD", full=True):
"""
converts from LTC to a given currency.
`amount` is any number to convert the value of defaults to 1 coin
`currency` is the desired currency you want to convert defaults to USD
`full` is a True/False value whether to display just the converted amount
or the full display for the currency
"""
if ammount == 1.0:
embed = await self.crypto_embed(ctx, "LTC", ammount, currency, full)
else:
embed = await self.crypto_embed(ctx, "LTC", ammount, currency, False)
if type(embed) is str:
await ctx.send(embed)
else:
await ctx.send(embed=embed)
@commands.command(pass_context=True, aliases=["monero", "XMR"])
async def xmr(self, ctx, ammount:float=1.0, currency="USD", full=True):
"""
converts from LTC to a given currency.
`amount` is any number to convert the value of defaults to 1 coin
`currency` is the desired currency you want to convert defaults to USD
`full` is a True/False value whether to display just the converted amount
or the full display for the currency
"""
if ammount == 1.0:
embed = await self.crypto_embed(ctx, "XMR", ammount, currency, full)
else:
embed = await self.crypto_embed(ctx, "XMR", ammount, currency, False)
if type(embed) is str:
await ctx.send(embed)
else:
await ctx.send(embed=embed)
@commands.command(pass_context=True, aliases=["bitcoin-cash", "BCH"])
async def bch(self, ctx, ammount:float=1.0, currency="USD", full=True):
"""
converts from LTC to a given currency.
`amount` is any number to convert the value of defaults to 1 coin
`currency` is the desired currency you want to convert defaults to USD
`full` is a True/False value whether to display just the converted amount
or the full display for the currency
"""
if ammount == 1.0:
embed = await self.crypto_embed(ctx, "BCH", ammount, currency, full)
else:
embed = await self.crypto_embed(ctx, "BCH", ammount, currency, False)
if type(embed) is str:
await ctx.send(embed)
else:
await ctx.send(embed=embed)
async def checkcoins(self, base):
link = "https://api.coinmarketcap.com/v2/ticker/"
async with self.session.get(link) as resp:
data = await resp.json()
for coin in data["data"]:
if base.upper() == data["data"][coin]["symbol"].upper() or base.lower() == data["data"][coin]["name"].lower():
return data["data"][coin]
return None
@commands.command(pass_context=True)
async def multicoin(self, ctx, *, coins=None):
"""
Gets the current USD value for a list of coins
`coins` must be a list of white space separated crypto coins
e.g. `[p]multicoin BTC BCH LTC ETH DASH XRP`
"""
coin_list = []
if coins is None:
async with self.session.get("https://api.coinmarketcap.com/v2/ticker/") as resp:
data = await resp.json()
for coin in data["data"]:
coin_list.append(data["data"][coin])
else:
coins = re.split("\W+", coins)
for coin in coins:
coin_list.append(await self.checkcoins(coin))
embed = discord.Embed(title="Crypto coin comparison")
if ctx.channel.permissions_for(ctx.me).embed_links:
for coin in coin_list[:25]:
if coin is not None:
msg = "1 {0} is {1:,.2f} USD".format(coin["symbol"], float(coin["quotes"]["USD"]["price"]))
embed.add_field(name=coin["name"], value=msg)
await ctx.send(embed=embed)
else:
msg = ""
for coin in coin_list[:25]:
if coin is not None:
msg += "1 {0} is {1:,.2f} USD\n".format(coin["symbol"], float(coin["quotes"]["USD"]["price"]))
await ctx.send(msg)
@commands.command(pass_context=True)
async def crypto(self, ctx, coin, ammount:float=1.0, currency="USD", full=True):
"""
Displays the latest information about a specified crypto currency
`coin` must be the name or symbol of a crypto coin
`amount` is any number to convert the value of defaults to 1 coin
`currency` is the desired currency you want to convert defaults to USD
`full` is a True/False value whether to display just the converted amount
or the full display for the currency
"""
if ammount == 1.0:
embed = await self.crypto_embed(ctx, coin, ammount, currency, full)
else:
embed = await self.crypto_embed(ctx, coin, ammount, currency, False)
if type(embed) is str:
await ctx.send(embed)
else:
await ctx.send(embed=embed)
async def crypto_embed(self, ctx, coin, ammount=1.0, currency="USD", full=True):
"""Creates the embed for the crypto currency"""
coin_data = await self.checkcoins(coin)
if coin_data is None:
await ctx.send("{} is not in my list of currencies!".format(coin))
return
coin_colour = {"Bitcoin": discord.Colour.gold(),
"Bitcoin Cash": discord.Colour.orange(),
"Ethereum": discord.Colour.dark_grey(),
"Litecoin": discord.Colour.dark_grey(),
"Monero": discord.Colour.orange()}
price = float(coin_data["quotes"]["USD"]["price"]) * ammount
market_cap = float(coin_data["quotes"]["USD"]["market_cap"])
volume_24h = float(coin_data["quotes"]["USD"]["volume_24h"])
coin_image = "https://s2.coinmarketcap.com/static/img/coins/128x128/{}.png".format(coin_data["id"])
coin_url = "https://coinmarketcap.com/currencies/{}".format(coin_data["id"])
if currency.upper() != "USD":
conversionrate = await self.conversionrate("USD", currency.upper())
price = conversionrate * price
market_cap = conversionrate * market_cap
volume_24h = conversionrate * volume_24h
msg = "{0} {3} is **{1:,.2f} {2}**".format(ammount, price, currency.upper(), coin_data["symbol"])
embed = discord.Embed(description=msg, colour=discord.Colour.dark_grey())
if coin_data["name"] in coin_colour:
embed.colour = coin_colour[coin_data["name"]]
embed.set_footer(text="As of")
embed.set_author(name=coin_data["name"], url=coin_url, icon_url=coin_image)
embed.timestamp = datetime.datetime.utcfromtimestamp(int(coin_data["last_updated"]))
if full:
hour_1 = coin_data["quotes"]["USD"]["percent_change_1h"]
hour_24 = coin_data["quotes"]["USD"]["percent_change_24h"]
days_7 = coin_data["quotes"]["USD"]["percent_change_7d"]
hour_1_emoji = "🔼" if hour_1 >= 0 else "🔽"
hour_24_emoji = "🔼" if hour_24 >= 0 else "🔽"
days_7_emoji = "🔼" if days_7 >= 0 else "🔽"
available_supply = "{0:,.2f}".format(coin_data["circulating_supply"])
max_supply = "{0:,.2f}".format(coin_data["max_supply"]) if "max_supply" in coin_data else None
total_supply = "{0:,.2f}".format(coin_data["total_supply"])
embed.set_thumbnail(url=coin_image)
embed.add_field(name="Market Cap", value="{0:,.2f} {1}".format(market_cap, currency.upper()))
embed.add_field(name="24 Hour Volume", value="{0:,.2f} {1}".format(volume_24h, currency.upper()))
embed.add_field(name="Available Supply", value=available_supply)
if max_supply is not None:
embed.add_field(name="Max Supply", value=max_supply)
embed.add_field(name="Total Supply ", value=total_supply)
embed.add_field(name="Change 1 hour " + hour_1_emoji, value="{}%".format(hour_1))
embed.add_field(name="Change 24 hours " + hour_24_emoji, value="{}%".format(hour_24))
embed.add_field(name="Change 7 days " +days_7_emoji, value="{}%".format(days_7))
if not ctx.channel.permissions_for(ctx.me).embed_links:
if full:
return (f"{msg}\nMarket Cap: **{market_cap}**\n"
f"24 Hour Volume: **{volume_24h}**\nAvailable Supply: **{available_supply}**\n"
f"Max Supply: **{max_supply}**\nTotal Supply: **{total_supply}**\n"
f"Change 1 hour{hour_1_emoji}: **{hour_1}%**\n"
f"Change 24 hours{hour_24_emoji}: **{hour_24}%**\n"
f"Change 7 days{days_7_emoji}: **{days_7}%**\n")
else:
return msg
else:
return embed
@commands.command()
async def gold(self, ctx, ammount=1, currency="USD"):
"""
Converts gold in ounces to a given currency.
`ammount` must be a number of ounces to convert defaults to 1 ounce
`currency` must be a valid currency defaults to USD
"""
GOLD = "https://www.quandl.com/api/v3/datasets/WGC/GOLD_DAILY_{}.json?api_key=EKvr5W-sJUFVSevcpk4v"
async with self.session.get(GOLD.format(currency.upper())) as resp:
data = await resp.json()
price = (data["dataset"]["data"][0][1]) * ammount
msg = "{0} oz of Gold is {1:,.2f} {2}".format(ammount, price, currency.upper())
embed = discord.Embed(descirption="Gold", colour=discord.Colour.gold())
embed.add_field(name="Gold", value=msg)
embed.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/d/d7/Gold-crystals.jpg")
if not ctx.channel.permissions_for(ctx.me).embed_links:
await ctx.send(msg)
else:
await ctx.send(embed=embed)
@commands.command()
async def silver(self, ctx, ammount=1, currency="USD"):
"""
Converts silver in ounces to a given currency.
`ammount` must be a number of ounces to convert defaults to 1 ounce
`currency` must be a valid currency defaults to USD
"""
SILVER = "https://www.quandl.com/api/v3/datasets/LBMA/SILVER.json?api_key=EKvr5W-sJUFVSevcpk4v"
async with self.session.get(SILVER) as resp:
data = await resp.json()
price = (data["dataset"]["data"][0][1]) * ammount
if currency != "USD":
price = await self.conversionrate("USD", currency.upper()) * price
msg = "{0} oz of Silver is {1:,.2f} {2}".format(ammount, price, currency.upper())
embed = discord.Embed(descirption="Silver", colour=discord.Colour.lighter_grey())
embed.add_field(name="Silver", value=msg)
embed.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/5/55/Silver_crystal.jpg")
if not ctx.channel.permissions_for(ctx.me).embed_links:
await ctx.send(msg)
else:
await ctx.send(embed=embed)
@commands.command()
async def platinum(self, ctx, ammount=1, currency="USD"):
"""
Converts platinum in ounces to a given currency.
`ammount` must be a number of ounces to convert defaults to 1 ounce
`currency` must be a valid currency defaults to USD
"""
PLATINUM = "https://www.quandl.com/api/v3/datasets/JOHNMATT/PLAT.json?api_key=EKvr5W-sJUFVSevcpk4v"
async with self.session.get(PLATINUM) as resp:
data = await resp.json()
price = (data["dataset"]["data"][0][1]) * ammount
if currency != "USD":
price = await self.conversionrate("USD", currency.upper()) * price
msg = "{0} oz of Platinum is {1:,.2f} {2}".format(ammount, price, currency.upper())
embed = discord.Embed(descirption="Platinum", colour=discord.Colour.dark_grey())
embed.add_field(name="Platinum", value=msg)
embed.set_thumbnail(url="https://upload.wikimedia.org/wikipedia/commons/6/68/Platinum_crystals.jpg")
if not ctx.channel.permissions_for(ctx.me).embed_links:
await ctx.send(msg)
else:
await ctx.send(embed=embed)
@commands.command(pass_context=True, aliases=["ticker"])
async def stock(self, ctx, ticker, currency="USD"):
"""
Gets current ticker symbol price.
`ticker` is the ticker symbol you want to look up
`currency` is the currency you want to convert to defaults to USD
"""
stock = "https://www.quandl.com/api/v3/datasets/WIKI/{}.json?api_key=EKvr5W-sJUFVSevcpk4v"
async with self.session.get(stock.format(ticker.upper())) as resp:
data = await resp.json()
convertrate = 1
if currency != "USD":
convertrate = self.conversionrate("USD", currency.upper())
price = (data["dataset"]["data"][0][1]) * convertrate
msg = "{0} is {1:,.2f} {2}".format(ticker.upper(), price, currency.upper())
embed = discord.Embed(descirption="Stock Price", colour=discord.Colour.lighter_grey())
embed.add_field(name=ticker.upper(), value=msg)
if not ctx.channel.permissions_for(ctx.me).embed_links:
await ctx.send(msg)
else:
await ctx.send(embed=embed)
@commands.command(pass_context=True)
async def convert(self, ctx, ammount:float=1.0, currency1="USD", currency2="GBP"):
"""
Converts a value between 2 different currencies
`ammount` is the ammount you want to convert default is 1
`currency1` is the currency you have default is USD
`currency2` is the currency you want to convert to default is GBP
"""
conversion = await self.conversionrate(currency1.upper(), currency2.upper())
conversion = conversion * ammount
await ctx.send("{0} {1} is {2:,.2f} {3}".format(ammount, currency1, conversion, currency2))
async def conversionrate(self, currency1, currency2):
"""Function to convert different currencies"""
CONVERSIONRATES = "https://free.currencyconverterapi.com/api/v6/convert?q={}_{}&compact=ultra".format(currency1.upper(), currency2.upper())
try:
async with self.session.get(CONVERSIONRATES) as resp:
data = await resp.json()
conversion = data["{}_{}".format(currency1.upper(), currency2.upper())]
return conversion
except:
return None
"""TODO: add feeder cattle, coffee, and sugar"""
def __unload(self):
self.bot.loop.create_task(self.session.close())
+24
View File
@@ -0,0 +1,24 @@
{
"author":[
"TrustyJAID"
],
"description":"Conversions for BTC, currencies, precious metals, and stocks.",
"install_msg":"Various commands.",
"min_python_version":[
3,
6,
2
],
"name":"Conversions",
"permissions":[
"embed_links"
],
"requirements":[],
"short":"Conversions",
"tags":[
"general",
"utility",
"bitcoin",
"litecoin"
]
}
+4
View File
@@ -0,0 +1,4 @@
from .covfefe import Covfefe
def setup(bot):
bot.add_cog(Covfefe(bot))
+29
View File
@@ -0,0 +1,29 @@
import discord
from redbot.core import commands
import re
class Covfefe(getattr(commands, "Cog", object)):
"""
Convert almost any word into covfefe
"""
def __init__(self, bot):
self.bot = bot
async def covfefe(self, x, k='aeiouy])'):
"""
https://codegolf.stackexchange.com/a/123697
"""
try:
b,c,v=re.findall(f'(.*?[{k}([^{k}.*?([{k}',x)[0];return b+c+(('bcdfgkpstvz'+c)['pgtvkgbzdfs'.find(c)]+v)*2
except:
return None
@commands.command()
async def covefy(self, ctx, msg):
"""Convert almost any word into covfefe"""
newword = await self.covfefe(msg)
if newword is not None:
await ctx.send(newword)
else:
await ctx.send("I cannot covfefeify that word")
+20
View File
@@ -0,0 +1,20 @@
{
"author":[
"TrustyJAID"
],
"description":"Covfefeify almost any word!",
"install_msg":"Use [p]covefy <word> to convert almost any word into covfefe",
"min_python_version":[
3,
6,
2
],
"name":"Covfefe",
"permissions":[],
"requirements":[],
"short":"General commands",
"tags":[
"general",
"fun"
]
}
+4
View File
@@ -0,0 +1,4 @@
from .dev import Dev
def setup(bot):
bot.add_cog(Dev(bot))
+316
View File
@@ -0,0 +1,316 @@
import asyncio
import inspect
import io
import textwrap
import traceback
import re
from contextlib import redirect_stdout
from copy import copy
import discord
from redbot.core import checks, commands
from redbot.core.i18n import Translator
from redbot.core.utils.chat_formatting import box, pagify
"""
Notice:
95% of the below code came from R.Danny which can be found here:
https://github.com/Rapptz/RoboDanny/blob/master/cogs/repl.py
"""
_ = Translator("Dev", __file__)
START_CODE_BLOCK_RE = re.compile(r"^((```py)(?=\s)|(```))")
class Dev(getattr(commands, "Cog", object)):
"""Various development focused utilities."""
def __init__(self, bot):
super().__init__()
self.bot = bot
self._last_result = None
self.sessions = set()
@staticmethod
def cleanup_code(content):
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith("```") and content.endswith("```"):
return START_CODE_BLOCK_RE.sub("", content)[:-3]
# remove `foo`
return content.strip("` \n")
@staticmethod
def get_syntax_error(e):
"""Format a syntax error to send to the user.
Returns a string representation of the error formatted as a codeblock.
"""
if e.text is None:
return box("{0.__class__.__name__}: {0}".format(e), lang="py")
return box("{0.text}{1:>{0.offset}}\n{2}: {0}".format(e, "^", type(e).__name__), lang="py")
@staticmethod
def get_pages(msg: str):
"""Pagify the given message for output to the user."""
return pagify(msg, delims=["\n", " "], priority=True, shorten_by=10)
@staticmethod
def sanitize_output(ctx: commands.Context, input_: str) -> str:
"""Hides the bot's token from a string."""
token = ctx.bot.http.token
r = "[EXPUNGED]"
result = input_.replace(token, r)
result = result.replace(token.lower(), r)
result = result.replace(token.upper(), r)
return result
@commands.command()
@checks.is_owner()
async def debug(self, ctx, *, code):
"""Evaluate a statement of python code.
The bot will always respond with the return value of the code.
If the return value of the code is a coroutine, it will be awaited,
and the result of that will be the bot's response.
Note: Only one statement may be evaluated. Using await, yield or
similar restricted keywords will result in a syntax error. For multiple
lines or asynchronous code, see [p]repl or [p]eval.
Environment Variables:
ctx - command invokation context
bot - bot object
channel - the current channel object
author - command author's member object
message - the command's message object
discord - discord.py library
commands - redbot.core.commands
_ - The result of the last dev command.
"""
env = {
"bot": ctx.bot,
"ctx": ctx,
"channel": ctx.channel,
"author": ctx.author,
"guild": ctx.guild,
"message": ctx.message,
"discord": discord,
"commands": commands,
"_": self._last_result,
}
code = self.cleanup_code(code)
try:
result = eval(code, env)
except SyntaxError as e:
await ctx.send(self.get_syntax_error(e))
return
except Exception as e:
await ctx.send(box("{}: {!s}".format(type(e).__name__, e), lang="py"))
return
if asyncio.iscoroutine(result):
result = await result
self._last_result = result
result = self.sanitize_output(ctx, str(result))
await ctx.send_interactive(self.get_pages(result), box_lang="py")
@commands.command(name="eval")
@checks.is_owner()
async def _eval(self, ctx, *, body: str):
"""Execute asynchronous code.
This command wraps code into the body of an async function and then
calls and awaits it. The bot will respond with anything printed to
stdout, as well as the return value of the function.
The code can be within a codeblock, inline code or neither, as long
as they are not mixed and they are formatted correctly.
Environment Variables:
ctx - command invokation context
bot - bot object
channel - the current channel object
author - command author's member object
message - the command's message object
discord - discord.py library
commands - redbot.core.commands
_ - The result of the last dev command.
"""
env = {
"bot": ctx.bot,
"ctx": ctx,
"channel": ctx.channel,
"author": ctx.author,
"guild": ctx.guild,
"message": ctx.message,
"discord": discord,
"commands": commands,
"_": self._last_result,
}
body = self.cleanup_code(body)
stdout = io.StringIO()
to_compile = "async def func():\n%s" % textwrap.indent(body, " ")
try:
exec(to_compile, env)
except SyntaxError as e:
return await ctx.send(self.get_syntax_error(e))
func = env["func"]
result = None
try:
with redirect_stdout(stdout):
result = await func()
except:
printed = "{}{}".format(stdout.getvalue(), traceback.format_exc())
else:
printed = stdout.getvalue()
await ctx.tick()
if result is not None:
self._last_result = result
msg = "{}{}".format(printed, result)
else:
msg = printed
msg = self.sanitize_output(ctx, msg)
await ctx.send_interactive(self.get_pages(msg), box_lang="py")
@commands.command()
@checks.is_owner()
async def repl(self, ctx):
"""Open an interactive REPL.
The REPL will only recognise code as messages which start with a
backtick. This includes codeblocks, and as such multiple lines can be
evaluated.
You may not await any code in this REPL unless you define it inside an
async function.
"""
variables = {
"ctx": ctx,
"bot": ctx.bot,
"message": ctx.message,
"guild": ctx.guild,
"channel": ctx.channel,
"author": ctx.author,
"_": None,
}
if ctx.channel.id in self.sessions:
await ctx.send(
_("Already running a REPL session in this channel. Exit it with `quit`.")
)
return
self.sessions.add(ctx.channel.id)
await ctx.send(_("Enter code to execute or evaluate. `exit()` or `quit` to exit."))
msg_check = lambda m: (
m.author == ctx.author and m.channel == ctx.channel and m.content.startswith("`")
)
while True:
response = await ctx.bot.wait_for("message", check=msg_check)
cleaned = self.cleanup_code(response.content)
if cleaned in ("quit", "exit", "exit()"):
await ctx.send("Exiting.")
self.sessions.remove(ctx.channel.id)
return
executor = exec
if cleaned.count("\n") == 0:
# single statement, potentially 'eval'
try:
code = compile(cleaned, "<repl session>", "eval")
except SyntaxError:
pass
else:
executor = eval
if executor is exec:
try:
code = compile(cleaned, "<repl session>", "exec")
except SyntaxError as e:
await ctx.send(self.get_syntax_error(e))
continue
variables["message"] = response
stdout = io.StringIO()
msg = ""
try:
with redirect_stdout(stdout):
result = executor(code, variables)
if inspect.isawaitable(result):
result = await result
except:
value = stdout.getvalue()
msg = "{}{}".format(value, traceback.format_exc())
else:
value = stdout.getvalue()
if result is not None:
msg = "{}{}".format(value, result)
variables["_"] = result
elif value:
msg = "{}".format(value)
msg = self.sanitize_output(ctx, msg)
try:
await ctx.send_interactive(self.get_pages(msg), box_lang="py")
except discord.Forbidden:
pass
except discord.HTTPException as e:
await ctx.send(_("Unexpected error: `{}`").format(e))
@commands.command()
@checks.is_owner()
async def sudo(self, ctx, user: discord.Member, *, command):
"""Mock another user invoking a command.
The prefix must not be entered.
"""
msg = copy(ctx.message)
msg.author = user
msg.content = ctx.prefix + command
ctx.bot.dispatch("message", msg)
@commands.command(name="sudomsg")
@checks.is_owner()
async def mock_msg(self, ctx, user: discord.Member, *, content: str):
"""Dispatch a message event as if it were sent by a different user.
Only reads the raw content of the message. Attachments, embeds etc. are
ignored.
"""
old_author = ctx.author
old_content = ctx.message.content
ctx.message.author = user
ctx.message.content = content
ctx.bot.dispatch("message", ctx.message)
# If we change the author and content back too quickly,
# the bot won't process the mocked message in time.
await asyncio.sleep(2)
ctx.message.author = old_author
ctx.message.content = old_content
+21
View File
@@ -0,0 +1,21 @@
{
"author":[
"R.Danny",
"Toby",
"Will",
"Michael",
"Eslyium"
],
"description":"Cog loadable dev commands, replaces mock with legacy sudo command",
"install_msg":"Separate loadable dev functions instead of --dev startup command",
"min_python_version":[
3,
6,
2
],
"name":"Dev",
"permissions":[],
"requirements":[],
"short":"Developer commands",
"tags":[]
}
+4
View File
@@ -0,0 +1,4 @@
from .emojireact import EmojiReactions
def setup(bot):
bot.add_cog(EmojiReactions(bot))
+81
View File
@@ -0,0 +1,81 @@
import discord
from redbot.core import commands, Config, checks
from .unicode_codes import UNICODE_EMOJI
class EmojiReactions(getattr(commands, "Cog", object)):
"""
Automatically react to messages with emojis in them with the emoji
"""
def __init__(self, bot):
self.bot = bot
default_guild = {"unicode": False, "guild":False, "random":False}
self.config = Config.get_conf(self, 35677998656)
self.config.register_guild(**default_guild)
@commands.group()
@checks.admin_or_permissions(manage_messages=True)
async def emojireact(self, ctx):
"""
Automatically react to messages with emojis in them with the emoji
"""
if ctx.invoked_subcommand is None:
try:
guild = ctx.message.guild
em = discord.Embed(title="Emojireact settings for {}".format(guild.name), colour=discord.Colour.blue())
em.add_field(name="Server", value=str(await self.config.guild(guild).guild()))
em.add_field(name="Unicode", value=str(await self.config.guild(guild).unicode()))
await ctx.send(embed=em)
except:
pass
@emojireact.command(name="unicode")
async def _unicode(self, ctx):
"""Toggle unicode emoji reactions"""
if await self.config.guild(ctx.guild).unicode():
await self.config.guild(ctx.guild).unicode.set(False)
await ctx.send("Okay, I will not react to messages containing unicode emojis!")
else:
await self.config.guild(ctx.guild).unicode.set(True)
await ctx.send("Okay, I will react to messages containing unicode emojis!")
@emojireact.command(name="guild")
async def _guild(self, ctx):
"""Toggle guild emoji reactions"""
if await self.config.guild(ctx.guild).guild():
await self.config.guild(ctx.guild).guild.set(False)
await ctx.send("Okay, I will not react to messages containing server emojis!")
else:
await self.config.guild(ctx.guild).guild.set(True)
await ctx.send("Okay, I will react to messages containing server emojis!")
@emojireact.command(name="all")
async def _all(self, ctx):
"""Toggle all emoji reactions"""
if await self.config.guild(ctx.guild).guild() or await self.config.guild(ctx.guild).unicode():
await self.config.guild(ctx.guild).guild.set(False)
await self.config.guild(ctx.guild).unicode.set(False)
await ctx.send("Okay, I will not react to messages containing all emojis!")
else:
await self.config.guild(ctx.guild).guild.set(True)
await self.config.guild(ctx.guild).unicode.set(True)
await ctx.send("Okay, I will react to messages containing all emojis!")
async def on_message(self, message):
channel = message.channel
emoji_list = []
if message.guild is None:
return
for word in message.content.split(" "):
if word.startswith("<:") and word.endswith(">") and await self.config.guild(message.guild).guild():
emoji_list.append(word.rpartition(">")[0].partition("<")[2])
if word in UNICODE_EMOJI and await self.config.guild(message.guild).unicode():
emoji_list.append(word)
if emoji_list == []:
return
for emoji in emoji_list:
try:
await message.add_reaction(emoji)
except:
pass
+22
View File
@@ -0,0 +1,22 @@
{
"author":[
"TrustyJAID"
],
"description":"React to messages containing any emojis!",
"install_msg":"React to message emojis automatically!",
"min_python_version":[
3,
6,
2
],
"name":"EmojiReact",
"permissions":[
"add_reactions"
],
"requirements":[],
"short":"Emoji Reaction",
"tags":[
"general",
"fun"
]
}
File diff suppressed because it is too large. Load diff
+5
View File
@@ -0,0 +1,5 @@
from .encoding import Encoding
def setup(bot):
n = Encoding(bot)
bot.add_cog(n)
+180
View File
@@ -0,0 +1,180 @@
import discord
from redbot.core import commands
from redbot.core.utils.chat_formatting import pagify, box
import binascii
import random
import hashlib
from string import ascii_lowercase as lc, ascii_uppercase as uc
class Encoding(getattr(commands, "Cog", object)):
"""
Convert messages into fun encodings
"""
def __init__(self, bot):
self.bot = bot
self.table = {
"A": ["00", "01", "10", "11", "00", "00", "00", "01", "01", "01", "10", "10", "10", "11", "11", "11"],
"G": ["01", "10", "11", "00", "11", "10", "01", "11", "00", "10", "11", "00", "01", "00", "01", "10"],
"C": ["10", "11", "00", "01", "10", "11", "10", "10", "11", "00", "01", "11", "00", "01", "00", "01"],
"T": ["11", "00", "01", "10", "01", "01", "11", "00", "10", "11", "00", "01", "11", "10", "10", "00"]
}
# A = 00
# G = 10
# C = 11
# T = 01
def remove_non_ascii(self, data):
msg = b""
for char in data:
if char in range(0, 127):
msg += bytes(chr(char).encode("utf8"))
return msg
def search_words(self, data):
count = 0
try:
for char in data:
if ord(char) in range(47, 122):
count += 1
except TypeError:
for char in data:
if char in range(47, 122):
count += 1
try:
if(count/len(data)) >= 0.75:
return True
except ZeroDivisionError:
return False
return False
@commands.group(name='hash', invoke_without_command=True)
async def hash_cmd(self, ctx, *, txt:str):
"""
MD5 Encrypt Text
"""
md5 = hashlib.md5(txt.encode()).hexdigest()
await ctx.send('**MD5**\n'+md5)
@hash_cmd.command(name='sha1')
async def hash_sha1(self, ctx, *, txt:str):
"""
SHA1 Encrypt Text
"""
sha = hashlib.sha1(txt.encode()).hexdigest()
await ctx.send('**SHA1**\n'+sha)
@hash_cmd.command(name='sha256')
async def hash_sha256(self, ctx, *, txt:str):
"""
SHA256 Encrypt Text
"""
sha256 = hashlib.sha256(txt.encode()).hexdigest()
await ctx.send('**SHA256**\n'+sha256)
@hash_cmd.command(name='sha512')
async def hash_sha512(self, ctx, *, txt:str):
"""
SHA512 Encrypt Text
"""
sha512 = hashlib.sha512(txt.encode()).hexdigest()
await ctx.send('**SHA512**\n'+sha512)
@commands.group(name="encode")
async def _encode(self, ctx: commands.Context):
"""Encode a string."""
pass
@commands.group(name="decode")
async def _decode(self, ctx: commands.Context):
"""Decode a string."""
pass
@_encode.command(name="binary")
async def encode_binary(self, ctx: commands.Context, *, message: str):
"""
Encode text into binary sequences of 8
"""
ascii_bin = ' '.join(bin(x)[2:].zfill(8) for x in message.encode('UTF-8'))
await ctx.send(ascii_bin)
@_decode.command(name="binary")
async def decode_binary(self, ctx: commands.Context, *, message: str):
"""
Decide binary sequences of 8
"""
msg = message.replace(" ", "")
bin_ascii = "".join([chr(int(msg[i:i+8],2)) for i in range(0,len(msg),8)])
await ctx.send(bin_ascii)
def rot_encode(self, n):
"""
https://stackoverflow.com/questions/47580337/short-rot-n-decode-function-in-python
"""
lookup = str.maketrans(lc + uc, lc[n:] + lc[:n] + uc[n:] + uc[:n])
return lambda s: s.translate(lookup)
@_encode.command(name="rot", aliases=["caeser"])
async def caeser_encode(self, ctx: commands.Context, rot_key:int, *, message:str):
"""
Encode a caeser cipher message with specified key
"""
await ctx.send(self.rot_encode(rot_key)(message))
@_decode.command(name="rot", aliases=["caeser"])
async def caeser_decode(self, ctx: commands.Context, rot_key:int, *, message:str):
"""
Decode a caeser cipher message with specified key
"""
await ctx.send(self.rot_encode(-rot_key)(message))
@_encode.command(name="dna")
async def dna_encode(self, ctx: commands.Context, *, message: str):
"""
Encodes a string into DNA 4 byte ACGT format
"""
dna = {"00": "A", "01": "T", "10": "G", "11": "C"}
message = message.strip(" ")
binary = ' '.join(bin(x)[2:].zfill(8) for x in message.encode('UTF-8')).replace(" ", "")
binlist = [binary[i:i+2] for i in range(0, len(binary), 2)]
newmsg = ""
count = 0
for letter in binlist:
newmsg += dna[letter]
count += 1
if count == 4:
count = 0
newmsg += " "
await ctx.send(newmsg)
@_decode.command(name="dna")
async def dna_decode(self ,ctx: commands.Context, *, message: str):
"""
Decodes a string of DNA in 4 byte ACGT format.
"""
message = message.strip(" ")
mapping = {}
replacement = ""
for i in range(0, 16):
skip = [" ", "\n", "\r"]
for character in message:
if character in skip:
continue
replacement += self.table[character][i]
try:
n = int("0b" + replacement, 2)
mapping[i] = n.to_bytes((n.bit_length() + 7) // 8, 'big').decode("utf8", "ignore")
except TypeError:
pass
replacement = ""
num = 1
new_msg = "Possible solutions:\n"
for result in mapping.values():
new_msg += str(num) + ": " + result + "\n"
num += 1
for page in pagify(new_msg, shorten_by=20):
await ctx.send(f"```\n{page}\n```")
+20
View File
@@ -0,0 +1,20 @@
{
"author":[
"TrustyJAID"
],
"description":"DNA and binary encoding/decoding and hashing of messages",
"install_msg":"Do `[p]encode`, `[p]decode` or `[p]help hash` to see available commands.",
"min_python_version":[
3,
6,
2
],
"name":"encoding",
"permissions":[],
"requirements":[],
"short":"General commands",
"tags":[
"general",
"fun"
]
}
+4
View File
@@ -0,0 +1,4 @@
from .faces import Faces
def setup(bot):
bot.add_cog(Faces(bot))
+429
View File
@@ -0,0 +1,429 @@
[
"¢‿¢",
"©¿© o",
"ª{•̃̾_•̃̾}ª",
"¬_¬",
"¯\(º_o)/¯",
"¯\\(º o)/¯",
"¯\\_(⊙︿⊙)_/¯",
"¯\\_(ツ)_/¯",
"°ω°",
"°Д°",
"°‿‿°",
"°ﺑ°",
"´ ▽ ` )ノ",
"¿ⓧ_ⓧﮌ",
"Ò,ó",
"ó‿ó",
"ô⌐ô",
"ôヮô",
"ŎםŎ",
"ŏﺡó",
"ʕ•̫͡•ʔ",
"ʕ•ᴥ•ʔ",
"ʘ‿ʘ",
"˚•_•˚",
"˚⌇˚",
"˚▱˚",
"̿ ̿̿'̿'\\̵͇̿̿\\=(•̪●)=/̵͇̿̿/'̿̿ ̿ ̿ ̿",
"͡° ͜ʖ ͡°",
"Σ ◕ ◡ ◕",
"Σ (゚Д゚;)",
"Σ(゚Д゚;≡;゚д゚)",
"Σ(゚Д゚ )",
"Σ(||゚Д゚)",
"Φ,Φ",
"δﺡό",
"σ_σ",
"д_д",
"ф_ф",
"щ(゚Д゚щ)",
"щ(ಠ益ಠщ)",
"щ(ಥДಥщ)",
"Ծ_Ծ",
"أ‿أ",
"ب_ب",
"ح˚௰˚づ",
"ح˚ᆺ˚ว",
"حᇂﮌᇂ)",
"٩๏̯͡๏۶",
"٩๏̯͡๏)۶",
"٩◔̯◔۶",
"٩(×̯×)۶",
"٩(̾●̮̮̃̾•̃̾)۶",
"٩(͡๏̯͡๏)۶",
"٩(͡๏̯ ͡๏)۶",
"٩(ಥ_ಥ)۶",
"٩(•̮̮̃•̃)۶",
"٩(●̮̮̃•̃)۶",
"٩(●̮̮̃●̃)۶",
"٩(。͡•‿•。)۶",
"٩(-̮̮̃•̃)۶",
"٩(-̮̮̃-̃)۶",
"۞_۞",
"۞_۟۞",
"۹ↁﮌↁ",
"۹⌤_⌤۹",
"॓_॔",
"१✌◡✌५",
"१|˚–˚|५",
"ਉ_ਉ",
"ଘ_ଘ",
"இ_இ",
"ఠ_ఠ",
"రృర",
"ಠ¿ಠi",
"ಠ‿ಠ",
"ಠ⌣ಠ",
"ಠ╭╮ಠ",
"ಠ▃ಠ",
"ಠ◡ಠ",
"ಠ益ಠ",
"ಠ益ಠ",
"ಠ︵ಠ凸",
"ಠ , ಥ",
"ಠ.ಠ",
"ಠoಠ",
"ಠ_ృ",
"ಠ_ಠ",
"ಠ_๏",
"ಠ~ಠ",
"ಡ_ಡ",
"ತಎತ",
"ತ_ತ",
"ಥдಥ",
"ಥ‿ಥ",
"ಥ⌣ಥ",
"ಥ◡ಥ",
"ಥ﹏ಥ",
"ಥ_ಥ",
"ಭ_ಭ",
"ರ_ರ",
"ಸ , ໖",
"ಸ_ಸ",
"ക_ക",
"อ้_อ้",
"อ_อ",
"โ๏௰๏ใ ื",
"๏̯͡๏﴿",
"๏̯͡๏",
"๏̯͡๏﴿",
"๏[-ิิ_•ิ]๏",
"๏_๏",
"໖_໖",
"༺‿༻",
"ლ(´ڡ`ლ)",
"ლ(́◉◞౪◟◉‵ლ)",
"ლ(ಠ益ಠლ)",
"ლ(╹◡╹ლ)",
"ლ(◉◞౪◟◉‵ლ)",
"ლ,ᔑ•ﺪ͟͠•ᔐ.ლ",
"ᄽὁȍ ̪ őὀᄿ",
"ᕕ( ᐛ )ᕗ",
"ᕙ(⇀‸↼‶)ᕗ",
"ᕦ(ò_óˇ)ᕤ",
"ᶘ ᵒᴥᵒᶅ",
"‘︿’",
"•▱•",
"•✞_✞•",
"•ﺑ•",
"•(⌚_⌚)•",
"•_•)",
"‷̗ↂ凸ↂ‴̖",
"‹•.•›",
"‹› ‹(•¿•)› ‹›",
"‹(ᵒᴥᵒ­­­­­)›",
"‹(•¿•)›",
"ↁ_ↁ",
"⇎_⇎",
"∩(︶▽︶)∩",
"∩( ・ω・)∩",
"≖‿≖",
"≧ヮ≦",
"⊂•⊃_⊂•⊃",
"⊂⌒~⊃。Д。)⊃",
"⊂(◉‿◉)つ",
"⊂(゚Д゚,,⊂⌒`つ",
"⊙ω⊙",
"⊙▂⊙",
"⊙▃⊙",
"⊙△⊙",
"⊙︿⊙",
"⊙﹏⊙",
"⊙0⊙",
"⊛ठ̯⊛",
"⋋ō_ō`",
"━━━ヽ(ヽ(゚ヽ(゚∀ヽ(゚∀゚ヽ(゚∀゚)ノ゚∀゚)ノ∀゚)ノ゚)ノ)ノ━━━",
"┌∩┐(◕_◕)┌∩┐",
"┌( ಠ_ಠ)┘",
"┌( ಥ_ಥ)┘",
"╚(•⌂•)╝",
"╭╮╭╮☜{•̃̾_•̃̾}☞╭╮╭╮",
"╭✬⌢✬╮",
"╮(─▽─)╭",
"╯‵Д′)╯彡┻━┻",
"╰☆╮",
"□_□",
"►_◄",
"◃┆◉◡◉┆▷",
"◉△◉",
"◉︵◉",
"◉_◉",
"○_○",
"●¿●\\ ~",
"●_●",
"◔̯◔",
"◔ᴗ◔",
"◔ ⌣ ◔",
"◔_◔",
"◕ω◕",
"◕‿◕",
"◕◡◕",
"◕ ◡ ◕",
"◖♪_♪|◗",
"◖|◔◡◉|◗",
"◘_◘",
"◙‿◙",
"◜㍕◝",
"◪_◪",
"◮_◮",
"☁ ☝ˆ~ˆ☂",
"☆¸☆",
"☉‿⊙",
"☉_☉",
"☐_☐",
"☜ق❂Ⴢ❂ق☞",
"☜(⌒▽⌒)☞",
"☜(゚ヮ゚☜)",
"☜-(ΘLΘ)-☞",
"☝☞✌",
"☮▁▂▃▄☾ ♛ ◡ ♛ ☽▄▃▂▁☮",
"☹_☹",
"☻_☻",
"☼.☼",
"☾˙❀‿❀˙☽",
"♀ح♀ヾ",
"♥‿♥",
"♥╣[-_-]╠♥",
"♥╭╮♥",
"♥◡♥",
"✌♫♪˙❤‿❤˙♫♪✌",
"✌.ʕʘ‿ʘʔ.✌",
"✌.|•͡˘‿•͡˘|.✌",
"✖‿✖",
"✖_✖",
"❐‿❑",
"⨀_⨀",
"⨀_Ꙩ",
"⨂_⨂",
"〆(・∀・@)",
"《〠_〠》",
"【•】_【•】",
"〠_〠",
"〴⋋_⋌〵",
"の� �の",
"ニガー? ━━━━━━(゚∀゚)━━━━━━ ニガー?",
"ペ㍕˚\\",
"ヽ(´ー` )ノ",
"ヽ(๏∀๏ )ノ",
"ヽ(`Д´)ノ",
"ヽ(o`皿′o)ノ",
"ヽ(`Д´)ノ",
"ㅎ_ㅎ",
"乂◜◬◝乂",
"凸ಠ益ಠ)凸",
"句_句",
"Ꙩ⌵Ꙩ",
"Ꙩ_Ꙩ",
"ꙩ_ꙩ",
"Ꙫ_Ꙫ",
"ꙫ_ꙫ",
"ꙮ_ꙮ",
"흫_흫",
"句_句",
"﴾͡๏̯͡๏﴿ O'RLY?",
"¯\\(ºдಠ)/¯",
"(·×·)",
"(⌒Д⌒)",
"(╹ェ╹)",
"(♯・∀・)⊃",
"( ´∀`)☆",
"( ´∀`)",
"(゜Д゜)",
"(・∀・)",
"(・A・)",
"(゚∀゚)",
"( ̄へ ̄)",
"( ´☣///_ゝ///☣`)",
"( つ Д `)",
"_☆( ´_⊃`)☆_",
"。◕‿‿◕。",
"。◕ ‿ ◕。",
"!⑈ˆ~ˆ!⑈",
"!(`・ω・。)",
"(¬‿¬)",
"(¬▂¬)",
"(¬_¬)",
"(°ℇ °)",
"(°∀°)",
"(´ω`)",
"(´◉◞౪◟◉)",
"(´ヘ`;)",
"(´・ω・`)",
"(´ー`)",
"(ʘ‿ʘ)",
"(ʘ_ʘ)",
"(˚இ˚)",
"(͡๏̯͡๏)",
"(ΘεΘ;)",
"(ι´Д`)ノ",
"(Ծ‸ Ծ)",
"(॓_॔)",
"(० ्०)",
"(ு८ு_ .:)",
"(ಠ‾ಠ)",
"(ಠ‿ʘ)",
"(ಠ‿ಠ)",
"(ಠ⌣ಠ)",
"(ಠ益ಠ ╬)",
"(ಠ益ಠ)",
"(ಠ_ృ)",
"(ಠ_ಠ)",
"(ಥ﹏ಥ)",
"(ಥ_ಥ)",
"(๏̯͡๏ )",
"(ღ˘⌣˘ღ) ♫・*:.。. .。.:*・",
"(ღ˘⌣˘ღ)",
"(ᵔᴥᵔ)",
"(•ω•)",
"(•‿•)",
"(•⊙ω⊙•)",
"(• ε •)",
"(∩▂∩)",
"(∩︵∩)",
"(∪ ◡ ∪)",
"(≧ω≦)",
"(≧◡≦)",
"(≧ロ≦)",
"(⊙ヮ⊙)",
"(⊙_◎)",
"(⋋▂⋌)",
"(⌐■_■)",
"(─‿‿─)",
"(┛◉Д◉)┛┻━┻",
"(╥_╥)",
"(╬ಠ益ಠ)",
"(╬◣д◢)",
"(╬ ಠ益ಠ)",
"(╯°□°)╯︵ ┻━┻",
"(╯ಊ╰)",
"(╯◕_◕)╯",
"(╯︵╰,)",
"(╯3╰)",
"(╯_╰)",
"(╹◡╹)凸",
"(▰˘◡˘▰)",
"(●´ω`●)",
"(●´∀`●)",
"(◑‿◐)",
"(◑◡◑)",
"(◕‿◕✿)",
"(◕‿◕)",
"(◕‿-)",
"(◕︵◕)",
"(◕ ^ ◕)",
"(◕_◕)",
"(◜௰◝)",
"(◡‿◡✿)",
"(◣_◢)",
"(☞゚∀゚)☞",
"(☞゚ヮ゚)☞",
"(☞゚ ∀゚ )☞",
"(☼◡☼)",
"(☼_☼)",
"(✌゚∀゚)☞",
"(✖╭╮✖)",
"(✪㉨✪)",
"(✿◠‿◠)",
"(✿ ♥‿♥)",
"( ・∀・)",
"( ・ัω・ั)?",
"( ゚∀゚)o彡゜えーりんえーりん!!",
"(。・_・。)",
"(つд`)",
"(づ。◕‿‿◕。)づ",
"(ノಠ益ಠ)ノ彡┻━┻",
"(ノ ◑‿◑)ノ",
"(ノ_・。)",
"(・∀・ )",
"(屮゚Д゚)屮",
"(︶ω︶)",
"(︶︹︺)",
"(ﺧ益ﺨ)",
"(;一_一)",
"(`・ω・´)”",
"(。◕‿‿◕。)",
"(。◕‿◕。)",
"(。◕ ‿ ◕。)",
"(。♥‿♥。)",
"(。・ω..・)っ",
"(・ェ-)",
"(ノ◕ヮ◕)ノ*:・゚✧",
"(゚Д゚)",
"(゚Д゚)y─┛~~",
"(゚∀゚)",
"(゚ヮ゚)",
"( ̄□ ̄)",
"( ̄。 ̄)",
"( ̄ー ̄)",
"( ̄(エ) ̄)",
"( °٢° )",
"( ´_ゝ`)",
"( ͡° ͜ʖ ͡°)",
"( ͡~ ͜ʖ ͡°)",
"( ಠ◡ಠ )",
"( •_•)>⌐■-■",
"(  ゚,_ゝ゚)",
"( ・ิз・ิ)",
"( ゚д゚)、",
"( ^▽^)σ)~O~)",
"((((゜д゜;))))",
"(*´д`*)",
"(*..Д`)",
"(*..д`*)",
"(*~▽~)",
"(-’๏_๏’-)",
"(-_- )ノ",
"(/◔ ◡ ◔)/",
"(///_ಥ)",
"(;´Д`)",
"(=ω=;)",
"(=゜ω゜)",
"(>'o')>♥<('o'<)",
"(n˘v˘•)¬",
"(o´ω`o)",
"(V)(°,,°)(V)",
"(\/) (°,,°) (\/) WOOPwoopwowopwoopwoopwoop!",
"(^▽^)",
"(`・ω・´)",
"(~ ̄▽ ̄)~",
"/╲/\\╭ºoꍘoº╮/\\╱\\",
"<【☯】‿【☯】>",
"= (゚д゚)ウ",
"@_@",
"d(*⌒▽⌒*)b",
"o(≧∀≦)o",
"o(≧o≦)o",
"q(❂‿❂)p",
"y=ー( ゚д゚)・∵.",
"\\˚ㄥ˚\\",
"\\ᇂ_ᇂ\\",
"\\(ಠ ὡ ಠ )/",
"\\(◕ ◡ ◕\\)",
"^̮^",
"^ㅂ^",
"_(͡๏̯͡๏)_",
"{´◕ ◡ ◕`}",
"{ಠ_ಠ}__,,|,",
"{◕ ◡ ◕}"
]
+36
View File
@@ -0,0 +1,36 @@
import discord
from random import choice
import random
from redbot.core import commands
from . import faceslist
class Faces(getattr(commands, "Cog", object)):
"""
Generate fun/random unicode faces courtesy of the CIA files
"""
def __init__(self, bot):
self.bot = bot
self.faces = faceslist.faces
@commands.command(pass_context=True, aliases=["japaneseface"])
async def face(self, ctx, number=None):
"""Japanese Faces at random courtesy of the CIA"""
if number is None:
await ctx.send(choice(self.faces))
return
if "<@" in str(number):
random.seed(number.strip("<@!>"))
userface = self.faces[random.randint(0, len(self.faces))]
await ctx.send(userface)
return
if number.isdigit():
if int(number) <= len(self.faces):
await ctx.send(self.faces[int(number)-1])
return
else:
await ctx.send("That number is too large, pick less than {}!"
.format(len(self.faces)))
return
if not number.isdigit() and "<@!" not in number:
await ctx.send(self.faces[len(number)])
+429
View File
@@ -0,0 +1,429 @@
faces = [
"¢‿¢",
"©¿© o",
"ª{•̃̾_•̃̾}ª",
"¬_¬",
"¯\(º_o)/¯",
"¯\\(º o)/¯",
"¯\\_(⊙︿⊙)_/¯",
"¯\\_(ツ)_/¯",
"°ω°",
"°Д°",
"°‿‿°",
"°ﺑ°",
"´ ▽ ` )ノ",
"¿ⓧ_ⓧﮌ",
"Ò,ó",
"ó‿ó",
"ô⌐ô",
"ôヮô",
"ŎםŎ",
"ŏﺡó",
"ʕ•̫͡•ʔ",
"ʕ•ᴥ•ʔ",
"ʘ‿ʘ",
"˚•_•˚",
"˚⌇˚",
"˚▱˚",
"̿ ̿̿'̿'\\̵͇̿̿\\=(•̪●)=/̵͇̿̿/'̿̿ ̿ ̿ ̿",
"͡° ͜ʖ ͡°",
"Σ ◕ ◡ ◕",
"Σ (゚Д゚;)",
"Σ(゚Д゚;≡;゚д゚)",
"Σ(゚Д゚ )",
"Σ(||゚Д゚)",
"Φ,Φ",
"δﺡό",
"σ_σ",
"д_д",
"ф_ф",
"щ(゚Д゚щ)",
"щ(ಠ益ಠщ)",
"щ(ಥДಥщ)",
"Ծ_Ծ",
"أ‿أ",
"ب_ب",
"ح˚௰˚づ",
"ح˚ᆺ˚ว",
"حᇂﮌᇂ)",
"٩๏̯͡๏۶",
"٩๏̯͡๏)۶",
"٩◔̯◔۶",
"٩(×̯×)۶",
"٩(̾●̮̮̃̾•̃̾)۶",
"٩(͡๏̯͡๏)۶",
"٩(͡๏̯ ͡๏)۶",
"٩(ಥ_ಥ)۶",
"٩(•̮̮̃•̃)۶",
"٩(●̮̮̃•̃)۶",
"٩(●̮̮̃●̃)۶",
"٩(。͡•‿•。)۶",
"٩(-̮̮̃•̃)۶",
"٩(-̮̮̃-̃)۶",
"۞_۞",
"۞_۟۞",
"۹ↁﮌↁ",
"۹⌤_⌤۹",
"॓_॔",
"१✌◡✌५",
"१|˚–˚|५",
"ਉ_ਉ",
"ଘ_ଘ",
"இ_இ",
"ఠ_ఠ",
"రృర",
"ಠ¿ಠi",
"ಠ‿ಠ",
"ಠ⌣ಠ",
"ಠ╭╮ಠ",
"ಠ▃ಠ",
"ಠ◡ಠ",
"ಠ益ಠ",
"ಠ益ಠ",
"ಠ︵ಠ凸",
"ಠ , ಥ",
"ಠ.ಠ",
"ಠoಠ",
"ಠ_ృ",
"ಠ_ಠ",
"ಠ_๏",
"ಠ~ಠ",
"ಡ_ಡ",
"ತಎತ",
"ತ_ತ",
"ಥдಥ",
"ಥ‿ಥ",
"ಥ⌣ಥ",
"ಥ◡ಥ",
"ಥ﹏ಥ",
"ಥ_ಥ",
"ಭ_ಭ",
"ರ_ರ",
"ಸ , ໖",
"ಸ_ಸ",
"ക_ക",
"อ้_อ้",
"อ_อ",
"โ๏௰๏ใ ื",
"๏̯͡๏﴿",
"๏̯͡๏",
"๏̯͡๏﴿",
"๏[-ิิ_•ิ]๏",
"๏_๏",
"໖_໖",
"༺‿༻",
"ლ(´ڡ`ლ)",
"ლ(́◉◞౪◟◉‵ლ)",
"ლ(ಠ益ಠლ)",
"ლ(╹◡╹ლ)",
"ლ(◉◞౪◟◉‵ლ)",
"ლ,ᔑ•ﺪ͟͠•ᔐ.ლ",
"ᄽὁȍ ̪ őὀᄿ",
"ᕕ( ᐛ )ᕗ",
"ᕙ(⇀‸↼‶)ᕗ",
"ᕦ(ò_óˇ)ᕤ",
"ᶘ ᵒᴥᵒᶅ",
"‘︿’",
"•▱•",
"•✞_✞•",
"•ﺑ•",
"•(⌚_⌚)•",
"•_•)",
"‷̗ↂ凸ↂ‴̖",
"‹•.•›",
"‹› ‹(•¿•)› ‹›",
"‹(ᵒᴥᵒ­­­­­)›",
"‹(•¿•)›",
"ↁ_ↁ",
"⇎_⇎",
"∩(︶▽︶)∩",
"∩( ・ω・)∩",
"≖‿≖",
"≧ヮ≦",
"⊂•⊃_⊂•⊃",
"⊂⌒~⊃。Д。)⊃",
"⊂(◉‿◉)つ",
"⊂(゚Д゚,,⊂⌒`つ",
"⊙ω⊙",
"⊙▂⊙",
"⊙▃⊙",
"⊙△⊙",
"⊙︿⊙",
"⊙﹏⊙",
"⊙0⊙",
"⊛ठ̯⊛",
"⋋ō_ō`",
"━━━ヽ(ヽ(゚ヽ(゚∀ヽ(゚∀゚ヽ(゚∀゚)ノ゚∀゚)ノ∀゚)ノ゚)ノ)ノ━━━",
"┌∩┐(◕_◕)┌∩┐",
"┌( ಠ_ಠ)┘",
"┌( ಥ_ಥ)┘",
"╚(•⌂•)╝",
"╭╮╭╮☜{•̃̾_•̃̾}☞╭╮╭╮",
"╭✬⌢✬╮",
"╮(─▽─)╭",
"╯‵Д′)╯彡┻━┻",
"╰☆╮",
"□_□",
"►_◄",
"◃┆◉◡◉┆▷",
"◉△◉",
"◉︵◉",
"◉_◉",
"○_○",
"●¿●\\ ~",
"●_●",
"◔̯◔",
"◔ᴗ◔",
"◔ ⌣ ◔",
"◔_◔",
"◕ω◕",
"◕‿◕",
"◕◡◕",
"◕ ◡ ◕",
"◖♪_♪|◗",
"◖|◔◡◉|◗",
"◘_◘",
"◙‿◙",
"◜㍕◝",
"◪_◪",
"◮_◮",
"☁ ☝ˆ~ˆ☂",
"☆¸☆",
"☉‿⊙",
"☉_☉",
"☐_☐",
"☜ق❂Ⴢ❂ق☞",
"☜(⌒▽⌒)☞",
"☜(゚ヮ゚☜)",
"☜-(ΘLΘ)-☞",
"☝☞✌",
"☮▁▂▃▄☾ ♛ ◡ ♛ ☽▄▃▂▁☮",
"☹_☹",
"☻_☻",
"☼.☼",
"☾˙❀‿❀˙☽",
"♀ح♀ヾ",
"♥‿♥",
"♥╣[-_-]╠♥",
"♥╭╮♥",
"♥◡♥",
"✌♫♪˙❤‿❤˙♫♪✌",
"✌.ʕʘ‿ʘʔ.✌",
"✌.|•͡˘‿•͡˘|.✌",
"✖‿✖",
"✖_✖",
"❐‿❑",
"⨀_⨀",
"⨀_Ꙩ",
"⨂_⨂",
"〆(・∀・@)",
"《〠_〠》",
"【•】_【•】",
"〠_〠",
"〴⋋_⋌〵",
"の� �の",
"ニガー? ━━━━━━(゚∀゚)━━━━━━ ニガー?",
"ペ㍕˚\\",
"ヽ(´ー` )ノ",
"ヽ(๏∀๏ )ノ",
"ヽ(`Д´)ノ",
"ヽ(o`皿′o)ノ",
"ヽ(`Д´)ノ",
"ㅎ_ㅎ",
"乂◜◬◝乂",
"凸ಠ益ಠ)凸",
"句_句",
"Ꙩ⌵Ꙩ",
"Ꙩ_Ꙩ",
"ꙩ_ꙩ",
"Ꙫ_Ꙫ",
"ꙫ_ꙫ",
"ꙮ_ꙮ",
"흫_흫",
"句_句",
"﴾͡๏̯͡๏﴿ O'RLY?",
"¯\\(ºдಠ)/¯",
"(·×·)",
"(⌒Д⌒)",
"(╹ェ╹)",
"(♯・∀・)⊃",
"( ´∀`)☆",
"( ´∀`)",
"(゜Д゜)",
"(・∀・)",
"(・A・)",
"(゚∀゚)",
"( ̄へ ̄)",
"( ´☣///_ゝ///☣`)",
"( つ Д `)",
"_☆( ´_⊃`)☆_",
"。◕‿‿◕。",
"。◕ ‿ ◕。",
"!⑈ˆ~ˆ!⑈",
"!(`・ω・。)",
"(¬‿¬)",
"(¬▂¬)",
"(¬_¬)",
"(°ℇ °)",
"(°∀°)",
"(´ω`)",
"(´◉◞౪◟◉)",
"(´ヘ`;)",
"(´・ω・`)",
"(´ー`)",
"(ʘ‿ʘ)",
"(ʘ_ʘ)",
"(˚இ˚)",
"(͡๏̯͡๏)",
"(ΘεΘ;)",
"(ι´Д`)ノ",
"(Ծ‸ Ծ)",
"(॓_॔)",
"(० ्०)",
"(ு८ு_ .:)",
"(ಠ‾ಠ)",
"(ಠ‿ʘ)",
"(ಠ‿ಠ)",
"(ಠ⌣ಠ)",
"(ಠ益ಠ ╬)",
"(ಠ益ಠ)",
"(ಠ_ృ)",
"(ಠ_ಠ)",
"(ಥ﹏ಥ)",
"(ಥ_ಥ)",
"(๏̯͡๏ )",
"(ღ˘⌣˘ღ) ♫・*:.。. .。.:*・",
"(ღ˘⌣˘ღ)",
"(ᵔᴥᵔ)",
"(•ω•)",
"(•‿•)",
"(•⊙ω⊙•)",
"(• ε •)",
"(∩▂∩)",
"(∩︵∩)",
"(∪ ◡ ∪)",
"(≧ω≦)",
"(≧◡≦)",
"(≧ロ≦)",
"(⊙ヮ⊙)",
"(⊙_◎)",
"(⋋▂⋌)",
"(⌐■_■)",
"(─‿‿─)",
"(┛◉Д◉)┛┻━┻",
"(╥_╥)",
"(╬ಠ益ಠ)",
"(╬◣д◢)",
"(╬ ಠ益ಠ)",
"(╯°□°)╯︵ ┻━┻",
"(╯ಊ╰)",
"(╯◕_◕)╯",
"(╯︵╰,)",
"(╯3╰)",
"(╯_╰)",
"(╹◡╹)凸",
"(▰˘◡˘▰)",
"(●´ω`●)",
"(●´∀`●)",
"(◑‿◐)",
"(◑◡◑)",
"(◕‿◕✿)",
"(◕‿◕)",
"(◕‿-)",
"(◕︵◕)",
"(◕ ^ ◕)",
"(◕_◕)",
"(◜௰◝)",
"(◡‿◡✿)",
"(◣_◢)",
"(☞゚∀゚)☞",
"(☞゚ヮ゚)☞",
"(☞゚ ∀゚ )☞",
"(☼◡☼)",
"(☼_☼)",
"(✌゚∀゚)☞",
"(✖╭╮✖)",
"(✪㉨✪)",
"(✿◠‿◠)",
"(✿ ♥‿♥)",
"( ・∀・)",
"( ・ัω・ั)?",
"( ゚∀゚)o彡゜えーりんえーりん!!",
"(。・_・。)",
"(つд`)",
"(づ。◕‿‿◕。)づ",
"(ノಠ益ಠ)ノ彡┻━┻",
"(ノ ◑‿◑)ノ",
"(ノ_・。)",
"(・∀・ )",
"(屮゚Д゚)屮",
"(︶ω︶)",
"(︶︹︺)",
"(ﺧ益ﺨ)",
"(;一_一)",
"(`・ω・´)”",
"(。◕‿‿◕。)",
"(。◕‿◕。)",
"(。◕ ‿ ◕。)",
"(。♥‿♥。)",
"(。・ω..・)っ",
"(・ェ-)",
"(ノ◕ヮ◕)ノ*:・゚✧",
"(゚Д゚)",
"(゚Д゚)y─┛~~",
"(゚∀゚)",
"(゚ヮ゚)",
"( ̄□ ̄)",
"( ̄。 ̄)",
"( ̄ー ̄)",
"( ̄(エ) ̄)",
"( °٢° )",
"( ´_ゝ`)",
"( ͡° ͜ʖ ͡°)",
"( ͡~ ͜ʖ ͡°)",
"( ಠ◡ಠ )",
"( •_•)>⌐■-■",
"(  ゚,_ゝ゚)",
"( ・ิз・ิ)",
"( ゚д゚)、",
"( ^▽^)σ)~O~)",
"((((゜д゜;))))",
"(*´д`*)",
"(*..Д`)",
"(*..д`*)",
"(*~▽~)",
"(-’๏_๏’-)",
"(-_- )ノ",
"(/◔ ◡ ◔)/",
"(///_ಥ)",
"(;´Д`)",
"(=ω=;)",
"(=゜ω゜)",
"(>'o')>♥<('o'<)",
"(n˘v˘•)¬",
"(o´ω`o)",
"(V)(°,,°)(V)",
"(\/) (°,,°) (\/) WOOPwoopwowopwoopwoopwoop!",
"(^▽^)",
"(`・ω・´)",
"(~ ̄▽ ̄)~",
"/╲/\\╭ºoꍘoº╮/\\╱\\",
"<【☯】‿【☯】>",
"= (゚д゚)ウ",
"@_@",
"d(*⌒▽⌒*)b",
"o(≧∀≦)o",
"o(≧o≦)o",
"q(❂‿❂)p",
"y=ー( ゚д゚)・∵.",
"\\˚ㄥ˚\\",
"\\ᇂ_ᇂ\\",
"\\(ಠ ὡ ಠ )/",
"\\(◕ ◡ ◕\\)",
"^̮^",
"^ㅂ^",
"_(͡๏̯͡๏)_",
"{´◕ ◡ ◕`}",
"{ಠ_ಠ}__,,|,",
"{◕ ◡ ◕}"
]
+20
View File
@@ -0,0 +1,20 @@
{
"author":[
"TrustyJAID"
],
"description":"Japanese faces courtesy of the CIA",
"install_msg":"Find what your face is like!",
"min_python_version":[
3,
6,
2
],
"name":"Faces",
"permissions":[],
"requirements":[],
"short":"General commands",
"tags":[
"general",
"fun"
]
}
+5
View File
@@ -0,0 +1,5 @@
from .fun import Fun
def setup(bot):
bot.add_cog(Fun(bot))
+316
View File
@@ -0,0 +1,316 @@
import random
import re
import json
from redbot.core import commands
import discord
'''Module for fun/meme commands commands
Fun commands from Appu's selfbot
'''
class Fun(getattr(commands, "Cog", object)):
"""
RedBot V3 conversion of Appu's Fun cog
"""
def __init__(self, bot):
self.bot = bot
self.regionals = {'a': '\N{REGIONAL INDICATOR SYMBOL LETTER A}', 'b': '\N{REGIONAL INDICATOR SYMBOL LETTER B}',
'c': '\N{REGIONAL INDICATOR SYMBOL LETTER C}',
'd': '\N{REGIONAL INDICATOR SYMBOL LETTER D}', 'e': '\N{REGIONAL INDICATOR SYMBOL LETTER E}',
'f': '\N{REGIONAL INDICATOR SYMBOL LETTER F}',
'g': '\N{REGIONAL INDICATOR SYMBOL LETTER G}', 'h': '\N{REGIONAL INDICATOR SYMBOL LETTER H}',
'i': '\N{REGIONAL INDICATOR SYMBOL LETTER I}',
'j': '\N{REGIONAL INDICATOR SYMBOL LETTER J}', 'k': '\N{REGIONAL INDICATOR SYMBOL LETTER K}',
'l': '\N{REGIONAL INDICATOR SYMBOL LETTER L}',
'm': '\N{REGIONAL INDICATOR SYMBOL LETTER M}', 'n': '\N{REGIONAL INDICATOR SYMBOL LETTER N}',
'o': '\N{REGIONAL INDICATOR SYMBOL LETTER O}',
'p': '\N{REGIONAL INDICATOR SYMBOL LETTER P}', 'q': '\N{REGIONAL INDICATOR SYMBOL LETTER Q}',
'r': '\N{REGIONAL INDICATOR SYMBOL LETTER R}',
's': '\N{REGIONAL INDICATOR SYMBOL LETTER S}', 't': '\N{REGIONAL INDICATOR SYMBOL LETTER T}',
'u': '\N{REGIONAL INDICATOR SYMBOL LETTER U}',
'v': '\N{REGIONAL INDICATOR SYMBOL LETTER V}', 'w': '\N{REGIONAL INDICATOR SYMBOL LETTER W}',
'x': '\N{REGIONAL INDICATOR SYMBOL LETTER X}',
'y': '\N{REGIONAL INDICATOR SYMBOL LETTER Y}', 'z': '\N{REGIONAL INDICATOR SYMBOL LETTER Z}',
'0': '0⃣', '1': '1⃣', '2': '2⃣', '3': '3⃣',
'4': '4⃣', '5': '5⃣', '6': '6⃣', '7': '7⃣', '8': '8⃣', '9': '9⃣', '!': '\u2757',
'?': '\u2753'}
self.emoji_reg = re.compile(r'<:.+?:([0-9]{15,21})>')
self.ball = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes definitely', 'You may rely on it',
'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes',
'Reply hazy try again',
'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again',
'Don\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good',
'Very doubtful']
emoji_dict = {
# these arrays are in order of "most desirable". Put emojis that most convincingly correspond to their letter near the front of each array.
'a': ['🇦', '🅰', '🍙', '🔼', '4⃣'],
'b': ['🇧', '🅱', '8⃣'],
'c': ['🇨', '©', '🗜'],
'd': ['🇩', '↩'],
'e': ['🇪', '3⃣', '📧', '💶'],
'f': ['🇫', '🎏'],
'g': ['🇬', '🗜', '6⃣', '9⃣', '⛽'],
'h': ['🇭', '♓'],
'i': ['🇮', 'ℹ', '🚹', '1⃣'],
'j': ['🇯', '🗾'],
'k': ['🇰', '🎋'],
'l': ['🇱', '1⃣', '🇮', '👢', '💷'],
'm': ['🇲', 'Ⓜ', '📉'],
'n': ['🇳', '♑', '🎵'],
'o': ['🇴', '🅾', '0⃣', '⭕', '🔘', '⏺', '⚪', '⚫', '🔵', '🔴', '💫'],
'p': ['🇵', '🅿'],
'q': ['🇶', '♌'],
'r': ['🇷', '®'],
's': ['🇸', '💲', '5⃣', '⚡', '💰', '💵'],
't': ['🇹', '✝', '➕', '🎚', '🌴', '7⃣'],
'u': ['🇺', '⛎', '🐉'],
'v': ['🇻', '♈', '☑'],
'w': ['🇼', '〰', '📈'],
'x': ['🇽', '❎', '✖', '❌', '⚒'],
'y': ['🇾', '✌', '💴'],
'z': ['🇿', '2⃣'],
'0': ['0⃣', '🅾', '0⃣', '⭕', '🔘', '⏺', '⚪', '⚫', '🔵', '🔴', '💫'],
'1': ['1⃣', '🇮'],
'2': ['2⃣', '🇿'],
'3': ['3⃣'],
'4': ['4⃣'],
'5': ['5⃣', '🇸', '💲', '⚡'],
'6': ['6⃣'],
'7': ['7⃣'],
'8': ['8⃣', '🎱', '🇧', '🅱'],
'9': ['9⃣'],
'?': ['❓'],
'!': ['❗', '❕', '⚠', '❣'],
# emojis that contain more than one letter can also help us react
# letters that we are trying to replace go in front, emoji to use second
#
# if there is any overlap between characters that could be replaced,
# e.g. 💯 vs 🔟, both could replace "10",
# the longest ones & most desirable ones should go at the top
# else you'll have "100" -> "🔟0" instead of "100" -> "💯".
'combination': [['cool', '🆒'],
['back', '🔙'],
['soon', '🔜'],
['free', '🆓'],
['end', '🔚'],
['top', '🔝'],
['abc', '🔤'],
['atm', '🏧'],
['new', '🆕'],
['sos', '🆘'],
['100', '💯'],
['loo', '💯'],
['zzz', '💤'],
['...', '💬'],
['ng', '🆖'],
['id', '🆔'],
['vs', '🆚'],
['wc', '🚾'],
['ab', '🆎'],
['cl', '🆑'],
['ok', '🆗'],
['up', '🆙'],
['10', '🔟'],
['11', '⏸'],
['ll', '⏸'],
['ii', '⏸'],
['tm', '™'],
['on', '🔛'],
['oo', '🈁'],
['!?', '⁉'],
['!!', '‼'],
['21', '📅'],
]
}
# used in textflip
text_flip = {}
char_list = "!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}"
alt_char_list = "{|}zʎxʍʌnʇsɹbdouɯlʞɾᴉɥƃɟǝpɔqɐ,‾^[\]Z⅄XMΛ∩┴SɹQԀONW˥ʞſIHפℲƎpƆq∀@¿<=>;:68ㄥ9ϛㄣƐᄅƖ0/˙-'+*(),⅋%$#¡"[::-1]
for idx, char in enumerate(char_list):
text_flip[char] = alt_char_list[idx]
text_flip[alt_char_list[idx]] = char
# used in [p]react, checks if it's possible to react with the duper string or not
def has_dupe(duper):
collect_my_duper = list(filter(lambda x: x != '⃣',
duper)) # ⃣ appears twice in the number unicode thing, so that must be stripped
return len(set(collect_my_duper)) != len(collect_my_duper)
# used in [p]react, replaces e.g. 'ng' with '🆖'
def replace_combos(react_me):
for combo in Fun.emoji_dict['combination']:
if combo[0] in react_me:
react_me = react_me.replace(combo[0], combo[1], 1)
return react_me
# used in [p]react, replaces e.g. 'aaaa' with '🇦🅰🍙🔼'
def replace_letters(react_me):
for char in "abcdefghijklmnopqrstuvwxyz0123456789!?":
char_count = react_me.count(char)
if char_count > 1: # there's a duplicate of this letter:
if len(Fun.emoji_dict[
char]) >= char_count: # if we have enough different ways to say the letter to complete the emoji chain
i = 0
while i < char_count: # moving goal post necessitates while loop instead of for
if Fun.emoji_dict[char][i] not in react_me:
react_me = react_me.replace(char, Fun.emoji_dict[char][i], 1)
else:
char_count += 1 # skip this one because it's already been used by another replacement (e.g. circle emoji used to replace O already, then want to replace 0)
i += 1
else:
if char_count == 1:
react_me = react_me.replace(char, Fun.emoji_dict[char][0])
return react_me
@commands.command(pass_context=True)
async def vowelreplace(self, ctx, replace, *, msg):
"""Replaces all vowels in a word with a letter"""
result = ""
for letter in msg:
if letter.lower() in "aeiou":
result += replace
else:
result += letter
await ctx.send(result)
@commands.command(pass_context=True)
async def textflip(self, ctx, *, msg):
"""Flip given text."""
result = ""
for char in msg:
if char in self.text_flip:
result += self.text_flip[char]
else:
result += char
await ctx.send(result[::-1]) # slice reverses the string
@commands.command(pass_context=True)
async def regional(self, ctx, *, msg):
"""Replace letters with regional indicator emojis"""
msg = list(msg)
regional_list = [self.regionals[x.lower()] if x.isalnum() or x in ["!", "?"] else x for x in msg]
regional_output = '\u200b'.join(regional_list)
await ctx.send(regional_output)
@commands.command(pass_context=True)
async def space(self, ctx, *, msg):
"""Add n spaces between each letter. Ex: [p]space 2 thicc"""
if msg.split(' ', 1)[0].isdigit():
spaces = int(msg.split(' ', 1)[0]) * ' '
msg = msg.split(' ', 1)[1].strip()
else:
spaces = ' '
spaced_message = spaces.join(list(msg))
await ctx.send(spaced_message)
@commands.command()
async def oof(self, ctx, msg_id:int=None, channel:discord.TextChannel=None):
"""
react 🅾🇴🇫 to a message
`msg_id` must be the message ID for desited message within the channel
`channel` must be the channel where the desired message is defaults to current channel
if the bot has manage messages permission it will attempt to delete the command
"""
emojis = ["🅾", "🇴", "🇫"]
if channel is None:
channel = ctx.message.channel
if msg_id is None:
async for message in channel.history(limit=2):
msg = message
else:
msg = await channel.get_message(msg_id)
if ctx.channel.permissions_for(ctx.me).manage_messages:
await ctx.message.delete()
if channel.permissions_for(ctx.me).add_reactions:
for emoji in emojis:
await msg.add_reaction(emoji)
# given String react_me, return a list of emojis that can construct the string with no duplicates (for the purpose of reacting)
# TODO make it consider reactions already applied to the message
@commands.command(pass_context=True, aliases=['r'])
async def react(self, ctx, msg: str, msg_id:int=None, channel:discord.TextChannel=None):
"""
Add letter(s) as reaction to previous message.
`msg` is the word you would like to react, no spaces
`msg_id` must be the message ID for desited message within the channel
`channel` must be the channel where the desired message is defaults to current channel
"""
msg = msg.lower()
if channel is None:
channel = ctx.channel
if not channel.permissions_for(ctx.me).add_reactions:
return
if msg_id is None:
async for message in channel.history(limit=2):
msg_id = message
else:
try:
msg_id = await channel.get_message(msg_id)
except:
await ctx.send("Message ID {} not found in {}".format(msg_id, channel.mention))
return
limit = 25 if msg_id else 2
reactions = []
non_unicode_emoji_list = []
react_me = "" # this is the string that will hold all our unicode converted characters from msg
# replace all custom server emoji <:emoji:123456789> with "<" and add emoji ids to non_unicode_emoji_list
char_index = 0
emotes = re.findall(r"<a?:(?:[a-zA-Z0-9]+?):(?:[0-9]+?)>", msg)
react_me = re.sub(r"<a?:([a-zA-Z0-9]+?):([0-9]+?)>", "", msg)
for emote in emotes:
reactions.append(discord.utils.get(self.bot.emojis, id=int(emote.split(":")[-1][:-1])))
non_unicode_emoji_list.append(emote)
if Fun.has_dupe(non_unicode_emoji_list):
return await ctx.send(
"You requested that I react with at least two of the exact same specific emoji. I'll try to find alternatives for alphanumeric text, but if you specify a specific emoji must be used, I can't help.")
react_me_original = react_me # we'll go back to this version of react_me if prefer_combine is false but we can't make the reaction happen unless we combine anyway.
if Fun.has_dupe(react_me): # there's a duplicate letter somewhere, so let's go ahead try to fix it.
react_me = Fun.replace_combos(react_me)
react_me = Fun.replace_letters(react_me)
# print(react_me)
if Fun.has_dupe(react_me): # check if we were able to solve the dupe
react_me = react_me_original
react_me = Fun.replace_combos(react_me)
react_me = Fun.replace_letters(react_me)
if Fun.has_dupe(react_me): # this failed too, so there's really nothing we can do anymore.
return await ctx.send("Failed to fix all duplicates. Cannot react with this string.")
lt_count = 0
for char in react_me:
if char not in "0123456789": # these unicode characters are weird and actually more than one character.
if char != '⃣': # </3
reactions.append(char)
else:
reactions.append(self.emoji_dict[char][0])
else: # probably doesn't matter, but by treating the case without dupes seperately, we can save some time
lt_count = 0
for char in react_me:
if char in "abcdefghijklmnopqrstuvwxyz0123456789!?":
reactions.append(self.emoji_dict[char][0])
else:
reactions.append(char)
for i in reactions:
await msg_id.add_reaction(i)
+23
View File
@@ -0,0 +1,23 @@
{
"author":[
"Appu",
"TrustyJAID"
],
"description":"All sorts of commands that users may find fun or useful",
"install_msg":"Type `[p]help` to see all the commands.",
"min_python_version":[
3,
6,
2
],
"name":"Fun",
"permissions":[
"add_reactions"
],
"requirements":[],
"short":"Various fun commands like react, textflip, and regional",
"tags":[
"general",
"fun"
]
}
+5
View File
@@ -0,0 +1,5 @@
from .gabai import Gabai
def setup(bot):
n = Gabai(bot)
bot.add_cog(n)
+257
View File
@@ -0,0 +1,257 @@
import discord
from redbot.core import commands, checks, Config
import asyncio
import aiohttp
from datetime import datetime
from .gabuser import GabUser
__version__ = "2.0.1"
__author__ = "TrustyJAID"
BASE_URL = "https://api.gab.com/v1.0/"
class GabaiError(Exception):
pass
class NotFoundError(GabaiError):
pass
class Gabai(getattr(commands, "Cog", object)):
"""
Get information from gab.ai and display on discord
"""
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 17864784635)
default_global = {"api_token":{"client_id":"", "client_secret":"", "token":{}, "refresh_time":0}}
self.config.register_global(**default_global)
self.session = aiohttp.ClientSession(loop=self.bot.loop)
self.rate_limit_remaining = 60
self.rate_limit_time = 0
@commands.group(pass_context=True)
async def gab(self, ctx):
"""
Add your gab tag to receive the role Anonymous
"""
pass
async def refresh_token(self):
api_token = await self.config.api_toke()
params = {
"grant_type": "refresh_token",
"refresh_token": api_token["token"]["refresh_token"],
"client_id": api_token["client_id"],
"client_secret": api_token["client_secret"],
"scope": "read engage-user engage-post write-post notifications"
}
async with self.session.post("https://api.gab.com/oauth/token", json=params) as resp:
token = await resp.json()
await self.config.api_token.token.set(token)
await self.config.api_token.refresh_time.set(token["expires_in"]+datetime.now().timestamp())
async def get_header(self):
access_token = await self.config.api_token.token.access_token()
return {"Authorization":"Bearer {}".format(access_token)}
async def check_rate_limit(self):
"""Current rate limit is 60 calls per minute"""
time_now = int(datetime.now().timestamp())
if self.rate_limit_remaining == 60:
self.rate_limit_time = int(datetime.now().timestamp())
self.rate_limit_remaining -= 1
return
if self.rate_limit_remaining != 0:
self.rate_limit_remaining -= 1
return
else:
if time_now > (self.rate_limit_time+60):
self.rate_limit_remaining = 59
self.rate_limit_time = time_now
else:
await asyncio.sleep(self.rate_limit_time+60-time_now)
async def get_gab_response(self, url, params=None):
await self.check_rate_limit()
header = await self.get_header()
async with self.session.get(BASE_URL+url, params=params, headers=header) as resp:
response = await resp.json()
if "status" in response:
raise NotFoundError(response["message"])
else:
return response
async def make_user_embed(self, user:GabUser):
url = "https://gab.ai/{}".format(user.username)
em = discord.Embed(description=user.bio[:1990], title=user.name, colour=int("4bd079", 16))
em.set_author(name=user.username, url=url, icon_url=user.picture_url_full)
em.set_thumbnail(url=user.picture_url_full)
em.add_field(name="Followers", value=user.follower_count)
em.add_field(name="Following", value=user.following_count)
em.add_field(name="Score", value=user.score)
acknowledgements = ""
if user.is_pro:
acknowledgements += "Pro, "
if user.verified:
acknowledgements += "Verified, "
if user.is_donor:
acknowledgements += "Donor, "
if user.is_investor:
acknowledgements += "Investor, "
if acknowledgements != "":
em.add_field(name="Acknowledgements", value=acknowledgements[:-2])
# em.set_image(url=user.cover_url)
return em
async def make_post_embed(self, post:dict):
username = post["actuser"]["username"]
post_id = post["post"]["id"]
url = "https://gab.ai/{}/posts/{}".format(username, post_id)
timestamp = datetime.strptime(post["post"]["created_at"], "%Y-%m-%dT%H:%M:%S+00:00")
attachment = post["post"]["attachment"]["type"]
colour = int("4bd079", 16)
likes = post["post"]["like_count"]
replies = post["post"]["reply_count"]
em = discord.Embed(description= post["post"]["body"], timestamp=timestamp, colour=colour)
if attachment is not None:
if attachment != "media":
em.set_image(url=post["post"]["attachment"]["value"])
else:
em.set_image(url=post["post"]["attachment"]["value"][0]["url_full"])
em.set_author(name=post["actuser"]["username"], url=url, icon_url=post["actuser"]["picture_url"])
em.set_footer(text="{} Likes | {} Replies | Created at".format(likes, replies))
return em
async def gab_menu(self, ctx:commands.Context, post_list: list,
message: discord.Message=None,
page=0, timeout: int=30):
"""menu control logic for this taken from
https://github.com/Lunar-Dust/Dusty-Cogs/blob/master/menu/menu.py"""
post = post_list[page]
if ctx.channel.permissions_for(ctx.me).embed_links:
em = await self.make_post_embed(post)
else:
await ctx.send("I need embed_links permission to use this command.")
return
if not message:
message = await ctx.send(embed=em)
await message.add_reaction("⬅")
await message.add_reaction("❌")
await message.add_reaction("➡")
else:
# message edits don't return the message object anymore lol
await message.edit(embed=em)
check = lambda react, user:user == ctx.message.author and react.emoji in ["➡", "⬅", "❌"] and react.message.id == message.id
try:
react, user = await ctx.bot.wait_for("reaction_add", check=check, timeout=timeout)
except asyncio.TimeoutError:
await message.remove_reaction("⬅", ctx.me)
await message.remove_reaction("❌", ctx.me)
await message.remove_reaction("➡", ctx.me)
return None
else:
if react.emoji == "➡":
next_page = 0
if page == len(post_list) - 1:
next_page = 0 # Loop around to the first item
else:
next_page = page + 1
if ctx.channel.permissions_for(ctx.me).manage_messages:
await message.remove_reaction("➡", ctx.message.author)
return await self.gab_menu(ctx, post_list, message=message,
page=next_page, timeout=timeout)
elif react.emoji == "⬅":
next_page = 0
if page == 0:
next_page = len(post_list) - 1 # Loop around to the last item
else:
next_page = page - 1
if ctx.channel.permissions_for(ctx.me).manage_messages:
await message.remove_reaction("⬅", ctx.message.author)
return await self.gab_menu(ctx, post_list, message=message,
page=next_page, timeout=timeout)
else:
return await message.delete()
@gab.command()
async def feed(self, ctx, username:str, before_date:str=None):
"""
Gets a users feed from gab.ai before a specified date
before_date must be in format DD-MM-YYYY
"""
await ctx.trigger_typing()
if before_date is None:
before_date = datetime.now().strftime("%Y-%m-%dT%H:%M%S%z")
else:
before_date = datetime.strptime(before_date, "%d-%m-%Y").strftime("%Y-%m-%dT%H:%M:%S+00:00")
try:
feed_info = await self.get_gab_response(f"users/{username}/feed/", {"before":before_date})
except NotFoundError as e:
await ctx.send("{} {}".format(username, e))
return
await self.gab_menu(ctx, feed_info["data"])
@gab.command()
async def user(self, ctx, username:str):
"""
Get user information from gab.ai
"""
await ctx.trigger_typing()
try:
user_info = await self.get_gab_response(f"users/{username}")
except NotFoundError as e:
await ctx.send("{} {}".format(username, e))
return
user = GabUser.from_json(user_info)
em = await self.make_user_embed(user)
await ctx.send(embed=em)
@gab.command()
@checks.is_owner()
async def token(self, ctx, client_id:str, client_secret:str):
"""
Provide your client_id and client_secret
1. go to https://gab.ai/settings/clients then Developer Apps
2. Select Create app
3. Fillout the form and set the redirect url to https://localhost
4. Provide the client_id and client_secret
5. The bot will provide a link and ask for the code
6. post everything after `?code=` in discord
"""
await self.config.api_token.client_id.set(client_id)
await self.config.api_token.client_secret.set(client_secret)
url = f"https://api.gab.com/oauth/authorize?response_type=code&client_id={client_id}&redirect_uri=https://localhost&scope=%20read%20engage-user%20engage-post%20write-post%20notifications"
await ctx.send("Please go to the following url and provide the code supplied: {}".format(url))
check = lambda m: m.author.id == ctx.message.author.id
code = await self.bot.wait_for("message", check=check)
params = {
"grant_type": "authorization_code",
"code": code.content,
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": "https://localhost"
}
async with self.session.post("https://api.gab.com/oauth/token", json=params) as resp:
token = await resp.json()
if "error" in token:
await ctx.send(token["message"]+ "\n\nMaybe try again/")
return
await self.config.api_token.token.set(token)
await self.config.api_token.refresh_time.set(token["expires_in"]+datetime.now().timestamp())
await ctx.send("API Tokens set!")
def __unload(self):
self.bot.loop.create_task(self.session.close())
+70
View File
@@ -0,0 +1,70 @@
class GabUser:
def __init__(self, user_id:int, created_at_month_label:str, name:str, username:str, follower_count:int,
following_count:int, post_count:int, picture_url:str, picture_url_full:str,
following:bool, followed:bool, verified:bool, is_pro:bool, is_donor:bool,
is_investor:bool, is_premium:bool, is_tippable:bool, is_private:bool,
is_accessible:bool, follow_pending:bool, bio:str, cover_url:str, score:int,
video_count:int, is_favorited:bool, subscribing:bool, is_muted:bool, distribution:list):
self.user_id = user_id
self.created_at_month_label = created_at_month_label
self.name = name
self.username = username
self.follower_count = follower_count
self.following_count = following_count
self.post_count = post_count
self.picture_url = picture_url
self.picture_url_full = picture_url_full
self.following = following
self.followed = followed
self.verified = verified
self.is_pro = is_pro
self.is_donor = is_donor
self.is_investor = is_investor
self.is_premium = is_premium
self.is_tippable = is_tippable
self.is_private = is_private
self.is_accessible = is_accessible
self.follow_pending = follow_pending
self.bio = bio
self.cover_url = cover_url
self.score = score
self.video_count = video_count
self.is_favorited = is_favorited
self.subscribing = subscribing
self.is_muted = is_muted
self.distribution = distribution
@classmethod
def from_json(cls, data:dict):
return cls(data["id"],
data["created_at_month_label"],
data["name"],
data["username"],
data["follower_count"],
data["following_count"],
data["post_count"],
data["picture_url"],
data["picture_url_full"],
data["following"],
data["followed"],
data["verified"],
data["is_pro"],
data["is_donor"],
data["is_investor"],
data["is_premium"],
data["is_tippable"],
data["is_private"],
data["is_accessible"],
data["follow_pending"],
data["bio"],
data["cover_url"],
data["score"],
data["video_count"],
data["is_favorited"],
data["subscribing"],
data["is_muted"],
data["distribution"])
+20
View File
@@ -0,0 +1,20 @@
{
"author":[
"TrustyJAID"
],
"description":"Get information from gab.ai's API and display in discord.",
"install_msg":"Thanks for installing, remember to set your gab API credentials with `[p]gab token` and follow the instructions.",
"min_python_version":[
3,
6,
2
],
"name":"Gabai",
"permissions":[],
"requirements":[],
"short":"Gab.ai information",
"tags":[
"general",
"utility"
]
}
+4
View File
@@ -0,0 +1,4 @@
from .halo import Halo
def setup(bot):
bot.add_cog(Halo(bot))
+220
View File
@@ -0,0 +1,220 @@
import discord
import aiohttp
from redbot.core import commands
from redbot.core import Config
from redbot.core import checks
from random import choice as randchoice
numbs = {
"next": "➡",
"back": "⬅",
"exit": "❌"
}
class Halo(getattr(commands, "Cog", object)):
"""
Display Halo 5 and Halo Wars 2 stats and information
"""
def __init__(self, bot):
self.bot = bot
self.session = aiohttp.ClientSession(loop=self.bot.loop)
default_global = {"api_token":{"token": "",
"language": "en"}}
self.config = Config.get_conf(self, 35689771456)
self.config.register_global(**default_global)
async def request_url(self, url, params=None):
header_data = await self.config.api_token()
header = {"Ocp-Apim-Subscription-Key": header_data["token"], "Accept-Language":header_data["language"]}
async with self.session.get(url, params=params, headers=header) as resp:
return await resp.json()
@commands.group(pass_context=True, name='halo5')
@checks.admin_or_permissions(manage_server=True)
async def _halo5(self, ctx):
"""Get information from Halo 5"""
pass
@commands.group(pass_context=True, name='halowars')
@checks.admin_or_permissions(manage_server=True)
async def _halowars(self, ctx):
"""Get information from Halo Wars 2"""
pass
def random_colour(self):
return int(''.join([randchoice('0123456789ABCDEF')for x in range(6)]), 16)
async def halo5_playlist_menu(self, ctx, post_list: list,
message: discord.Message=None,
page=0, timeout: int=30):
"""menu control logic for this taken from
https://github.com/Lunar-Dust/Dusty-Cogs/blob/master/menu/menu.py"""
s = post_list[page]
created_at = ctx.message.created_at
desc = "Created at: {}".format(created_at)
em = discord.Embed(title=s["name"],
description=s["description"],
colour=discord.Colour(value=self.random_colour()),
timestamp=created_at)
em.add_field(name="Gamemode", value=s["gameMode"])
em.add_field(name="Ranked", value=str(s["isRanked"]))
if s["imageUrl"] is not None:
em.set_image(url=s["imageUrl"])
if not message:
message =\
await ctx.send(embed=em)
await message.add_reaction("⬅")
await message.add_reaction("❌")
await message.add_reaction("➡")
else:
# message edits don't return the message object anymore lol
await message.edit(embed=em)
check = lambda react, user:user == ctx.message.author and react.emoji in ["➡", "⬅", "❌"]
try:
react, user = await self.bot.wait_for("reaction_add", check=check, timeout=timeout)
except asyncio.TimeoutError:
await message.remove_reaction("⬅", self.bot.user)
await message.remove_reaction("❌", self.bot.user)
await message.remove_reaction("➡", self.bot.user)
return None
else:
reacts = {v: k for k, v in numbs.items()}
react = reacts[react.emoji]
if react == "next":
next_page = 0
if page == len(post_list) - 1:
next_page = 0 # Loop around to the first item
else:
next_page = page + 1
return await self.halo5_playlist_menu(ctx, post_list, message=message,
page=next_page, timeout=timeout)
elif react == "back":
next_page = 0
if page == 0:
next_page = len(post_list) - 1 # Loop around to the last item
else:
next_page = page - 1
return await self.halo5_playlist_menu(ctx, post_list, message=message,
page=next_page, timeout=timeout)
else:
return await message.delete()
@_halo5.command(pass_context=True, name="playlist")
async def halo5_playlist(self, ctx, active=True):
"""Gathers data about active Halo 5 playlists"""
data = await self.request_url("https://www.haloapi.com/metadata/h5/metadata/playlists")
list_active = []
for playlist in data:
if playlist["isActive"]:
list_active.append(playlist)
await self.halo5_playlist_menu(ctx, list_active)
async def halowars_playlist_menu(self, ctx, post_list: list,
message: discord.Message=None,
page=0, timeout: int=30):
"""menu control logic for this taken from
https://github.com/Lunar-Dust/Dusty-Cogs/blob/master/menu/menu.py"""
s = post_list[page]
created_at = ctx.message.created_at
desc = "Created at: {}".format(created_at)
em = discord.Embed(title=s["View"]["Title"],
# description=s["description"],
colour=discord.Colour(value=self.random_colour()),
timestamp=created_at)
# em.add_field(name="Gamemode", value=s["gameMode"])
# em.add_field(name="Ranked", value=str(s["isRanked"]))
# if s["HW2Playlist"][] is not None:
em.set_image(url=s["View"]["HW2Playlist"]["Image"]["View"]["Media"]["MediaUrl"])
if not message:
message =\
await ctx.send(embed=em)
await message.add_reaction("⬅")
await message.add_reaction("❌")
await message.add_reaction("➡")
else:
# message edits don't return the message object anymore lol
await message.edit(embed=em)
check = lambda react, user:user == ctx.message.author and react.emoji in ["➡", "⬅", "❌"]
try:
react, user = await self.bot.wait_for("reaction_add", check=check, timeout=timeout)
except asyncio.TimeoutError:
await message.remove_reaction("⬅", self.bot.user)
await message.remove_reaction("❌", self.bot.user)
await message.remove_reaction("➡", self.bot.user)
return None
else:
reacts = {v: k for k, v in numbs.items()}
react = reacts[react.emoji]
if react == "next":
next_page = 0
if page == len(post_list) - 1:
next_page = 0 # Loop around to the first item
else:
next_page = page + 1
return await self.halowars_playlist_menu(ctx, post_list, message=message,
page=next_page, timeout=timeout)
elif react == "back":
next_page = 0
if page == 0:
next_page = len(post_list) - 1 # Loop around to the last item
else:
next_page = page - 1
return await self.halowars_playlist_menu(ctx, post_list, message=message,
page=next_page, timeout=timeout)
else:
return await message.delete()
async def get_halo5_rank_data(self, designation_id, tier_id):
rank_data = await self.request_url("https://www.haloapi.com/metadata/h5/metadata/csr-designations")
designation = [x for x in rank_data if x["id"] == str(designation_id)]
image_url = [x["iconImageUrl"] for x in designation[0]["tiers"] if x["id"] == str(tier_id)]
return designation[0]["name"], image_url
@_halo5.command(pass_context=True, name="rank")
async def Halo5_rank(self, ctx, *, gamertag):
"""Gather playter rank information from Halo 5"""
colours = {"Unranked": "7f7f7f", "Bronze": "c27c0e", "Silver": "cccccc", "Gold": "xf1c40f",
"Platinum": "e5e5e5", "Diamond": "ffffff", "Onyx": "000000", "Champion": "71368a"}
player_data = await self.request_url("https://www.haloapi.com/stats/h5/servicerecords/arena?", {"players":gamertag})
tier = player_data["Results"][0]["Result"]["ArenaStats"]["HighestCsrAttained"]["Tier"]
designation = player_data["Results"][0]["Result"]["ArenaStats"]["HighestCsrAttained"]["DesignationId"]
designation_name, image_url = await self.get_halo5_rank_data(designation, tier)
embed = discord.Embed(title=gamertag,
description=designation_name,
colour=discord.Colour(value=int(colours[designation_name], 16)),
timestamp=ctx.message.created_at)
embed.add_field(name="Designation", value=str(designation), inline=True)
embed.add_field(name="Tier", value=str(tier), inline=True)
embed.set_thumbnail(url=image_url[0])
await ctx.send(embed=embed)
@_halowars.command(pass_context=True, name="playlist")
async def halowars_playlist(self, ctx, active=True):
"""Gathers data about active Halo 5 playlists"""
data = await self.request_url("https://www.haloapi.com/metadata/hw2/playlists")
list_active = []
for playlist in data["ContentItems"]:
# print(playlist)
if not playlist["View"]["HW2Playlist"]["Hide"]:
list_active.append(playlist)
await self.halowars_playlist_menu(ctx, list_active)
@commands.group(pass_context=True, name='haloset')
@checks.admin_or_permissions(manage_server=True)
async def _haloset(self, ctx):
"""Command for setting required access information for the API.
To get this info, visit https://developer.haloapi.com and create a new application."""
pass
@_haloset.command(pass_context=True)
async def tokens(self, ctx, subscription_key, language="en"):
"""Set the tokens and language for requests from the API"""
await self.config.api_token.token.set(subscription_key)
await self.config.api_token.language.set(language)
await ctx.send("Halo API credentials set!")
def __unload(self):
self.bot.loop.create_task(self.session.close())
+19
View File
@@ -0,0 +1,19 @@
{
"author":[
"TrustyJAID"
],
"description":"Gathers information from the Halo API and posts it on discord.",
"install_msg":"Set your API key from https://developer.haloapi.com and access different stats from Halo 5 and Halo Wars 2.",
"min_python_version":[
3,
6,
2
],
"name":"Halo",
"permissions":[],
"requirements":[],
"short":"halo",
"tags":[
"general"
]
}
+4
View File
@@ -0,0 +1,4 @@
from .hockey import Hockey
def setup(bot):
bot.add_cog(Hockey(bot))
+425
View File
@@ -0,0 +1,425 @@
BASE_URL = "https://statsapi.web.nhl.com"
HEADSHOT_URL = "https://nhl.bamcontent.com/images/headshots/current/168x168/{}.jpg"
CONFIG_ID = 13457745779
TEAMS = {
"Anaheim Ducks" : {
"away" : "#F95602",
"conference" : "Western",
"division" : "Pacific",
"emoji" : "AnaheimDucks:381568940108939265",
"home" : "#B5985A",
"id" : 24,
"invite" : "https://discord.gg/Pqf9W6M",
"logo" : "https://nhl.bamcontent.com/images/photos/281720124/256x256/cut.png",
"team_url" : "http://www.anaheimducks.com",
"timezone" : "US/Pacific"
},
"Arizona Coyotes" : {
"away" : "#E2D6B5",
"conference" : "Western",
"division" : "Pacific",
"emoji" : "ArizonaCoyotes:381568940083511297",
"home" : "#8C2633",
"id" : 53,
"invite" : "https://discord.gg/dguBmGm",
"logo" : "https://nhl.bamcontent.com/images/photos/281720888/256x256/cut.png",
"team_url" : "http://www.arizonacoyotes.com",
"timezone" : "US/Arizona"
},
"Boston Bruins" : {
"away" : "#111111",
"conference" : "Eastern",
"division" : "Atlantic",
"emoji" : "BostonBruins:381568939857149954",
"home" : "#FCB514",
"id" : 6,
"invite" : "https://discord.gg/BbPN25d",
"logo" : "https://nhl.bamcontent.com/images/photos/281719378/256x256/cut.png",
"team_url" : "https://www.youtube.com/watch?v=1RCjTRXRk1Y",
"timezone" : "US/Eastern"
},
"Buffalo Sabres" : {
"away" : "#FCB514",
"conference" : "Eastern",
"division" : "Atlantic",
"emoji" : "BuffaloSabres:381568940658130944",
"home" : "#002654",
"id" : 7,
"invite" : "https://discord.gg/zbDhqmt",
"logo" : "https://nhl.bamcontent.com/images/photos/281723274/256x256/cut.png",
"team_url" : "http://www.sabres.com",
"timezone" : "US/Eastern"
},
"Calgary Flames" : {
"away" : "#F1BE48",
"conference" : "Western",
"division" : "Pacific",
"emoji" : "CalgaryFlames:381568940314460171",
"home" : "#B72B35",
"id" : 20,
"invite" : "https://discord.gg/PAZsyWE",
"logo" : "https://nhl.bamcontent.com/images/photos/281720898/256x256/cut.png",
"team_url" : "http://www.calgaryflames.com",
"timezone" : "US/Mountain"
},
"Carolina Hurricanes" : {
"away" : "#A4A9AD",
"conference" : "Eastern",
"division" : "Metropolitan",
"emoji" : "CarolinaHurricanes:381568942436646914",
"home" : "#B72B35",
"id" : 12,
"invite" : "https://discord.gg/mqGDdrr",
"logo" : "https://nhl.bamcontent.com/images/photos/281726500/256x256/cut.png",
"team_url" : "http://www.carolinahurricanes.com",
"timezone" : "US/Eastern"
},
"Chicago Blackhawks" : {
"away" : "#000000",
"conference" : "Western",
"division" : "Central",
"emoji" : "ChicagoBlackhawks:381568943279702036",
"home" : "#CF0A2C",
"id" : 16,
"invite" : "https://discord.gg/DkuRmj7",
"logo" : "https://nhl.bamcontent.com/images/photos/281726514/256x256/cut.png",
"team_url" : "http://www.chicagoblackhawks.com",
"timezone" : "US/Central"
},
"Colorado Avalanche" : {
"away" : "#236192",
"conference" : "Western",
"division" : "Central",
"emoji" : "ColoradoAvalanche:381568943170519040",
"home" : "#6F263D",
"id" : 21,
"invite" : "https://discord.gg/tamwt88",
"logo" : "https://nhl.bamcontent.com/images/photos/281721016/256x256/cut.png",
"team_url" : "http://www.coloradoavalanche.com",
"timezone" : "US/Mountain"
},
"Columbus Blue Jackets" : {
"away" : "#CE1126",
"conference" : "Eastern",
"division" : "Metropolitan",
"emoji" : "ColumbusBlueJackets:381568942839300107",
"home" : "#041E42",
"id" : 29,
"invite" : "https://discord.gg/wJKdYtG",
"logo" : "https://nhl.bamcontent.com/images/photos/281726518/256x256/cut.png",
"team_url" : "http://www.bluejackets.com",
"timezone" : "US/Eastern"
},
"Dallas Stars" : {
"away" : "#8F8F8C",
"conference" : "Western",
"division" : "Central",
"emoji" : "DallasStars:381568942520664065",
"home" : "#006847",
"id" : 25,
"invite" : "https://discord.gg/KzxfCH4",
"logo" : "https://nhl.bamcontent.com/images/photos/281726660/256x256/cut.png",
"team_url" : "http://www.dallasstars.com",
"timezone" : "US/Central"
},
"Detroit Red Wings" : {
"away" : "#FFFFFF",
"conference" : "Eastern",
"division" : "Atlantic",
"emoji" : "DetroitRedWings:381568943162130442",
"home" : "#C8102E",
"id" : 17,
"invite" : "https://discord.gg/zp9WjV9",
"logo" : "https://nhl.bamcontent.com/images/photos/281723286/256x256/cut.png",
"team_url" : "http://www.detroitredwings.com",
"timezone" : "US/Eastern"
},
"Edmonton Oilers" : {
"away" : "#041E41",
"conference" : "Western",
"division" : "Pacific",
"emoji" : "EdmontonOilers:381568942721728513",
"home" : "#FF4C00",
"id" : 22,
"invite" : "https://discord.gg/6XKZyxy",
"logo" : "https://nhl.bamcontent.com/images/photos/281721030/256x256/cut.png",
"team_url" : "https://youtu.be/xXwkD8N8TjY?t=1m3s",
"timezone" : "US/Mountain"
},
"Florida Panthers" : {
"away" : "#041E42",
"conference" : "Eastern",
"division" : "Atlantic",
"emoji" : "FloridaPanthers:381568943137095680",
"home" : "#C8102E",
"id" : 13,
"invite" : "https://discord.gg/cedDpzj",
"logo" : "https://nhl.bamcontent.com/images/photos/281723310/256x256/cut.png",
"team_url" : "http://www.floridapanthers.com",
"timezone" : "US/Eastern"
},
"Los Angeles Kings" : {
"away" : "#B2B7BB",
"conference" : "Western",
"division" : "Pacific",
"emoji" : "LosAngelesKings:381568942105296898",
"home" : "#111111",
"id" : 26,
"invite" : "https://discord.gg/H6EH73h",
"logo" : "https://nhl.bamcontent.com/images/photos/281721042/256x256/cut.png",
"team_url" : "http://www.lakings.com",
"timezone" : "US/Mountain"
},
"Minnesota Wild" : {
"away" : "#C51230",
"conference" : "Western",
"division" : "Central",
"emoji" : "MinnesotaWild:381568942596030475",
"home" : "#004F30",
"id" : 30,
"invite" : "https://discord.gg/CT2HUUV",
"logo" : "https://nhl.bamcontent.com/images/photos/281721058/256x256/cut.png",
"team_url" : "http://www.wild.com",
"timezone" : "US/Central"
},
"Montr\u00e9al Canadiens" : {
"away" : "#192168",
"conference" : "Eastern",
"division" : "Atlantic",
"emoji" : "MontrealCanadiens:381568942486847491",
"home" : "#AF1E2D",
"id" : 8,
"invite" : "https://discord.gg/rhabs",
"logo" : "https://nhl.bamcontent.com/images/photos/281723300/256x256/cut.png",
"team_url" : "https://www.youtube.com/watch?v=9YFtlvDOVVE",
"timezone" : "US/Eastern"
},
"Nashville Predators" : {
"away" : "#041E42",
"conference" : "Western",
"division" : "Central",
"emoji" : "NashvillePredators:381568942944157706",
"home" : "#FFB81C",
"id" : 18,
"invite" : "https://discord.gg/Z7DF8zE",
"logo" : "https://nhl.bamcontent.com/images/photos/281721070/256x256/cut.png",
"team_url" : "http://www.nashvillepredators.com",
"timezone" : "US/Central"
},
"New Jersey Devils" : {
"away" : "#000000",
"conference" : "Eastern",
"division" : "Metropolitan",
"emoji" : "NewJerseyDevils:381568942537179138",
"home" : "#E03A3E",
"id" : 1,
"invite" : "https://discord.gg/4TtS8m4",
"logo" : "https://nhl.bamcontent.com/images/photos/281726626/256x256/cut.png",
"team_url" : "http://www.truesince82.com",
"timezone" : "US/Eastern"
},
"New York Islanders" : {
"away" : "#F47920",
"conference" : "Eastern",
"division" : "Metropolitan",
"emoji" : "NewYorkIslanders:381568942948352011",
"home" : "#00529B",
"id" : 2,
"invite" : "https://discord.gg/MSHNyqB",
"logo" : "https://nhl.bamcontent.com/images/photos/281726632/256x256/cut.png",
"team_url" : "http://www.newyorkislanders.com",
"timezone" : "US/Eastern"
},
"New York Rangers" : {
"away" : "#C8102E",
"conference" : "Eastern",
"division" : "Metropolitan",
"emoji" : "NewYorkRangers:381568942898151435",
"home" : "#0038A8",
"id" : 3,
"invite" : "https://discord.gg/zDWnpHM",
"logo" : "https://nhl.bamcontent.com/images/photos/281718864/256x256/cut.png",
"team_url" : "http://www.newyorkrangers.com",
"timezone" : "US/Eastern"
},
"Ottawa Senators" : {
"away" : "#CBA044",
"conference" : "Eastern",
"division" : "Atlantic",
"emoji" : "OttawaSenators:381568942776254475",
"home" : "#E31837",
"id" : 9,
"invite" : "https://discord.gg/VQzYRKP",
"logo" : "https://nhl.bamcontent.com/images/photos/281723314/256x256/cut.png",
"team_url" : "http://www.ottawasenators.com",
"timezone" : "US/Eastern"
},
"Philadelphia Flyers" : {
"away" : "#000000",
"conference" : "Eastern",
"division" : "Metropolitan",
"emoji" : "PhiladelphiaFlyers:381568942004764673",
"home" : "#F74902",
"id" : 4,
"invite" : "https://discord.gg/U5PdQaA",
"logo" : "https://nhl.bamcontent.com/images/photos/281726640/256x256/cut.png",
"team_url" : "http://www.philadelphiaflyers.com",
"timezone" : "US/Eastern"
},
"Pittsburgh Penguins" : {
"away" : "#CFC493",
"conference" : "Eastern",
"division" : "Metropolitan",
"emoji" : "PittsburghPenguins:381568942587510796",
"home" : "#FCB514",
"id" : 5,
"invite" : "https://discord.gg/nZ2vuWj",
"logo" : "https://nhl.bamcontent.com/images/photos/281726648/256x256/cut.png",
"team_url" : "https://www.youtube.com/watch?v=lDw7GqD_xro",
"timezone" : "US/Eastern"
},
"San Jose Sharks" : {
"away" : "#EA7200",
"conference" : "Western",
"division" : "Pacific",
"emoji" : "SanJoseSharks:381568942864334848",
"home" : "#006D75",
"id" : 28,
"invite" : "https://discord.gg/X9Xr8Zn",
"logo" : "https://nhl.bamcontent.com/images/photos/281721090/256x256/cut.png",
"team_url" : "http://www.sjsharks.com",
"timezone" : "US/Pacific"
},
"St. Louis Blues" : {
"away" : "#FCB514",
"conference" : "Western",
"division" : "Central",
"emoji" : "StLouisBlues:381568942474526724",
"home" : "#002F87",
"id" : 19,
"invite" : "https://discord.gg/013pcvc9v5MCl64Ic",
"logo" : "https://nhl.bamcontent.com/images/photos/281752302/256x256/cut.png",
"team_url" : "http://www.stlouisblues.com",
"timezone" : "US/Central"
},
"Tampa Bay Lightning" : {
"away" : "#FFFFFF",
"conference" : "Eastern",
"division" : "Atlantic",
"emoji" : "TampaBayLightning:381568942054834196",
"home" : "#002868",
"id" : 14,
"invite" : "https://discord.gg/PZ3bDJA",
"logo" : "https://nhl.bamcontent.com/images/photos/281723320/256x256/cut.png",
"team_url" : "https://www.youtube.com/watch?v=UjbdFKsHD_M",
"timezone" : "US/Eastern"
},
"Team Atlantic" : {
"away" : "#fef5aa",
"conference" : "",
"division" : "",
"emoji" : "Atlantic:406575132895739924",
"home" : "#032c88",
"id" : 87,
"invite" : "",
"logo" : "https://i.imgur.com/I1NWsss.png",
"team_url" : "http://nhl.coms.com",
"timezone" : "US/Eastern"
},
"Team Central" : {
"away" : "#111111",
"conference" : "",
"division" : "",
"emoji" : "Central:406575132656533516",
"home" : "#ff6668",
"id" : 89,
"invite" : "",
"logo" : "https://i.imgur.com/Adrh7aD.png",
"team_url" : "http://nhl.coms.com",
"timezone" : "US/Central"
},
"Team Metropolitan" : {
"away" : "#d1cad2",
"conference" : "",
"division" : "",
"emoji" : "Metropolitan:406575133113712640",
"home" : "#f6e98b",
"id" : 88,
"invite" : "",
"logo" : "https://i.imgur.com/l4nxmZx.png",
"team_url" : "http://nhl.coms.com",
"timezone" : "US/Mountain"
},
"Team Pacific" : {
"away" : "#FFFFFF",
"conference" : "",
"division" : "",
"emoji" : "Pacific:406575133096935437",
"home" : "#ff2734",
"id" : 90,
"invite" : "",
"logo" : "https://i.imgur.com/e5a4y36.png",
"team_url" : "http://nhl.coms.com",
"timezone" : "US/Pacific"
},
"Toronto Maple Leafs" : {
"away" : "#FFFFFF",
"conference" : "Eastern",
"division" : "Atlantic",
"emoji" : "TorontoMapleLeafs:381568943011135488",
"home" : "#003E7E",
"id" : 10,
"invite" : "https://discord.gg/VwDTAhk",
"logo" : "https://nhl.bamcontent.com/images/photos/281723324/256x256/cut.png",
"team_url" : "http://www.mapleleafs.com",
"timezone" : "US/Eastern"
},
"Vancouver Canucks" : {
"away" : "#008852",
"conference" : "Western",
"division" : "Pacific",
"emoji" : "VancouverCanucks:381568942914928641",
"home" : "#001F5C",
"id" : 23,
"invite" : "https://discord.gg/UTZ5Vrb",
"logo" : "https://nhl.bamcontent.com/images/photos/281721212/256x256/cut.png",
"team_url" : "http://www.canucks.com",
"timezone" : "US/Pacific"
},
"Vegas Golden Knights" : {
"away" : "#333F42",
"conference" : "Western",
"division" : "Pacific",
"emoji" : "VegasGoldenKnights:381568942465875970",
"home" : "#B4975A",
"id" : 54,
"invite" : "https://discord.gg/dMKq7RH",
"logo" : "https://nhl.bamcontent.com/images/photos/284409696/256x256/cut.png",
"team_url" : "https://www.youtube.com/watch?v=QrctmCqhq6o",
"timezone" : "US/Pacific"
},
"Washington Capitals" : {
"away" : "#CF0A2C",
"conference" : "Eastern",
"division" : "Metropolitan",
"emoji" : "WashingtonCapitals:381568942541373440",
"home" : "#041E41",
"id" : 15,
"invite" : "https://discord.gg/CbjPuTM",
"logo" : "https://nhl.bamcontent.com/images/photos/281726654/256x256/cut.png",
"team_url" : "http://www.washingtoncapitals.com",
"timezone" : "US/Eastern"
},
"Winnipeg Jets" : {
"away" : "#AC162C",
"conference" : "Western",
"division" : "Central",
"emoji" : "WinnipegJets:381568942700888065",
"home" : "#041E41",
"id" : 52,
"invite" : "https://discord.gg/tbyU5KF",
"logo" : "https://nhl.bamcontent.com/images/photos/281723512/256x256/cut.png",
"team_url" : "https://www.youtube.com/watch?v=jJnj0-aX_es",
"timezone" : "US/Central"
}
}
+83
View File
@@ -0,0 +1,83 @@
import discord
import aiohttp
from datetime import datetime
from .constants import BASE_URL, TEAMS, HEADSHOT_URL
from .helper import *
from .standings import Standings
from redbot.core.i18n import Translator
_ = Translator("Hockey", __file__)
async def make_rules_embed(guild, team, rules):
"""
Builds the rule embed for the server
"""
warning = _("***Any violation of the [Discord TOS](https://discordapp.com/terms) "
"or [Community Guidelines](https://discordapp.com/guidelines) will "
"result in immediate banning and possibly reported to discord.***")
em = discord.Embed(colour=int(TEAMS[team]["home"].replace("#", ""), 16))
em.description = rules
em.title = _("__RULES__")
em.add_field(name=_("__**WARNING**__"), value=warning)
em.set_thumbnail(url=guild.icon_url)
em.set_author(name=guild.name, icon_url=guild.icon_url)
return em
async def make_leaderboard_embed(guild, post_list, page=0):
"""
Makes the leaderboard embed
"""
leaderboard = post_list["lists"][page]
style = post_list["type"]
em = discord.Embed(timestamp=datetime.utcnow())
description = ""
for msg in leaderboard:
description += msg
em.description = description
em.set_author(name=guild.name + _(" Pickems ") + style + _(" Leaderboard"), icon_url=guild.icon_url)
em.set_thumbnail(url=guild.icon_url)
em.set_footer(text=_("Page") + " {}/{}".format(page+1, len(post_list["lists"])))
return em
async def roster_embed(post_list, page):
"""
Builds the embed for players by stats in the current season
"""
player_list = post_list[page]
url = BASE_URL + player_list["person"]["link"] + "?expand=person.stats&stats=yearByYear"
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
player_data = await resp.json()
player = player_data["people"][0]
year_stats = [league for league in player["stats"][0]["splits"] if league["league"]["name"] == "National Hockey League"][-1]
name = player["fullName"]
number = player["primaryNumber"]
position = player["primaryPosition"]["name"]
headshot = HEADSHOT_URL.format(player["id"])
team = player["currentTeam"]["name"]
em = discord.Embed(colour=int(TEAMS[team]["home"].replace("#", ""), 16))
em.set_author(name="{} #{}".format(name, number), url=TEAMS[team]["team_url"], icon_url=TEAMS[team]["logo"])
em.add_field(name="Position", value=position)
em.set_thumbnail(url=headshot)
if position != "Goalie":
post_data = {_("Shots") : year_stats["stat"]["shots"],
_("Goals") : year_stats["stat"]["goals"],
_("Assists") : year_stats["stat"]["assists"],
_("Hits") : year_stats["stat"]["hits"],
_("Face Off Percent") : year_stats["stat"]["faceOffPct"],
"+/-" : year_stats["stat"]["plusMinus"],
_("Blocked Shots") : year_stats["stat"]["blocked"],
_("PIM") : year_stats["stat"]["pim"]}
for key, value in post_data.items():
if value != 0.0:
em.add_field(name=key, value=value)
else:
saves = year_stats["stat"]["saves"]
save_percentage = year_stats["stat"]["savePercentage"]
goals_against_average = year_stats["stat"]["goalAgainstAverage"]
em.add_field(name=_("Saves"), value=saves)
em.add_field(name=_("Save Percentage"), value=save_percentage)
em.add_field(name=_("Goals Against Average"), value=goals_against_average)
return em
+72
View File
@@ -0,0 +1,72 @@
Anaheim Ducks:
- AnaheimDucks:381568940108939265
Arizona Coyotes:
- ArizonaCoyotes:381568940083511297
Boston Bruins:
- BostonBruins:381568939857149954
Buffalo Sabres:
- BuffaloSabres:381568940658130944
Calgary Flames:
- CalgaryFlames:381568940314460171
Carolina Hurricanes:
- CarolinaHurricanes:381568942436646914
Chicago Blackhawks:
- ChicagoBlackhawks:381568943279702036
Colorado Avalanche:
- ColoradoAvalanche:381568943170519040
Columbus Blue Jackets:
- ColumbusBlueJackets:381568942839300107
Dallas Stars:
- DallasStars:381568942520664065
Detroit Red Wings:
- DetroitRedWings:381568943162130442
Edmonton Oilers:
- EdmontonOilers:381568942721728513
Florida Panthers:
- FloridaPanthers:381568943137095680
Los Angeles Kings:
- LosAngelesKings:381568942105296898
Minnesota Wild:
- MinnesotaWild:381568942596030475
Montréal Canadiens:
- MontrealCanadiens:381568942486847491
Nashville Predators:
- NashvillePredators:381568942944157706
New Jersey Devils:
- NewJerseyDevils:381568942537179138
New York Islanders:
- NewYorkIslanders:381568942948352011
New York Rangers:
- NewYorkRangers:381568942898151435
Ottawa Senators:
- OttawaSenators:381568942776254475
Philadelphia Flyers:
- PhiladelphiaFlyers:381568942004764673
Pittsburgh Penguins:
- PittsburghPenguins:381568942587510796
San Jose Sharks:
- SanJoseSharks:381568942864334848
St. Louis Blues:
- StLouisBlues:381568942474526724
Tampa Bay Lightning:
- TampaBayLightning:381568942054834196
Team Atlantic:
- Atlantic:406575132895739924
Team Central:
- Central:406575132656533516
Team Metropolitan:
- Metropolitan:406575133113712640
Team Pacific:
- Pacific:406575133096935437
Toronto Maple Leafs:
- TorontoMapleLeafs:381568943011135488
Vancouver Canucks:
- VancouverCanucks:381568942914928641
Vegas Golden Knights:
- VegasGoldenKnights:381568942465875970
Washington Capitals:
- WashingtonCapitals:381568942541373440
Winnipeg Jets:
- WinnipegJets:381568942700888065
Other:
- nhl:496510372828807178
+14
View File
@@ -0,0 +1,14 @@
class HockeyError(Exception):
pass
class UserHasVotedError(HockeyError):
pass
class VotingHasEndedError(HockeyError):
pass
class NotAValidTeamError(HockeyError):
pass
class InvalidFileError(HockeyError):
pass
+567
View File
@@ -0,0 +1,567 @@
import aiohttp
from datetime import datetime
from redbot.core import Config
from .embeds import *
from .pickems import Pickems
from .constants import BASE_URL, TEAMS
from .goal import Goal
from .helper import *
from .standings import Standings
import discord
from redbot.core.i18n import Translator
_ = Translator("Hockey", __file__)
class Game:
"""
This is the object that handles game information
game state updates and goal posts
"""
def __init__(self, game_state:str, home_team: str, away_team:str, period:int,
home_shots:int, away_shots:int, home_score:int, away_score:int, game_start:str, goals:list,
home_goals:list, away_goals:list, home_abr:str, away_abr:str, period_ord:str,
period_time_left:str, plays:list, first_star:str, second_star:str, third_star:str):
super().__init__()
self.game_state = game_state
self.home_team = home_team
self.away_team = away_team
self.home_shots = home_shots
self.away_shots = away_shots
self.home_score = home_score
self.away_score = away_score
self.goals = goals
self.home_goals = home_goals
self.away_goals = away_goals
self.home_abr = home_abr
self.away_abr = away_abr
self.period = period
self.period_ord = period_ord
self.period_time_left = period_time_left
self.plays = plays
self.game_start = datetime.strptime(game_start, "%Y-%m-%dT%H:%M:%SZ")
self.home_logo = TEAMS[home_team]["logo"] if home_team in TEAMS else "https://www-league.nhlstatic.com/images/logos/league-light/133.svg"
self.away_logo = TEAMS[away_team]["logo"] if away_team in TEAMS else "https://www-league.nhlstatic.com/images/logos/league-light/133.svg"
self.home_emoji = "<:{}>".format(TEAMS[home_team]["emoji"]) if home_team in TEAMS else "<:nhl:496510372828807178>"
self.away_emoji = "<:{}>".format(TEAMS[away_team]["emoji"]) if away_team in TEAMS else "<:nhl:496510372828807178>"
self.first_star = first_star
self.second_star = second_star
self.third_star = third_star
self.config = hockey_config()
def to_json(self) -> dict:
return {
"game_state" : self.game_state,
"home_team" : self.home_team,
"away_team" : self.away_team,
"home_shots" : self.home_shots,
"away_shots" : self.away_shots,
"home_score" : self.home_score,
"away_score" : self.away_score,
"goals" : [goal.to_json() for goal in self.goals],
"home_goals" : self.home_goals,
"away_goals" : self.away_goals,
"home_abr" : self.home_abr,
"away_abr" : self.away_abr,
"period" : self.period,
"period_ord" : self.period_ord,
"period_time_left" : self.period_time_left,
"plays" : self.plays,
"game_start" : self.game_start.strftime("%Y-%m-%dT%H:%M:%SZ"),
"home_logo" : self.home_logo,
"away_logo" : self.away_logo,
"home_emoji" : self.home_emoji,
"away_emoji" : self.away_emoji,
"first_star" : self.first_star,
"second_star" : self.second_star,
"third_star" : self.third_star
}
@staticmethod
async def get_games(team=None, start_date:datetime=None, end_date:datetime=None):
"""
Get a specified days games, defaults to the current day
requires a datetime object
returns a list of game objects
if a start date and an end date are not provided to the url
it returns only todays games
returns a list of game objects
"""
games_list = await Game.get_games_list(team, start_date, end_date)
return_games_list = []
if games_list != []:
for games in games_list:
try:
async with aiohttp.ClientSession() as session:
async with session.get(BASE_URL + games["link"]) as resp:
data = await resp.json()
return_games_list.append(await Game.from_json(data))
except Exception as e:
print(_("Error grabbing game data: ")+"{}".format(e))
continue
return return_games_list
@staticmethod
async def get_games_list(team=None, start_date:datetime=None, end_date:datetime=None):
"""
Get a specified days games, defaults to the current day
requires a datetime object
returns a list of game objects
if a start date and an end date are not provided to the url
it returns only todays games
returns a list of games
"""
start_date_str = start_date.strftime("%Y-%m-%d") if start_date is not None else None
end_date_str = end_date.strftime("%Y-%m-%d") if end_date is not None else None
if start_date is None and end_date is None:
# if no dates are provided get todays current schedule
url = BASE_URL + "/api/v1/schedule"
elif start_date is None and end_date is not None:
# if no start date is provided start with today
start_date_str = datetime.now().strftime("%Y-%m-%d")
url = f"{BASE_URL}/api/v1/schedule?startDate={start_date_str}&endDate={end_date_str}"
elif start_date is not None and end_date is None:
# if no end date is provided carry through to the following year
end_date_str = str(start_date.year + 1) + datetime.now().strftime("-%m-%d")
url = f"{BASE_URL}/api/v1/schedule?startDate={start_date_str}&endDate={end_date_str}"
else:
url = f"{BASE_URL}/api/v1/schedule?startDate={start_date_str}&endDate={end_date_str}"
if team not in ["all", None]:
# if a team is provided get just that TEAMS data
url += "&teamId={}".format(TEAMS[team]["id"])
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
data = await resp.json()
game_list = [game for date in data["dates"] for game in date["games"]]
return game_list
@staticmethod
async def get_game_embed(post_list, page):
"""
Makes the game object from provided URL
"""
game = post_list[page]
if type(game) is dict:
async with aiohttp.ClientSession() as session:
async with session.get(BASE_URL + game["link"]) as resp:
game_json = await resp.json()
data = await Game.from_json(game_json)
print(BASE_URL + game["link"])
else:
data = game
return await data.make_game_embed()
async def make_game_embed(self):
"""
Builds the game embed when the command is called
provides as much data as possible
"""
team_url = TEAMS[self.home_team]["team_url"] if self.home_team in TEAMS else "https://nhl.com"
# timestamp = datetime.strptime(self.game_start, "%Y-%m-%dT%H:%M:%SZ")
title = "{away} @ {home} {state}".format(away=self.away_team, home=self.home_team, state=self.game_state)
colour = int(TEAMS[self.home_team]["home"].replace("#", ""), 16) if self.home_team in TEAMS else None
em = discord.Embed(timestamp=self.game_start)
if colour is not None:
em.colour = colour
em.set_author(name=title, url=team_url, icon_url=self.home_logo)
em.set_thumbnail(url=self.home_logo)
em.set_footer(text=_("Game start "), icon_url=self.away_logo)
if self.game_state == "Preview":
home_str, away_str = await self.get_stats_msg()
em.add_field(name=f"{self.home_emoji} {self.home_team} {self.home_emoji}", value=home_str)
em.add_field(name=f"{self.away_emoji} {self.away_team} {self.away_emoji}", value=away_str)
if self.game_state != "Preview":
home_msg = _("Goals: **") + str(self.home_score) + _("** \nShots: **") + str(self.home_shots) + "**"
away_msg = _("Goals: **") + str(self.away_score) + _("** \nShots: **") + str(self.away_shots) + "**"
em.add_field(name=f"{self.home_emoji} {self.home_team} {self.home_emoji}", value=home_msg)
em.add_field(name=f"{self.away_emoji} {self.away_team} {self.away_emoji}", value=away_msg)
if self.goals != []:
goal_msg = ""
first_goals = [goal for goal in self.goals if goal.period_ord == "1st"]
second_goals = [goal for goal in self.goals if goal.period_ord == "2nd"]
third_goals = [goal for goal in self.goals if goal.period_ord == "3rd"]
ot_goals = [goal for goal in self.goals if goal.period_ord == "OT"]
so_goals = [goal for goal in self.goals if goal.period_ord == "SO"]
list_goals = {"1st":first_goals, "2nd":second_goals, "3rd":third_goals, "OT":ot_goals}
for goals in list_goals:
ordinal = goals
goal_msg = ""
for goal in list_goals[ordinal]:
emoji = TEAMS[goal.team_name]["emoji"]
goal_msg += f"<:{emoji}> {goal.team_name} Goal By {goal.description}\n\n"
if goal_msg != "":
em.add_field(name=str(ordinal) + _(" Period Goals"), value=goal_msg)
if len(so_goals) != 0:
home_msg = ""
away_msg = ""
score = "☑\n"
miss = "❌\n"
for goal in so_goals:
if goal.event in ["Shot", "Missed Shot"] and goal.period_ord == "SO":
if goal.team_name == self.home_team:
home_msg += miss
else:
away_msg += miss
if goal.event in ["Goal"] and goal.period_ord == "SO":
if goal.team_name == self.home_team:
home_msg += score
else:
away_msg += score
em.add_field(name=f"{self.home_team}"+_(" Shootout"), value=home_msg)
em.add_field(name=f"{self.away_team}"+_(" Shootout"), value=away_msg)
if self.first_star is not None:
stars = f"⭐ {self.first_star}\n⭐⭐ {self.second_star}\n⭐⭐⭐ {self.third_star}"
em.add_field(name=_("Stars of the game"), value=stars)
if self.game_state == "Live":
period = self.period_ord
if self.period_time_left[0].isdigit():
msg = str(self.period_time_left) + _(" Left in the ") + str(period) + _(" period")
else:
msg = str(self.period_time_left) + _(" Left in the ") + str(period) + _(" period")
em.add_field(name="Period", value=msg)
return em
async def game_state_embed(self):
"""
Makes the game state embed based on the game self provided
"""
post_state = ["all", self.home_team, self.away_team]
# timestamp = datetime.strptime(self.game_start, "%Y-%m-%dT%H:%M:%SZ")
title = f"{self.away_team} @ {self.home_team} {self.game_state}"
em = discord.Embed(timestamp=self.game_start)
home_field = "{0} {1} {0}".format(self.home_emoji, self.home_team)
away_field = "{0} {1} {0}".format(self.away_emoji, self.away_team)
if self.game_state != "Preview":
home_str = _("Goals: **") + str(self.home_score) + _("** \nShots: **") + str(self.home_shots) + "**"
away_str = _("Goals: **") + str(self.away_score) + _("** \nShots: **") + str(self.away_shots) + "**"
else:
home_str, away_str = await self.get_stats_msg()
em.add_field(name=home_field, value=home_str, inline=True)
em.add_field(name=away_field, value=away_str, inline=True)
colour = int(TEAMS[self.home_team]["home"].replace("#", ""), 16) if self.home_team in TEAMS else None
if colour is not None:
em.colour = colour
home_url = TEAMS[self.home_team]["team_url"] if self.home_team in TEAMS else "https://nhl.com"
if self.first_star is not None:
stars = f"⭐ {self.first_star}\n⭐⭐ {self.second_star}\n⭐⭐⭐ {self.third_star}"
em.add_field(name=_("Stars of the game"), value=stars)
em.set_author(name=title, url=home_url, icon_url=self.home_logo)
em.set_thumbnail(url=self.home_logo)
em.set_footer(text=_("Game start "), icon_url=self.away_logo)
return em
async def game_state_text(self):
post_state = ["all", self.home_team, self.away_team]
# timestamp = datetime.strptime(self.game_start, "%Y-%m-%dT%H:%M:%SZ")
time_string = utc_to_local(self.game_start).strftime("%I:%M %p %Z")
em = (f"{self.away_emoji}{self.away_team} @ {self.home_emoji}{self.home_team} "
f"{self.game_state}\n({time_string})")
if self.game_state != "Preview":
em = (_("**__Current Score__**\n") + f"{self.home_emoji} {self.home_team}: {self.home_score}\n"+
f"{self.away_emoji} {self.away_team}: {self.away_score}")
return em
async def get_stats_msg(self):
"""
returns team stats on the season from standings object
"""
msg = "GP:**{gp}** W:**{wins}** L:**{losses}\n**OT:**{ot}** PTS:**{pts}** S:**{streak}**\n"
streak_types = {"wins":"W", "losses":"L", "ot":"OT"}
home_str = "GP:**0** W:**0** L:**0\n**OT:**0** PTS:**0** S:**0**\n"
away_str = "GP:**0** W:**0** L:**0\n**OT:**0** PTS:**0** S:**0**\n"
try:
stats, home_i = await Standings.get_team_standings(self.home_team)
for team in stats:
if team.name == self.away_team:
streak = "{} {}".format(team.streak, streak_types[team.streak_type])
away_str = msg.format(wins=team.wins, losses=team.losses,\
ot=team.ot, pts=team.pts, gp=team.gp, streak=streak)
if team.name == self.home_team:
streak = "{} {}".format(team.streak, streak_types[team.streak_type])
home_str = msg.format(wins=team.wins, losses=team.losses,\
ot=team.ot, pts=team.pts, gp=team.gp, streak=streak)
except:
pass
return home_str, away_str
async def check_game_state(self, bot):
post_state = ["all", self.home_team, self.away_team]
home = await get_team(self.home_team)
away = await get_team(self.away_team)
team_list = await self.config.teams()
# Home team checking
if self.game_state == "Preview":
"""Checks if the the game state has changes from Final to Preview
Could be unnecessary since after Game Final it will check for next game
"""
time_now = datetime.utcnow()
# game_time = datetime.strptime(data.game_start, "%Y-%m-%dT%H:%M:%SZ")
game_start = (self.game_start - time_now).total_seconds()/60
if "Preview" not in home["game_state"]:
await self.post_game_state(bot)
await self.save_game_state()
if game_start < 60 and game_start > 30 and home["game_state"] != "Preview60":
# Post 60 minutes until game start
await self.post_time_to_game_start(bot, "60")
await self.save_game_state("60")
if game_start < 30 and game_start >10 and home["game_state"] != "Preview30":
# Post 30 minutes until game start
await self.post_time_to_game_start(bot, "30")
await self.save_game_state("30")
if game_start < 10 and game_start > 0 and home["game_state"] != "Preview10":
# Post 10 minutes until game start
await self.post_time_to_game_start(bot, "10")
await self.save_game_state("10")
# Create channel and look for game day thread
if self.game_state == "Live":
"""Checks what the period is and posts the game is starting in the appropriate channel"""
if home["period"] != self.period:
if await self.config.print():
msg = "**{} Period starting {} at {}**"
print(msg.format(self.period_ord, self.away_team, self.home_team))
await self.post_game_state(bot)
await self.save_game_state()
if (self.home_score + self.away_score) != 0:
# Check if there's goals only if there are goals
await self.check_team_goals(bot)
if self.game_state == "Final" and self.first_star is not None:
"""Final game state checks"""
if (self.home_score + self.away_score) != 0:
""" Check for goal before posting game final, happens with OT games"""
await self.check_team_goals(bot)
if home["game_state"] != self.game_state and home["game_state"] != "Null":
# Post game final data and check for next game
if await self.config.print():
msg = "Game Final {} @ {}"
print(msg.format(self.home_team, self.away_team))
await self.post_game_state(bot)
await self.save_game_state()
async def post_game_state(self, bot):
"""
When a game state has changed this is called to create the embed
and post in all channels
"""
post_state = ["all", self.home_team, self.away_team]
state_embed = await self.game_state_embed()
state_text = await self.game_state_text()
for channels in await self.config.all_channels():
channel = bot.get_channel(id=channels)
if channel is None:
continue
guild = channel.guild
should_post = await check_to_post(channel, post_state)
if should_post:
game_day_channels = await self.config.guild(guild).gdc()
can_embed = channel.permissions_for(guild.me).embed_links
can_manage_webhooks = False # channel.permissions_for(guild.me).manage_webhooks
if self.game_state == "Live":
home_role, away_role = await get_team_role(guild, self.home_team, self.away_team)
if game_day_channels is not None:
# We don't want to ping people in the game day channels twice
if channel.id in game_day_channels:
home_role, away_role = self.home_team, self.away_team
msg = "**" + str(self.period_ord) + _(" Period starting ") + away_role + _(" at ") + home_role +"**"
try:
if not can_embed:
await channel.send(msg+"\n{}".format(state_text))
else:
await channel.send(msg, embed=state_embed)
except Exception as e:
print(_("Could not post goal in ") + str(channels) + str(e))
else:
if self.game_state == "Preview":
if game_day_channels is not None:
# Don't post the preview message twice in the channel
if channel.id in game_day_channels:
continue
try:
if not can_embed:
preview_msg = await channel.send(state_text)
else:
preview_msg = await channel.send(embed=state_embed)
# Create new pickems object for the game
if self.game_state == "Preview":
await Pickems.create_pickem_object(guild, preview_msg, channel, self)
if channel.permissions_for(guild.me).add_reactions:
try:
await preview_msg.add_reaction(self.away_emoji[2:-1])
await preview_msg.add_reaction(self.home_emoji[2:-1])
except Exception as e:
print(e)
except Exception as e:
print(_("Could not post goal in ") + str(channels) + str(e))
async def check_team_goals(self, bot):
"""
Checks to see if a goal needs to be posted
"""
home_team_data = await get_team(self.home_team)
away_team_data = await get_team(self.away_team)
all_data = await get_team("all")
team_list = await self.config.teams()
post_state = ["all", self.home_team, self.away_team]
home_goal_ids = [goal.goal_id for goal in self.home_goals]
away_goal_ids = [goal.goal_id for goal in self.away_goals]
home_goal_list = list(home_team_data["goal_id"])
away_goal_list = list(away_team_data["goal_id"])
for goal in self.goals:
# goal_id = str(goal["result"]["eventCode"])
# team = goal["team"]["name"]
team_data = await get_team(goal.team_name)
if goal.goal_id not in team_data["goal_id"]:
# attempts to post the goal if there is a new goal
msg_list = await goal.post_team_goal(bot, self)
team_list.remove(team_data)
team_data["goal_id"][goal.goal_id] = {"goal":goal.to_json(),"messages":msg_list}
team_list.append(team_data)
await self.config.teams.set(team_list)
continue
if goal.goal_id in team_data["goal_id"]:
# attempts to edit the goal if the scorers have changed
old_goal = Goal(**team_data["goal_id"][goal.goal_id]["goal"])
if goal.description != old_goal.description:
old_msgs = team_data["goal_id"][goal.goal_id]["messages"]
team_list.remove(team_data)
team_data["goal_id"][goal.goal_id]["goal"] = goal.to_json()
team_list.append(team_data)
await self.config.teams.set(team_list)
await goal.edit_team_goal(bot, self, old_msgs)
# attempts to delete the goal if it was called back
for goal_str in home_goal_list:
await Goal.remove_goal_post(bot, goal_str, self.home_team, self)
for goal_str in away_goal_list:
await Goal.remove_goal_post(bot, goal_str, self.away_team, self)
async def save_game_state(self, time_to_game_start:str="0"):
"""
Saves the data do the config to compare against new data
"""
home = await get_team(self.home_team)
away = await get_team(self.away_team)
team_list = await self.config.teams()
team_list.remove(home)
team_list.remove(away)
if self.game_state != "Final":
if self.game_state == "Preview" and time_to_game_start != "0":
home["game_state"] = self.game_state+time_to_game_start
away["game_state"] = self.game_state+time_to_game_start
else:
home["game_state"] = self.game_state
away["game_state"] = self.game_state
home["period"] = self.period
away["period"] = self.period
home["game_start"] = self.game_start.strftime("%Y-%m-%dT%H:%M:%SZ")
away["game_start"] = self.game_start.strftime("%Y-%m-%dT%H:%M:%SZ")
else:
home["game_state"] = "Null"
away["game_state"] = "Null"
home["period"] = 0
away["period"] = 0
home["goal_id"] = {}
away["goal_id"] = {}
home["game_start"] = ""
away["game_start"] = ""
team_list.append(home)
team_list.append(away)
await self.config.teams.set(team_list)
async def post_time_to_game_start(self, bot, time_left):
"""
Post when there is 60, 30, and 10 minutes until the game starts in all channels
"""
post_state = ["all", self.home_team, self.away_team]
for channels in await self.config.all_channels():
channel = bot.get_channel(id=channels)
if channel is None:
continue
should_post = await check_to_post(channel, post_state)
team_to_post = await self.config.channel(channel).team()
if should_post and "all" not in team_to_post:
guild = channel.guild
msg = (str(time_left) + _(" minutes until ") + f"{self.away_emoji} {self.away_team}"+
f" @ {self.home_emoji} {self.home_team}" + _(" starts"))
try:
await channel.send(msg)
except Exception as e:
print(_("Could not post goal in ") + str(channels) + str(e))
@staticmethod
async def from_url(url:str):
try:
async with aiohttp.ClientSession() as session:
async with session.get(BASE_URL + url) as resp:
data = await resp.json()
return await Game.from_json(data)
except Exception as e:
print(_("Error grabbing game data: ")+"{}".format(e))
return
@classmethod
async def from_json(cls, data: dict):
event = data["liveData"]["plays"]["allPlays"]
home_team = data["gameData"]["teams"]["home"]["name"]
away_team = data["gameData"]["teams"]["away"]["name"]
players = data["liveData"]["boxscore"]["teams"]["away"]["players"]
players.update(data["liveData"]["boxscore"]["teams"]["home"]["players"])
goals = [await Goal.from_json(goal, players) for goal in event if goal["result"]["eventTypeId"] == "GOAL"\
or (goal["result"]["eventTypeId"] in ["SHOT", "MISSED_SHOT"] and goal["about"]["ordinalNum"] == "SO")]
if "currentPeriodOrdinal" in data["liveData"]["linescore"]:
period_ord = data["liveData"]["linescore"]["currentPeriodOrdinal"]
period_time_left = data["liveData"]["linescore"]["currentPeriodTimeRemaining"]
events = data["liveData"]["plays"]["allPlays"]
else:
period_ord = "0"
period_time_left = "0"
events = ["."]
decisions = data["liveData"]["decisions"]
first_star = decisions["firstStar"]["fullName"] if "firstStar" in decisions else None
second_star = decisions["secondStar"]["fullName"] if "secondStar" in decisions else None
third_star = decisions["thirdStar"]["fullName"] if "thirdStar" in decisions else None
return cls(data["gameData"]["status"]["abstractGameState"],
data["gameData"]["teams"]["home"]["name"],
data["gameData"]["teams"]["away"]["name"],
data["liveData"]["linescore"]["currentPeriod"],
data["liveData"]["linescore"]["teams"]["home"]["shotsOnGoal"],
data["liveData"]["linescore"]["teams"]["away"]["shotsOnGoal"],
data["liveData"]["linescore"]["teams"]["home"]["goals"],
data["liveData"]["linescore"]["teams"]["away"]["goals"],
data["gameData"]["datetime"]["dateTime"],
goals,
[goal for goal in goals if home_team in goal.team_name],
[goal for goal in goals if away_team in goal.team_name],
data["gameData"]["teams"]["home"]["abbreviation"],
data["gameData"]["teams"]["away"]["abbreviation"],
period_ord,
period_time_left,
events,
first_star,
second_star,
third_star
)
+159
View File
@@ -0,0 +1,159 @@
from datetime import datetime
from redbot.core import Config
from .game import Game
from .constants import BASE_URL, CONFIG_ID, TEAMS
from .pickems import Pickems
from .helper import *
class GameDayChannels:
"""
This is where the functions to handle creation and deletion
of game day channels is stored
"""
def __init__(self):
pass
@staticmethod
async def get_chn_name(game):
"""
Creates game day channel name
"""
timestamp = utc_to_local(game.game_start)
chn_name = "{}-vs-{}-{}-{}-{}".format(game.home_abr, game.away_abr,\
timestamp.year, timestamp.month, timestamp.day)
return chn_name.lower()
@staticmethod
async def check_new_gdc(bot):
config = Config.get_conf(None, CONFIG_ID, cog_name="Hockey")
game_list = await Game.get_games() # Do this once so we don't spam the api
for guilds in await config.all_guilds():
guild = bot.get_guild(guilds)
if guild is None:
continue
if not await config.guild(guild).create_channels():
continue
team = await config.guild(guild).gdc_team()
if team != "all":
next_games = await Game.get_games_list(team, datetime.now())
# print(next_game)
if next_games != []:
next_game = await Game.from_url(next_games[0]["link"])
if next_game is None:
continue
chn_name = await GameDayChannels.get_chn_name(next_game)
try:
cur_channels = await config.guild(guild).gdc()
cur_channel = bot.get_channel(cur_channels[0])
except Exception as e:
print(e)
cur_channel = None
if cur_channel is None:
await GameDayChannels.create_gdc(bot, guild)
elif cur_channel.name != chn_name.lower():
await GameDayChannels.delete_gdc(bot, guild)
await GameDayChannels.create_gdc(bot, guild)
else:
await GameDayChannels.delete_gdc(bot, guild)
for game in game_list:
await GameDayChannels.create_gdc(bot, guild, game)
@staticmethod
async def create_gdc(bot, guild, game_data=None):
"""
Creates a game day channel for the given game object
if no game object is passed it looks for the set team for the guild
returns None if not setup
"""
config = Config.get_conf(None, CONFIG_ID, cog_name="Hockey")
category = bot.get_channel(await config.guild(guild).category())
if category is None:
# Return none if there's no category to create the channel
return
if game_data is None:
team = await config.guild(guild).gdc_team()
next_games = await Game.get_games_list(team, datetime.now())
if next_games != []:
next_game = await Game.from_url(next_games[0]["link"])
if next_game is None:
return
else:
# Return if no more games are playing for this team
return
else:
team = game_data.home_team
next_game = game_data
chn_name = await GameDayChannels.get_chn_name(next_game)
try:
new_chn = await guild.create_text_channel(chn_name, category=category)
except Exception as e:
print("Error creating channels in {}: {}".format(guild.name, e))
return
cur_channels = await config.guild(guild).gdc()
if cur_channels is None:
cur_channels = []
cur_channels.append(new_chn.id)
await config.guild(guild).gdc.set(cur_channels)
await config.guild(guild).create_channels.set(True)
await config.channel(new_chn).team.set([team])
delete_gdc = await config.guild(guild).delete_gdc()
await config.channel(new_chn).to_delete.set(delete_gdc)
# Gets the timezone to use for game day channel topic
# timestamp = datetime.strptime(next_game.game_start, "%Y-%m-%dT%H:%M:%SZ")
guild_team = await config.guild(guild).gdc_team()
channel_team = guild_team if guild_team != "all" else next_game.home_team
timezone = TEAMS[channel_team]["timezone"] if channel_team in TEAMS else TEAMS[next_game.away_team]["timezone"]
time_string = utc_to_local(next_game.game_start, timezone).strftime("%A %B %d, %Y at %I:%M %p %Z")
game_msg = (f"{next_game.away_team} {next_game.away_emoji} @ "
f"{next_game.home_team} {next_game.home_emoji} {time_string}")
await new_chn.edit(topic=game_msg)
if new_chn.permissions_for(guild.me).embed_links:
em = await next_game.game_state_embed()
preview_msg = await new_chn.send(embed=em)
else:
preview_msg = await new_chn.send(await next_game.game_state_text())
# Create new pickems object for the game
await Pickems.create_pickem_object(guild, preview_msg, new_chn, next_game)
if new_chn.permissions_for(guild.me).manage_messages:
await preview_msg.pin()
if new_chn.permissions_for(guild.me).add_reactions:
try:
await preview_msg.add_reaction(next_game.away_emoji[2:-1])
await preview_msg.add_reaction(next_game.home_emoji[2:-1])
except Exception as e:
print(e)
@staticmethod
async def delete_gdc(bot, guild):
"""
Deletes all game day channels in a given guild
"""
config = Config.get_conf(None, CONFIG_ID, cog_name="Hockey")
channels = await config.guild(guild).gdc()
for channel in channels:
chn = bot.get_channel(channel)
if chn is None:
try:
await config._clear_scope(Config.CHANNEL, str(chn))
except:
pass
continue
if not await config.channel(chn).to_delete():
continue
try:
await config.channel(chn).clear()
await chn.delete()
except Exception as e:
print(e)
await config.guild(guild).gdc.set([])
+294
View File
@@ -0,0 +1,294 @@
from .constants import HEADSHOT_URL
from datetime import datetime
import discord
from .helper import *
from redbot.core.i18n import Translator
try:
from .oilers import Oilers
except:
pass
_ = Translator("Hockey", __file__)
class Goal:
def __init__(self, goal_id:str, team_name:str, scorer_id:int, jersey_no:str, description:str,
period:int, period_ord:str, time_remaining:str, time:str, home_score:int,
away_score:int, strength:str, empty_net:bool, event:str):
super().__init__()
self.goal_id = goal_id
self.team_name = team_name
self.scorer_id = scorer_id
self.headshot = HEADSHOT_URL.format(scorer_id)
self.jersey_no = jersey_no
self.description = description
self.period = period
self.period_ord = period_ord
self.time_remaining = time_remaining
self.time = datetime.strptime(time, "%Y-%m-%dT%H:%M:%SZ")
self.home_score = home_score
self.away_score = away_score
self.strength = strength
self.empty_net = empty_net
self.event = event
self.config = hockey_config()
def to_json(self) -> dict:
return {
"goal_id" : self.goal_id,
"team_name" : self.team_name,
"scorer_id" : self.scorer_id,
"jersey_no": self.jersey_no,
"description" : self.description,
"period" : self.period,
"period_ord" : self.period_ord,
"time_remaining" : self.time_remaining,
"time" : self.time.strftime("%Y-%m-%dT%H:%M:%SZ"),
"home_score" : self.home_score,
"away_score" : self.away_score,
"strength" : self.strength,
"empty_net" : self.empty_net,
"event" : self.event
}
@classmethod
async def from_json(cls, data: dict, players: dict):
scorer_id = [p["player"]["id"] for p in data["players"] if p["playerType"] in ["Scorer", "Shooter"]]
if "strength" in data["result"]:
str_dat = data["result"]["strength"]["name"]
strength = "Even Strength" if str_dat == "Even" else str_dat
if data["about"]["ordinalNum"] == "SO":
strength = "Shoot Out"
else:
strength = " "
empty_net = data["result"]["emptyNet"] if "emptyNet" in data["result"] else False
jersey_no = players["ID"+str(scorer_id[0])]["jerseyNumber"]
scorer = scorer_id[0]
return cls(data["result"]["eventCode"],
data["team"]["name"],
scorer_id[0],
jersey_no,
data["result"]["description"],
data["about"]["period"],
data["about"]["ordinalNum"],
data["about"]["periodTimeRemaining"],
data["about"]["dateTime"],
data["about"]["goals"]["home"],
data["about"]["goals"]["away"],
strength,
empty_net,
data["result"]["event"]
)
async def post_team_goal(self, bot, game_data):
"""
Creates embed and sends message if a team has scored a goal
"""
# scorer = self.headshots.format(goal["players"][0]["player"]["id"])
post_state = ["all", game_data.home_team, game_data.away_team]
msg_list = {}
if "Edmonton Oilers" in self.team_name and "missed" not in self.event.lower():
try:
hue = Oilers(bot)
await hue.goal_lights()
except:
pass
goal_embed = await self.goal_post_embed(game_data)
goal_text = await self.goal_post_text(game_data)
for channels in await self.config.all_channels():
role = None
channel = bot.get_channel(id=channels)
if channel is None:
continue
should_post = await check_to_post(channel, post_state)
if should_post:
try:
guild = channel.guild
game_day_channels = await self.config.guild(guild).gdc()
# Don't want to ping people in the game day channels
can_embed = channel.permissions_for(guild.me).embed_links
can_manage_webhooks = False # channel.permissions_for(guild.me).manage_webhooks
for roles in guild.roles:
if roles.name == self.team_name + " GOAL":
role = roles
if game_day_channels is not None:
# We don't want to ping people in the game day channels twice
if channel.id in game_day_channels:
role = None
if not can_embed and can_manage_webhooks:
# try to create a webhook with the teams info to bypass embed permissions
# Waiting for d.py to return messages from webhook responses
# After testing it doesn't look as nice as I would like
# Will leave it off until at some point I can make it look better
webhook = None
for hook in await channel.webhooks():
if hook.name == guild.me.name:
webhook = hook
if webhook is None:
webhook = await channel.create_webhook(name=guild.me.name)
url = TEAMS[self.team_name]["logo"]
await webhook.send(username=self.team_name, avatar_url=url, embed=goal_embed)
continue
if not can_embed and not can_manage_webhooks:
# Create text only message if embed_links permission is not set
if role is not None:
msg = await channel.send("{}\n{}".format(role, goal_text))
else:
msg = await channel.send("{}".format(goal_text))
msg_list[str(channel.id)] = msg.id
continue
if role is None or "missed" in self.event.lower():
msg = await channel.send(embed=goal_embed)
msg_list[str(channel.id)] = msg.id
else:
msg = await channel.send(role.mention, embed=goal_embed)
msg_list[str(channel.id)] = msg.id
except Exception as e:
print(_("Could not post goal in ") + str(channels) + str(e))
pass
return msg_list
@staticmethod
async def remove_goal_post(bot, goal, team, data):
"""
Attempt to delete a goal if it was pulled back
"""
config = hockey_config()
team_list = await config.teams()
team_data = await get_team(team)
if goal not in [goal.goal_id for goal in data.goals]:
try:
old_msgs = team_data["goal_id"][goal]["messages"].items()
except Exception as e:
print(e)
return
for channel_id, message_id in old_msgs:
channel = bot.get_channel(id=int(channel_id))
try:
message = await channel.get_message(message_id)
if message is not None:
await message.delete()
except Exception as e:
print(_("Cannot find message ") + team + " " + goal + " " + str(e))
pass
try:
team_list.remove(team_data)
del team_data["goal_id"][goal]
team_list.append(team_data)
await config.teams.set(team_list)
except Exception as e:
print(e)
return
return
async def edit_team_goal(self, bot, game_data, og_msg):
"""
When a goal scorer has changed we want to edit the original post
"""
# scorer = self.headshots.format(goal["players"][0]["player"]["id"])
post_state = ["all", game_data.home_team, game_data.away_team]
em = await self.goal_post_embed(game_data)
for channel_id, message_id in og_msg.items():
try:
role = None
channel = bot.get_channel(id=int(channel_id))
if channel is None:
continue
if not channel.permissions_for(channel.guild.me).embed_links:
continue
message = await channel.get_message(message_id)
guild = message.guild
game_day_channels = await self.config.guild(guild).gdc()
for roles in guild.roles:
if roles.name == self.team_name + " GOAL":
role = roles
if game_day_channels is not None:
# We don't want to ping people in the game day channels twice
if channel.id in game_day_channels:
role = None
if role is None or "missed" in self.event.lower():
await message.edit(embed=em)
else:
await message.edit(content=role.mention, embed=em)
except:
print(_("Could not edit goal in") + str(channel_id))
return
async def get_shootout_display(self, game_goals):
"""
Gets a string for the shootout display
"""
msg = ""
score = "☑\n"
miss = "❌\n"
for goal in game_goals:
if goal.event in ["Shot", "Missed Shot"] and goal.period_ord == "SO":
msg += miss
if goal.event in ["Goal"] and goal.period_ord == "SO":
msg += score
return msg
async def goal_post_embed(self, game):
"""
Gets the embed for goal posts
"""
h_emoji = game.home_emoji
a_emoji = game.away_emoji
shootout = False
if game.period_ord == "SO":
shootout = True
colour = int(TEAMS[self.team_name]["home"].replace("#", ""), 16) if self.team_name in TEAMS else None
title = "🚨 {} #{} {} {} 🚨".format(self.team_name, self.jersey_no, self.strength, self.event)
url = TEAMS[self.team_name]["team_url"] if self.team_name in TEAMS else "https://nhl.com"
logo = TEAMS[self.team_name]["logo"] if self.team_name in TEAMS else "https://nhl.com"
if not shootout:
em = discord.Embed(description=self.description)
if colour is not None:
em.colour = colour
em.set_author(name=title, url=url, icon_url=logo)
home_str = _("Goals: **") + str(self.home_score) + _("** \nShots: **") + str(game.home_shots) + "**"
away_str = _("Goals: **") + str(self.away_score) + _("** \nShots: **") + str(game.away_shots) + "**"
home_field = f"{game.home_emoji} {game.home_team} {game.home_emoji}"
away_field = f"{game.away_emoji} {game.away_team} {game.away_emoji}"
em.add_field(name=home_field, value=home_str, inline=True)
em.add_field(name=away_field, value=away_str, inline=True)
em.set_footer(text=str(self.time_remaining) + _(" left in the ") + str(self.period_ord) + _(" period"), icon_url=logo)
em.timestamp = self.time
else:
if "missed" in self.event.lower():
em = discord.Embed(description=self.description, colour=colour)
em.set_author(name=title.replace("🚨", ""), url=url, icon_url=logo)
else:
em = discord.Embed(description=self.description, colour=colour)
em.set_author(name=title, url=url, icon_url=logo)
home_msg = await self.get_shootout_display(game.home_goals)
away_msg = await self.get_shootout_display(game.away_goals)
em.add_field(name=game.home_team, value=home_msg)
em.add_field(name=game.away_team, value=away_msg)
em.set_footer(text=str(game.period_time_left) + _(" left in the ") + str(game.period_ord) + _(" period"), icon_url=logo)
em.timestamp = self.time
return em
async def goal_post_text(self, game):
"""
Gets the text to send for goal posts
"""
if game.period_ord != "SO":
text = (f"{game.home_emoji} {game.home_team}: {game.home_score}\n"
f"{game.away_emoji} {game.away_team}: {game.away_score}\n "
f"({self.time_remaining}" + _(" left in the ") + f"{game.period_ord}" + _(" period") + ")")
else:
home_msg = await self.get_shootout_display(game.home_goals)
away_msg = await self.get_shootout_display(game.away_goals)
text = (f"{game.home_emoji} {game.home_team}: {home_msg}\n"
f"{game.away_emoji} {game.away_team}: {away_msg}\n "
f"({self.time_remaining}" + _(" left in the ") + f"{game.period_ord}" + _(" period") + ")")
return text
+154
View File
@@ -0,0 +1,154 @@
from redbot.core import commands
import asyncio
from datetime import datetime, timezone
from redbot.core import Config
from .constants import TEAMS, CONFIG_ID
from .teamentry import TeamEntry
from redbot.core.i18n import Translator
import pytz
_ = Translator("Hockey", __file__)
def get_season():
now = datetime.now()
if (now.month, now.day) < (7, 1):
return (now.year - 1, now.year)
if (now.month, now.day) >= (7, 1):
return (now.year, now.year + 1)
def hockey_config():
return Config.get_conf(None, CONFIG_ID, cog_name="Hockey")
def utc_to_local(utc_dt, new_timezone='US/Eastern'):
eastern = pytz.timezone(new_timezone)
return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=eastern)
async def pick_team(ctx, team_list):
"""
helper to determine the team when two teams share a name when requested
TODO: impliment everywhere teams are a choice
"""
msg = _("There's multiple teams with that name, pick one of these:\n")
if ctx.channel.permissions_for(ctx.guild.me).add_reactions:
new_msg = await ctx.send(msg)
team_emojis = [TEAMS[team]["emoji"] for team in team_list]
def reaction_check(r, u):
return u == ctx.message.author and str(r.emoji).replace("<:", "").replace(">", "") in team_emojis
for emoji in team_emojis:
await new_msg.add_reaction(emoji)
try:
reaction, user = await ctx.bot.wait_for("reaction_add", check=reaction_check, timeout=15)
except asyncio.TimeoutError:
await new_msg.edit(content=_("I guess not."))
return
else:
return team_list[team_emojis.index(str(reaction.emoji).replace("<:", "").replace(">", ""))]
else:
for i, team_name in enumerate(team_list):
msg += "{}: {}\n".format(i+1, team_name)
def msg_check(m):
return m.author == ctx.message.author
try:
msg = await ctx.bot.wait_for("message", check=msg_check, timeout=15)
except asyncio.TimeoutError:
await new_msg.edit(content=_("I guess not."))
return
if msg.content.isdigit():
msg = int(msg.content)-1
try:
return team_list[msg]
except (IndexError, ValueError, AttributeError):
pass
else:
return_team = None
for team in team_list:
if msg.content.lower() in team.lower():
return_team = team
return return_team
async def check_to_post(channel, post_state):
config = Config.get_conf(None, CONFIG_ID, cog_name="Hockey")
channel_teams = await config.channel(channel).team()
should_post = False
for team in channel_teams:
if team in post_state:
should_post = True
return should_post
async def get_team_role(guild, home_team, away_team):
home_role = None
away_role = None
for role in guild.roles:
if "Montréal Canadiens" in home_team and "Montreal Canadiens" in role.name:
home_role = role.mention
elif role.name == home_team:
home_role = role.mention
if "Montréal Canadiens" in away_team and "Montreal Canadiens" in role.name:
away_role = role.mention
elif role.name == away_team:
away_role = role.mention
if home_role is None:
home_role = home_team
if away_role is None:
away_role = away_team
return home_role, away_role
async def get_team(team):
config = Config.get_conf(None, CONFIG_ID, cog_name="Hockey")
return_team = None
team_list = await config.teams()
for teams in team_list:
if team == teams["team_name"]:
return_team = team
return teams
if return_team is None:
# Add unknown teams to the config to track stats
return_team = TeamEntry("Null", team, 0, [], {}, [], "")
team_list.append(return_team.to_json())
await config.teams.set(team_list)
return await get_team(team)
async def check_valid_team(team_name, standings=False):
"""
Checks if this is a valid team name or all teams
useful for game day channel creation should impliment elsewhere
"""
is_team = []
conference = ["eastern", "western", "conference"]
division = ["metropolitan", "atlantic", "pacific", "central", "division"]
if team_name.lower() == "all":
return ["all"]
if team_name in conference and standings:
return [team_name]
if team_name.lower() in division and standings:
return [team_name]
for team in TEAMS:
if team_name.lower() in team.lower():
is_team.append(team)
if is_team == []:
if team_name.lower() in ["montreal canadiens", "habs", "montreal"]:
is_team.append("Montréal Canadiens")
if team_name.lower() == "avs":
is_team.append("Colorado Avalanche")
if team_name.lower() == "preds":
is_team.append("Nashville Predators")
if team_name.lower() == "bolts":
is_team.append("Tampa Bay Lightning")
if team_name.lower() in ["jackets", "bjs"]:
is_team.append("Columbus Blue Jackets")
if team_name.lower() == "isles":
is_team.append("New York Islanders")
if team_name.lower() == "sens":
is_team.append("Ottawa Senators")
if team_name.lower() == "pens":
is_team.append("Pittsburgh Penguins")
if team_name.lower() == "caps":
is_team.append("Washington Capitals")
return is_team
+1288
View File
File diff suppressed because it is too large. Load diff
+27
View File
@@ -0,0 +1,27 @@
{
"author":[
"TrustyJAID"
],
"description":"Gather hockey information from nhl.com and display in discord.",
"install_msg":"Use `[p]hockey`, `[p]hockeyset` and `[p]gdc` to see what commands are available. If you want the emojis to work please ask <@218773382617890828> to add your bot to his server hosting the emojis.",
"min_python_version":[
3,
6,
2
],
"name":"Hockey",
"permissions":[
"embed_links",
"manage_messages",
"manage_channels"
],
"requirements":[
"pytz"
],
"short":"Hockey commands",
"tags":[
"general",
"hockey",
"utility"
]
}
+949
View File
@@ -0,0 +1,949 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2018-11-17 09:51-0700\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: redgettext 2.1\n"
#: hockey.py:36
#, docstring
msgid ""
"\n"
" Gather information and post goal updates for NHL hockey teams\n"
" "
msgstr ""
#: hockey.py:105
msgid "Error grabbing game data: "
msgstr ""
#: hockey.py:126
msgid "Pickems Set Winner error: "
msgstr ""
#: hockey.py:133
msgid "Games Done Playing"
msgstr ""
#: hockey.py:137
msgid "Error tallying leaderboard:"
msgstr ""
#: hockey.py:164
msgid "Checking GDC"
msgstr ""
#: hockey.py:202
msgid "You have already voted! Changing vote to) "
msgstr ""
#: hockey.py:206
msgid "Voting has ended!"
msgstr ""
#: hockey.py:210
msgid "Don't clutter the voting message with emojis!"
msgstr ""
#: hockey.py:251 hockey.py:254
msgid "Emoji changing cancelled"
msgstr ""
#: hockey.py:266
#, docstring
msgid ""
"\n"
" Get information from NHL.com\n"
" "
msgstr ""
#: hockey.py:273
#, docstring
msgid ""
"\n"
" Setup commands for the server\n"
" "
msgstr ""
#: hockey.py:279
msgid "On"
msgstr ""
#: hockey.py:279
msgid "Off"
msgstr ""
#: hockey.py:293
msgid "[Standings"
msgstr ""
#: hockey.py:295
msgid "Standings"
msgstr ""
#: hockey.py:310
msgid " Hockey Settings"
msgstr ""
#: hockey.py:313 hockey.py:317
msgid "Standings Settings"
msgstr ""
#: hockey.py:316
msgid ""
"Hockey Settings\n"
msgstr ""
#: hockey.py:326
#, docstring
msgid ""
"\n"
" Game Day Channel setup for the server\n"
"\n"
" You can setup only a single team or all teams for the server\n"
" Game day channels are deleted and created on the day after the game is played\n"
" usually around 9AM PST\n"
" "
msgstr ""
#: hockey.py:362
msgid "```GDC settings for"
msgstr ""
#: hockey.py:363
msgid "Create Game Day Channels:"
msgstr ""
#: hockey.py:364
msgid "Delete Game Day Channels: "
msgstr ""
#: hockey.py:365
msgid "Team:"
msgstr ""
#: hockey.py:365
msgid "Current Channels:"
msgstr ""
#: hockey.py:368
msgid "GDC settings for "
msgstr ""
#: hockey.py:370
msgid "Create Game Day Channels"
msgstr ""
#: hockey.py:371
msgid "Delete Game Day Channels"
msgstr ""
#: hockey.py:372
msgid "Team"
msgstr ""
#: hockey.py:373
msgid "Current Channels"
msgstr ""
#: hockey.py:381
#, docstring
msgid ""
"\n"
" Delete all current game day channels for the server\n"
" "
msgstr ""
#: hockey.py:386
msgid "Game day channels deleted."
msgstr ""
#: hockey.py:390
#, docstring
msgid ""
"\n"
" Creates the next gdc for the server\n"
" "
msgstr ""
#: hockey.py:396
msgid "Game day channels created."
msgstr ""
#: hockey.py:400
#, docstring
msgid ""
"\n"
" Toggles the game day channel creation on this server\n"
" "
msgstr ""
#: hockey.py:405 hockey.py:431 hockey.py:557
msgid "will"
msgstr ""
#: hockey.py:405 hockey.py:431 hockey.py:557
msgid "won't"
msgstr ""
#: hockey.py:406 hockey.py:432
msgid "Game day channels "
msgstr ""
#: hockey.py:406
msgid " be created on this server."
msgstr ""
#: hockey.py:412
#, docstring
msgid ""
"\n"
" Change the category for channel creation. Channel is case sensitive.\n"
" "
msgstr ""
#: hockey.py:419
msgid "Game day channels will be created in "
msgstr ""
#: hockey.py:425
#, docstring
msgid ""
"\n"
" Toggle's auto deletion of game day channels.\n"
" "
msgstr ""
#: hockey.py:432
msgid ""
" be deleted on this server.\n"
msgstr ""
#: hockey.py:433
msgid "Note, this may not happen until the next set of games."
msgstr ""
#: hockey.py:439
#, docstring
msgid ""
"\n"
" Setup game day channels for a single team or all teams\n"
" \n"
" Required parameters:\n"
" `team` must use quotes if a space is in the name will search for partial team name\n"
" Optional Parameters:\n"
" `category` must use quotes if a space is in the name will default to current category\n"
" `delete_gdc` will tell the bot whether or not to delete game day channels automatically\n"
" must be either `True` or `False` and a category must be provided\n"
" "
msgstr ""
#: hockey.py:453
msgid "I don't have manage channels permission!"
msgstr ""
#: hockey.py:457
msgid " is not a valid team!"
msgstr ""
#: hockey.py:473
msgid "Game Day Channels for "
msgstr ""
#: hockey.py:473
msgid "setup in "
msgstr ""
#: hockey.py:481
#, docstring
msgid ""
"\n"
" Restarts the hockey loop incase there are issues with the posts\n"
" "
msgstr ""
#: hockey.py:484
msgid "Restarting..."
msgstr ""
#: hockey.py:486
msgid "loop closed..."
msgstr ""
#: hockey.py:488
msgid "restarted"
msgstr ""
#: hockey.py:494
#, docstring
msgid ""
"\n"
" Allows moderators to set a users points on the leaderboard\n"
" "
msgstr ""
#: hockey.py:503 hockey.py:852
msgid "There is no current leaderboard for this server!"
msgstr ""
#: hockey.py:511
msgid " now has "
msgstr ""
#: hockey.py:512
msgid " points on the season, "
msgstr ""
#: hockey.py:512
msgid " points for the week,"
msgstr ""
#: hockey.py:513
msgid " and "
msgstr ""
#: hockey.py:513
msgid " votes overall."
msgstr ""
#: hockey.py:518
#, docstring
msgid ""
"\n"
" Posts automatic standings when all games for the day are done\n"
"\n"
" `standings_type` can be a division, conference, team, or all\n"
" `channel` will default to the current channel or be specified\n"
" "
msgstr ""
#: hockey.py:531
msgid "You must choose from "
msgstr ""
#: hockey.py:541
msgid "Sending standings to"
msgstr ""
#: hockey.py:544
msgid " standings will now be automatically updated in "
msgstr ""
#: hockey.py:550
#, docstring
msgid ""
"\n"
" Toggles automatic standings updates\n"
"\n"
" This updates at the same time as the game day channels (usually 9AM PST)\n"
" "
msgstr ""
#: hockey.py:558
msgid "Okay, standings "
msgstr ""
#: hockey.py:558
msgid "be updated automatically."
msgstr ""
#: hockey.py:565
#, docstring
msgid ""
"\n"
" Adds a hockey team goal updates to a channel do 'all' for all teams\n"
"\n"
" `team` needs to be all or part of an NHL team if more than one team\n"
" match it will ask for the correct team.\n"
" `channel` defaults to the current channel\n"
" "
msgstr ""
#: hockey.py:575 hockey.py:618
msgid " is not an available team!"
msgstr ""
#: hockey.py:585 hockey.py:917
msgid "I don't have embed links permission!"
msgstr ""
#: hockey.py:594
msgid " goals will be posted in "
msgstr ""
#: hockey.py:600
#, docstring
msgid ""
"\n"
" Removes a teams goal updates from a channel\n"
" defaults to the current channel\n"
" "
msgstr ""
#: hockey.py:608
msgid "no teams are currently being posted in "
msgstr ""
#: hockey.py:612 hockey.py:628
msgid "All goal updates will not be posted in "
msgstr ""
#: hockey.py:631
msgid " goal updates removed from "
msgstr ""
#: hockey.py:638
#, docstring
msgid ""
"\n"
" Display the current version\n"
" "
msgstr ""
#: hockey.py:641
msgid "Hockey version "
msgstr ""
#: hockey.py:645
#, docstring
msgid "Set your role to a team role"
msgstr ""
#: hockey.py:651 hockey.py:688 hockey.py:746 hockey.py:921 hockey.py:943
msgid " Does not appear to be an NHL team!"
msgstr ""
#: hockey.py:660
msgid "role applied."
msgstr ""
#: hockey.py:663 hockey.py:700
msgid " is not an available role!"
msgstr ""
#: hockey.py:667
#, docstring
msgid "Subscribe to goal notifications"
msgstr ""
#: hockey.py:697
msgid " role applied."
msgstr ""
#: hockey.py:704
#, docstring
msgid ""
"\n"
" Displays current standings\n"
"\n"
" If a search is provided you can see a teams complete stats\n"
" by searching for team or get all standings at once \n"
" separated by division\n"
" "
msgstr ""
#: hockey.py:717
msgid " Does not appear to be a valid standing type!"
msgstr ""
#: hockey.py:733
#, docstring
msgid ""
"\n"
" Gets all NHL games for the current season\n"
"\n"
" If team is provided it will grab that teams schedule\n"
" "
msgstr ""
#: hockey.py:761
msgid " have no recent or upcoming games!"
msgstr ""
#: hockey.py:765
#, docstring
msgid ""
"\n"
" Search for a player or get a team roster\n"
" "
msgstr ""
#: hockey.py:796
msgid "{} is not an NHL team or Player!"
msgstr ""
#: hockey.py:801
#, docstring
msgid ""
"\n"
" Display a nice embed of server specific rules\n"
" "
msgstr ""
#: hockey.py:819
#, docstring
msgid ""
"\n"
" Generates a pickems page for voting on a specified day must be \"DD-MM-YYYY\"\n"
" "
msgstr ""
#: hockey.py:826
msgid ""
"**Welcome to our daily Pick'ems challenge! Below you will see today's games! Vote for who you think will win! You get one point for each correct prediction. We will be tracking points over the course of the season and will be rewarding weekly, worst and full-season winners!**\n"
"\n"
"- Click the reaction for the team you think will win the day's match-up.\n"
"- Anyone who votes for both teams will have their vote removed and will receive no points!\n"
"\n"
"\n"
"\n"
msgstr ""
#: hockey.py:866
msgid "User has left the server "
msgstr ""
#: hockey.py:889
msgid ", you're #"
msgstr ""
#: hockey.py:890
msgid " leaderboard!"
msgstr ""
#: hockey.py:902
#, docstring
msgid ""
"\n"
" Shows the current server leaderboard either seasonal or weekly\n"
" "
msgstr ""
#: hockey.py:915
#, docstring
msgid "Set the main rules page for the nhl rules command"
msgstr ""
#: hockey.py:930
msgid "Done, here's how it will look."
msgstr ""
#: hockey.py:934
#, docstring
msgid ""
"\n"
" Get team specific discord links\n"
"\n"
" choosing all will create a nicely formatted list of \n"
" all current NHL team discord server links\n"
" "
msgstr ""
#: hockey.py:959
msgid ""
"__**Hockey Discord Master List**__\n"
"```fix\n"
"- Do not join other discords to troll.\n"
"- Respect their rules & their members (Yes even the leafs & habs unfortunately).\n"
"- We don't control the servers below. If you get banned we can not get you unbanned.\n"
"- Don't be an asshole because then we all look like assholes. They won't see it as one asshole fan they will see it as a toxic fanbase.\n"
"- Salt levels may vary. Your team is the best here but don't go on another discord and preach it to an angry mob after we just won.\n"
"- Not following the above rules will result in appropriate punishments ranging from a warningto a ban. ```\n"
"\n"
"https://discord.gg/reddithockey"
msgstr ""
#: hockey.py:998
#, docstring
msgid ""
"\n"
" Testing function with testgame.json\n"
" "
msgstr ""
#: hockey.py:1027
#, docstring
msgid ""
"\n"
" Manually tally the leaderboard\n"
" "
msgstr ""
#: hockey.py:1031
msgid "Leaderboard tallying complete."
msgstr ""
#: hockey.py:1037
#, docstring
msgid ""
"\n"
" Test checking for new game day channels\n"
" "
msgstr ""
#: hockey.py:1045
#, docstring
msgid ""
"\n"
" Test the automatic standings function/manually update standings\n"
" "
msgstr ""
#: hockey.py:1056
#, docstring
msgid ""
"\n"
" Display current number of servers and channels\n"
" the cog is storing in console\n"
" "
msgstr ""
#: hockey.py:1084
#, docstring
msgid ""
"\n"
" Set custom emojis for the bot to use\n"
"\n"
" Requires you to upload a .yaml file with \n"
" emojis that the bot can see\n"
" an example may be found [here](insert link after commit)\n"
" if no emoji is provided for a team the Other\n"
" slot will be filled instead\n"
" It's recommended to have an emoji for every team\n"
" to utilize all features of the cog such as pickems\n"
" "
msgstr ""
#: hockey.py:1097
msgid "Upload the .yaml file to use. Type `exit` to cancel."
msgstr ""
#: hockey.py:1104 hockey.py:1110
msgid "That file doesn't seem to be formatted correctly."
msgstr ""
#: hockey.py:1113
msgid "New emojis set to: "
msgstr ""
#: hockey.py:1120
#, docstring
msgid ""
"\n"
" Resets the bots game data incase something goes wrong\n"
" "
msgstr ""
#: hockey.py:1133
msgid "Saved game data reset."
msgstr ""
#: hockey.py:1139
#, docstring
msgid ""
"\n"
" Sets whether or not the game day channels have been created\n"
" "
msgstr ""
#: hockey.py:1143
msgid "created_gdc set to "
msgstr ""
#: hockey.py:1148
#, docstring
msgid ""
"\n"
" Checks for manually deleted channels from the GDC channel list \n"
" and removes them\n"
" "
msgstr ""
#: hockey.py:1167
#, docstring
msgid ""
"\n"
" Removes missing channels from the config\n"
" "
msgstr ""
#: hockey.py:1178
msgid "Broken channels removed"
msgstr ""
#: hockey.py:1183
#, docstring
msgid ""
"\n"
" Removes a server that no longer exists on the bot\n"
" "
msgstr ""
#: hockey.py:1195
msgid "Saved servers the bot is no longer on have been removed."
msgstr ""
#: hockey.py:1201
#, docstring
msgid ""
"\n"
" Clears the weekly tracker on the current servers pickems\n"
"\n"
" May not be necessary anymore\n"
" "
msgstr ""
#: hockey.py:1217
#, docstring
msgid ""
"\n"
" Tests the philips Hue light integration\n"
" This is hard coded at the moment with no plans to make work generally\n"
" this will be safely ignored.\n"
" "
msgstr ""
#: hockey.py:1231
#, docstring
msgid ""
"\n"
" Toggle the console print for cog functions\n"
" "
msgstr ""
#: hockey.py:1240
msgid "Console printing is now "
msgstr ""
#: hockey.py:1245
#, docstring
msgid ""
"\n"
" Toggle the test game loop\n"
" "
msgstr ""
#: hockey.py:1252
msgid "Test loop set to "
msgstr ""
#: hockey.py:1257
#, docstring
msgid ""
"\n"
" Clears the servers current pickems object list\n"
" "
msgstr ""
#: hockey.py:1261
msgid "All pickems removed on this server."
msgstr ""
#: hockey.py:1266
#, docstring
msgid ""
"\n"
" Clears the servers pickems leaderboard\n"
" "
msgstr ""
#: hockey.py:1270
msgid "Server leaderboard reset."
msgstr ""
#: goal.py:149
msgid "Could not post goal in "
msgstr ""
#: goal.py:174
msgid "Cannot find message "
msgstr ""
#: goal.py:216
msgid "Could not edit goal in"
msgstr ""
#: goal.py:252 goal.py:253
msgid "Goals: **"
msgstr ""
#: goal.py:252 goal.py:253
msgid ""
"** \n"
"Shots: **"
msgstr ""
#: goal.py:258 goal.py:271 goal.py:282 goal.py:288
msgid " left in the "
msgstr ""
#: goal.py:258 goal.py:271 goal.py:282 goal.py:288
msgid " period"
msgstr ""
#: game.py:102
msgid "Error grabbing game data: "
msgstr ""
#: game.py:176 game.py:258
msgid "Game start "
msgstr ""
#: game.py:182 game.py:183 game.py:243 game.py:244
msgid "Goals: **"
msgstr ""
#: game.py:182 game.py:183 game.py:243 game.py:244
msgid ""
"** \n"
"Shots: **"
msgstr ""
#: game.py:201
msgid " Period Goals"
msgstr ""
#: game.py:218 game.py:219
msgid " Shootout"
msgstr ""
#: game.py:222 game.py:255
msgid "Stars of the game"
msgstr ""
#: game.py:226 game.py:228
msgid " Left in the "
msgstr ""
#: game.py:226 game.py:228
msgid " period"
msgstr ""
#: game.py:268
msgid ""
"**__Current Score__**\n"
msgstr ""
#: game.py:377
msgid " Period starting "
msgstr ""
#: game.py:377
msgid " at "
msgstr ""
#: game.py:384 game.py:408 game.py:508
msgid "Could not post goal in "
msgstr ""
#: game.py:503
msgid " minutes until "
msgstr ""
#: game.py:504
msgid " starts"
msgstr ""
#: embeds.py:16
msgid "***Any violation of the [Discord TOS](https://discordapp.com/terms) or [Community Guidelines](https://discordapp.com/guidelines) will result in immediate banning and possibly reported to discord.***"
msgstr ""
#: embeds.py:21
msgid "__RULES__"
msgstr ""
#: embeds.py:22
msgid "__**WARNING**__"
msgstr ""
#: embeds.py:38
msgid " Pickems "
msgstr ""
#: embeds.py:38
msgid " Leaderboard"
msgstr ""
#: embeds.py:40
msgid "Page"
msgstr ""
#: embeds.py:65
msgid "Shots"
msgstr ""
#: embeds.py:66
msgid "Goals"
msgstr ""
#: embeds.py:67
msgid "Assists"
msgstr ""
#: embeds.py:68
msgid "Hits"
msgstr ""
#: embeds.py:69
msgid "Face Off Percent"
msgstr ""
#: embeds.py:71
msgid "Blocked Shots"
msgstr ""
#: embeds.py:72
msgid "PIM"
msgstr ""
#: embeds.py:80
msgid "Saves"
msgstr ""
#: embeds.py:81
msgid "Save Percentage"
msgstr ""
#: embeds.py:82
msgid "Goals Against Average"
msgstr ""
#: menu.py:47
msgid "I don't have embed links permission!"
msgstr ""
#: helper.py:31
msgid ""
"There's multiple teams with that name, pick one of these:\n"
msgstr ""
#: helper.py:42 helper.py:56
msgid "I guess not."
msgstr ""
#: pickems.py:44
msgid "You have voted for "
msgstr ""
#: pickems.py:54
msgid "You did not vote on this game!"
msgstr ""
#: pickems.py:119
msgid "Pickem already exists, adding channel"
msgstr ""
#: pickems.py:183
msgid "Error tallying leaderboard in "
msgstr ""
+949
View File
@@ -0,0 +1,949 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2018-11-17 09:51-0700\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: redgettext 2.1\n"
#: hockey.py:36
#, docstring
msgid ""
"\n"
" Gather information and post goal updates for NHL hockey teams\n"
" "
msgstr ""
#: hockey.py:105
msgid "Error grabbing game data: "
msgstr ""
#: hockey.py:126
msgid "Pickems Set Winner error: "
msgstr ""
#: hockey.py:133
msgid "Games Done Playing"
msgstr ""
#: hockey.py:137
msgid "Error tallying leaderboard:"
msgstr ""
#: hockey.py:164
msgid "Checking GDC"
msgstr ""
#: hockey.py:202
msgid "You have already voted! Changing vote to) "
msgstr ""
#: hockey.py:206
msgid "Voting has ended!"
msgstr ""
#: hockey.py:210
msgid "Don't clutter the voting message with emojis!"
msgstr ""
#: hockey.py:251 hockey.py:254
msgid "Emoji changing cancelled"
msgstr ""
#: hockey.py:266
#, docstring
msgid ""
"\n"
" Get information from NHL.com\n"
" "
msgstr ""
#: hockey.py:273
#, docstring
msgid ""
"\n"
" Setup commands for the server\n"
" "
msgstr ""
#: hockey.py:279
msgid "On"
msgstr ""
#: hockey.py:279
msgid "Off"
msgstr ""
#: hockey.py:293
msgid "[Standings"
msgstr ""
#: hockey.py:295
msgid "Standings"
msgstr ""
#: hockey.py:310
msgid " Hockey Settings"
msgstr ""
#: hockey.py:313 hockey.py:317
msgid "Standings Settings"
msgstr ""
#: hockey.py:316
msgid ""
"Hockey Settings\n"
msgstr ""
#: hockey.py:326
#, docstring
msgid ""
"\n"
" Game Day Channel setup for the server\n"
"\n"
" You can setup only a single team or all teams for the server\n"
" Game day channels are deleted and created on the day after the game is played\n"
" usually around 9AM PST\n"
" "
msgstr ""
#: hockey.py:362
msgid "```GDC settings for"
msgstr ""
#: hockey.py:363
msgid "Create Game Day Channels:"
msgstr ""
#: hockey.py:364
msgid "Delete Game Day Channels: "
msgstr ""
#: hockey.py:365
msgid "Team:"
msgstr ""
#: hockey.py:365
msgid "Current Channels:"
msgstr ""
#: hockey.py:368
msgid "GDC settings for "
msgstr ""
#: hockey.py:370
msgid "Create Game Day Channels"
msgstr ""
#: hockey.py:371
msgid "Delete Game Day Channels"
msgstr ""
#: hockey.py:372
msgid "Team"
msgstr ""
#: hockey.py:373
msgid "Current Channels"
msgstr ""
#: hockey.py:381
#, docstring
msgid ""
"\n"
" Delete all current game day channels for the server\n"
" "
msgstr ""
#: hockey.py:386
msgid "Game day channels deleted."
msgstr ""
#: hockey.py:390
#, docstring
msgid ""
"\n"
" Creates the next gdc for the server\n"
" "
msgstr ""
#: hockey.py:396
msgid "Game day channels created."
msgstr ""
#: hockey.py:400
#, docstring
msgid ""
"\n"
" Toggles the game day channel creation on this server\n"
" "
msgstr ""
#: hockey.py:405 hockey.py:431 hockey.py:557
msgid "will"
msgstr ""
#: hockey.py:405 hockey.py:431 hockey.py:557
msgid "won't"
msgstr ""
#: hockey.py:406 hockey.py:432
msgid "Game day channels "
msgstr ""
#: hockey.py:406
msgid " be created on this server."
msgstr ""
#: hockey.py:412
#, docstring
msgid ""
"\n"
" Change the category for channel creation. Channel is case sensitive.\n"
" "
msgstr ""
#: hockey.py:419
msgid "Game day channels will be created in "
msgstr ""
#: hockey.py:425
#, docstring
msgid ""
"\n"
" Toggle's auto deletion of game day channels.\n"
" "
msgstr ""
#: hockey.py:432
msgid ""
" be deleted on this server.\n"
msgstr ""
#: hockey.py:433
msgid "Note, this may not happen until the next set of games."
msgstr ""
#: hockey.py:439
#, docstring
msgid ""
"\n"
" Setup game day channels for a single team or all teams\n"
" \n"
" Required parameters:\n"
" `team` must use quotes if a space is in the name will search for partial team name\n"
" Optional Parameters:\n"
" `category` must use quotes if a space is in the name will default to current category\n"
" `delete_gdc` will tell the bot whether or not to delete game day channels automatically\n"
" must be either `True` or `False` and a category must be provided\n"
" "
msgstr ""
#: hockey.py:453
msgid "I don't have manage channels permission!"
msgstr ""
#: hockey.py:457
msgid " is not a valid team!"
msgstr ""
#: hockey.py:473
msgid "Game Day Channels for "
msgstr ""
#: hockey.py:473
msgid "setup in "
msgstr ""
#: hockey.py:481
#, docstring
msgid ""
"\n"
" Restarts the hockey loop incase there are issues with the posts\n"
" "
msgstr ""
#: hockey.py:484
msgid "Restarting..."
msgstr ""
#: hockey.py:486
msgid "loop closed..."
msgstr ""
#: hockey.py:488
msgid "restarted"
msgstr ""
#: hockey.py:494
#, docstring
msgid ""
"\n"
" Allows moderators to set a users points on the leaderboard\n"
" "
msgstr ""
#: hockey.py:503 hockey.py:852
msgid "There is no current leaderboard for this server!"
msgstr ""
#: hockey.py:511
msgid " now has "
msgstr ""
#: hockey.py:512
msgid " points on the season, "
msgstr ""
#: hockey.py:512
msgid " points for the week,"
msgstr ""
#: hockey.py:513
msgid " and "
msgstr ""
#: hockey.py:513
msgid " votes overall."
msgstr ""
#: hockey.py:518
#, docstring
msgid ""
"\n"
" Posts automatic standings when all games for the day are done\n"
"\n"
" `standings_type` can be a division, conference, team, or all\n"
" `channel` will default to the current channel or be specified\n"
" "
msgstr ""
#: hockey.py:531
msgid "You must choose from "
msgstr ""
#: hockey.py:541
msgid "Sending standings to"
msgstr ""
#: hockey.py:544
msgid " standings will now be automatically updated in "
msgstr ""
#: hockey.py:550
#, docstring
msgid ""
"\n"
" Toggles automatic standings updates\n"
"\n"
" This updates at the same time as the game day channels (usually 9AM PST)\n"
" "
msgstr ""
#: hockey.py:558
msgid "Okay, standings "
msgstr ""
#: hockey.py:558
msgid "be updated automatically."
msgstr ""
#: hockey.py:565
#, docstring
msgid ""
"\n"
" Adds a hockey team goal updates to a channel do 'all' for all teams\n"
"\n"
" `team` needs to be all or part of an NHL team if more than one team\n"
" match it will ask for the correct team.\n"
" `channel` defaults to the current channel\n"
" "
msgstr ""
#: hockey.py:575 hockey.py:618
msgid " is not an available team!"
msgstr ""
#: hockey.py:585 hockey.py:917
msgid "I don't have embed links permission!"
msgstr ""
#: hockey.py:594
msgid " goals will be posted in "
msgstr ""
#: hockey.py:600
#, docstring
msgid ""
"\n"
" Removes a teams goal updates from a channel\n"
" defaults to the current channel\n"
" "
msgstr ""
#: hockey.py:608
msgid "no teams are currently being posted in "
msgstr ""
#: hockey.py:612 hockey.py:628
msgid "All goal updates will not be posted in "
msgstr ""
#: hockey.py:631
msgid " goal updates removed from "
msgstr ""
#: hockey.py:638
#, docstring
msgid ""
"\n"
" Display the current version\n"
" "
msgstr ""
#: hockey.py:641
msgid "Hockey version "
msgstr ""
#: hockey.py:645
#, docstring
msgid "Set your role to a team role"
msgstr ""
#: hockey.py:651 hockey.py:688 hockey.py:746 hockey.py:921 hockey.py:943
msgid " Does not appear to be an NHL team!"
msgstr ""
#: hockey.py:660
msgid "role applied."
msgstr ""
#: hockey.py:663 hockey.py:700
msgid " is not an available role!"
msgstr ""
#: hockey.py:667
#, docstring
msgid "Subscribe to goal notifications"
msgstr ""
#: hockey.py:697
msgid " role applied."
msgstr ""
#: hockey.py:704
#, docstring
msgid ""
"\n"
" Displays current standings\n"
"\n"
" If a search is provided you can see a teams complete stats\n"
" by searching for team or get all standings at once \n"
" separated by division\n"
" "
msgstr ""
#: hockey.py:717
msgid " Does not appear to be a valid standing type!"
msgstr ""
#: hockey.py:733
#, docstring
msgid ""
"\n"
" Gets all NHL games for the current season\n"
"\n"
" If team is provided it will grab that teams schedule\n"
" "
msgstr ""
#: hockey.py:761
msgid " have no recent or upcoming games!"
msgstr ""
#: hockey.py:765
#, docstring
msgid ""
"\n"
" Search for a player or get a team roster\n"
" "
msgstr ""
#: hockey.py:796
msgid "{} is not an NHL team or Player!"
msgstr ""
#: hockey.py:801
#, docstring
msgid ""
"\n"
" Display a nice embed of server specific rules\n"
" "
msgstr ""
#: hockey.py:819
#, docstring
msgid ""
"\n"
" Generates a pickems page for voting on a specified day must be \"DD-MM-YYYY\"\n"
" "
msgstr ""
#: hockey.py:826
msgid ""
"**Welcome to our daily Pick'ems challenge! Below you will see today's games! Vote for who you think will win! You get one point for each correct prediction. We will be tracking points over the course of the season and will be rewarding weekly, worst and full-season winners!**\n"
"\n"
"- Click the reaction for the team you think will win the day's match-up.\n"
"- Anyone who votes for both teams will have their vote removed and will receive no points!\n"
"\n"
"\n"
"\n"
msgstr ""
#: hockey.py:866
msgid "User has left the server "
msgstr ""
#: hockey.py:889
msgid ", you're #"
msgstr ""
#: hockey.py:890
msgid " leaderboard!"
msgstr ""
#: hockey.py:902
#, docstring
msgid ""
"\n"
" Shows the current server leaderboard either seasonal or weekly\n"
" "
msgstr ""
#: hockey.py:915
#, docstring
msgid "Set the main rules page for the nhl rules command"
msgstr ""
#: hockey.py:930
msgid "Done, here's how it will look."
msgstr ""
#: hockey.py:934
#, docstring
msgid ""
"\n"
" Get team specific discord links\n"
"\n"
" choosing all will create a nicely formatted list of \n"
" all current NHL team discord server links\n"
" "
msgstr ""
#: hockey.py:959
msgid ""
"__**Hockey Discord Master List**__\n"
"```fix\n"
"- Do not join other discords to troll.\n"
"- Respect their rules & their members (Yes even the leafs & habs unfortunately).\n"
"- We don't control the servers below. If you get banned we can not get you unbanned.\n"
"- Don't be an asshole because then we all look like assholes. They won't see it as one asshole fan they will see it as a toxic fanbase.\n"
"- Salt levels may vary. Your team is the best here but don't go on another discord and preach it to an angry mob after we just won.\n"
"- Not following the above rules will result in appropriate punishments ranging from a warningto a ban. ```\n"
"\n"
"https://discord.gg/reddithockey"
msgstr ""
#: hockey.py:998
#, docstring
msgid ""
"\n"
" Testing function with testgame.json\n"
" "
msgstr ""
#: hockey.py:1027
#, docstring
msgid ""
"\n"
" Manually tally the leaderboard\n"
" "
msgstr ""
#: hockey.py:1031
msgid "Leaderboard tallying complete."
msgstr ""
#: hockey.py:1037
#, docstring
msgid ""
"\n"
" Test checking for new game day channels\n"
" "
msgstr ""
#: hockey.py:1045
#, docstring
msgid ""
"\n"
" Test the automatic standings function/manually update standings\n"
" "
msgstr ""
#: hockey.py:1056
#, docstring
msgid ""
"\n"
" Display current number of servers and channels\n"
" the cog is storing in console\n"
" "
msgstr ""
#: hockey.py:1084
#, docstring
msgid ""
"\n"
" Set custom emojis for the bot to use\n"
"\n"
" Requires you to upload a .yaml file with \n"
" emojis that the bot can see\n"
" an example may be found [here](insert link after commit)\n"
" if no emoji is provided for a team the Other\n"
" slot will be filled instead\n"
" It's recommended to have an emoji for every team\n"
" to utilize all features of the cog such as pickems\n"
" "
msgstr ""
#: hockey.py:1097
msgid "Upload the .yaml file to use. Type `exit` to cancel."
msgstr ""
#: hockey.py:1104 hockey.py:1110
msgid "That file doesn't seem to be formatted correctly."
msgstr ""
#: hockey.py:1113
msgid "New emojis set to: "
msgstr ""
#: hockey.py:1120
#, docstring
msgid ""
"\n"
" Resets the bots game data incase something goes wrong\n"
" "
msgstr ""
#: hockey.py:1133
msgid "Saved game data reset."
msgstr ""
#: hockey.py:1139
#, docstring
msgid ""
"\n"
" Sets whether or not the game day channels have been created\n"
" "
msgstr ""
#: hockey.py:1143
msgid "created_gdc set to "
msgstr ""
#: hockey.py:1148
#, docstring
msgid ""
"\n"
" Checks for manually deleted channels from the GDC channel list \n"
" and removes them\n"
" "
msgstr ""
#: hockey.py:1167
#, docstring
msgid ""
"\n"
" Removes missing channels from the config\n"
" "
msgstr ""
#: hockey.py:1178
msgid "Broken channels removed"
msgstr ""
#: hockey.py:1183
#, docstring
msgid ""
"\n"
" Removes a server that no longer exists on the bot\n"
" "
msgstr ""
#: hockey.py:1195
msgid "Saved servers the bot is no longer on have been removed."
msgstr ""
#: hockey.py:1201
#, docstring
msgid ""
"\n"
" Clears the weekly tracker on the current servers pickems\n"
"\n"
" May not be necessary anymore\n"
" "
msgstr ""
#: hockey.py:1217
#, docstring
msgid ""
"\n"
" Tests the philips Hue light integration\n"
" This is hard coded at the moment with no plans to make work generally\n"
" this will be safely ignored.\n"
" "
msgstr ""
#: hockey.py:1231
#, docstring
msgid ""
"\n"
" Toggle the console print for cog functions\n"
" "
msgstr ""
#: hockey.py:1240
msgid "Console printing is now "
msgstr ""
#: hockey.py:1245
#, docstring
msgid ""
"\n"
" Toggle the test game loop\n"
" "
msgstr ""
#: hockey.py:1252
msgid "Test loop set to "
msgstr ""
#: hockey.py:1257
#, docstring
msgid ""
"\n"
" Clears the servers current pickems object list\n"
" "
msgstr ""
#: hockey.py:1261
msgid "All pickems removed on this server."
msgstr ""
#: hockey.py:1266
#, docstring
msgid ""
"\n"
" Clears the servers pickems leaderboard\n"
" "
msgstr ""
#: hockey.py:1270
msgid "Server leaderboard reset."
msgstr ""
#: goal.py:149
msgid "Could not post goal in "
msgstr ""
#: goal.py:174
msgid "Cannot find message "
msgstr ""
#: goal.py:216
msgid "Could not edit goal in"
msgstr ""
#: goal.py:252 goal.py:253
msgid "Goals: **"
msgstr ""
#: goal.py:252 goal.py:253
msgid ""
"** \n"
"Shots: **"
msgstr ""
#: goal.py:258 goal.py:271 goal.py:282 goal.py:288
msgid " left in the "
msgstr ""
#: goal.py:258 goal.py:271 goal.py:282 goal.py:288
msgid " period"
msgstr ""
#: game.py:102
msgid "Error grabbing game data: "
msgstr ""
#: game.py:176 game.py:258
msgid "Game start "
msgstr ""
#: game.py:182 game.py:183 game.py:243 game.py:244
msgid "Goals: **"
msgstr ""
#: game.py:182 game.py:183 game.py:243 game.py:244
msgid ""
"** \n"
"Shots: **"
msgstr ""
#: game.py:201
msgid " Period Goals"
msgstr ""
#: game.py:218 game.py:219
msgid " Shootout"
msgstr ""
#: game.py:222 game.py:255
msgid "Stars of the game"
msgstr ""
#: game.py:226 game.py:228
msgid " Left in the "
msgstr ""
#: game.py:226 game.py:228
msgid " period"
msgstr ""
#: game.py:268
msgid ""
"**__Current Score__**\n"
msgstr ""
#: game.py:377
msgid " Period starting "
msgstr ""
#: game.py:377
msgid " at "
msgstr ""
#: game.py:384 game.py:408 game.py:508
msgid "Could not post goal in "
msgstr ""
#: game.py:503
msgid " minutes until "
msgstr ""
#: game.py:504
msgid " starts"
msgstr ""
#: embeds.py:16
msgid "***Any violation of the [Discord TOS](https://discordapp.com/terms) or [Community Guidelines](https://discordapp.com/guidelines) will result in immediate banning and possibly reported to discord.***"
msgstr ""
#: embeds.py:21
msgid "__RULES__"
msgstr ""
#: embeds.py:22
msgid "__**WARNING**__"
msgstr ""
#: embeds.py:38
msgid " Pickems "
msgstr ""
#: embeds.py:38
msgid " Leaderboard"
msgstr ""
#: embeds.py:40
msgid "Page"
msgstr ""
#: embeds.py:65
msgid "Shots"
msgstr ""
#: embeds.py:66
msgid "Goals"
msgstr ""
#: embeds.py:67
msgid "Assists"
msgstr ""
#: embeds.py:68
msgid "Hits"
msgstr ""
#: embeds.py:69
msgid "Face Off Percent"
msgstr ""
#: embeds.py:71
msgid "Blocked Shots"
msgstr ""
#: embeds.py:72
msgid "PIM"
msgstr ""
#: embeds.py:80
msgid "Saves"
msgstr ""
#: embeds.py:81
msgid "Save Percentage"
msgstr ""
#: embeds.py:82
msgid "Goals Against Average"
msgstr ""
#: menu.py:47
msgid "I don't have embed links permission!"
msgstr ""
#: helper.py:31
msgid ""
"There's multiple teams with that name, pick one of these:\n"
msgstr ""
#: helper.py:42 helper.py:56
msgid "I guess not."
msgstr ""
#: pickems.py:44
msgid "You have voted for "
msgstr ""
#: pickems.py:54
msgid "You did not vote on this game!"
msgstr ""
#: pickems.py:119
msgid "Pickem already exists, adding channel"
msgstr ""
#: pickems.py:183
msgid "Error tallying leaderboard in "
msgstr ""
File diff suppressed because it is too large. Load diff
+90
View File
@@ -0,0 +1,90 @@
import asyncio
import discord
import aiohttp
from redbot.core.commands import Context
from .embeds import *
from .standings import Standings
from .game import Game
from redbot.core.i18n import Translator
_ = Translator("Hockey", __file__)
numbs = {
"next": "➡",
"back": "⬅",
"exit": "❌"
}
async def hockey_menu(ctx:Context, display_type:str, post_list: list,
message: discord.Message=None,
page=0, timeout: int=30):
"""menu control logic for this taken from
https://github.com/Lunar-Dust/Dusty-Cogs/blob/master/menu/menu.py"""
if ctx.channel.permissions_for(ctx.me).embed_links:
if display_type == "standings":
em = await Standings.build_standing_embed(post_list, page)
if display_type == "division":
em = await Standings.build_standing_embed(post_list, page)
if display_type == "conference":
em = await Standings.build_standing_embed(post_list, page)
if display_type == "teams":
em = await Standings.build_standing_embed(post_list, page)
if display_type == "all":
em = await Standings.all_standing_embed(post_list, page)
if display_type == "roster":
em = await roster_embed(post_list, page)
if display_type == "game":
em = await Game.get_game_embed(post_list, page)
if display_type == "season":
leaderboard = {"type": "Seasonal", "lists": post_list}
em = await make_leaderboard_embed(ctx.guild, leaderboard, page)
if display_type == "weekly":
leaderboard = {"type": "Weekly", "lists": post_list}
em = await make_leaderboard_embed(ctx.guild, leaderboard, page)
if display_type == "worst":
leaderboard = {"type": "Worst", "lists": post_list}
em = await make_leaderboard_embed(ctx.guild, leaderboard, page)
else:
await ctx.send(_("I don't have embed links permission!"))
return
if not message:
message = await ctx.send(embed=em)
await message.add_reaction("⬅")
await message.add_reaction("❌")
await message.add_reaction("➡")
else:
# message edits don't return the message object anymore lol
await message.edit(embed=em)
check = lambda react, user:user == ctx.message.author and react.emoji in ["➡", "⬅", "❌"] and react.message.id == message.id
try:
react, user = await ctx.bot.wait_for("reaction_add", check=check, timeout=timeout)
except asyncio.TimeoutError:
await message.remove_reaction("⬅", ctx.me)
await message.remove_reaction("❌", ctx.me)
await message.remove_reaction("➡", ctx.me)
return None
else:
reacts = {v: k for k, v in numbs.items()}
react = reacts[react.emoji]
if react == "next":
next_page = 0
if page == len(post_list) - 1:
next_page = 0 # Loop around to the first item
else:
next_page = page + 1
if ctx.channel.permissions_for(ctx.me).manage_messages:
await message.remove_reaction("➡", ctx.message.author)
return await hockey_menu(ctx, display_type, post_list, message=message,
page=next_page, timeout=timeout)
elif react == "back":
next_page = 0
if page == 0:
next_page = len(post_list) - 1 # Loop around to the last item
else:
next_page = page - 1
if ctx.channel.permissions_for(ctx.me).manage_messages:
await message.remove_reaction("⬅", ctx.message.author)
return await hockey_menu(ctx, display_type, post_list, message=message,
page=next_page, timeout=timeout)
else:
return await message.delete()
+88
View File
@@ -0,0 +1,88 @@
import asyncio
from phue import Bridge
import functools
class Oilers:
def __init__(self, bot):
self.bot = bot
self.bridge = Bridge("192.168.0.35")
self.lights = self.bridge.lights
self.bridge2 = Bridge("192.168.0.115")
self.lights2 = self.bridge2.lights
self.cur_lights = {}
self.cur_lights2 = {}
# @commands.command(pass_context=True)
async def goal_lights(self):
task = functools.partial(self.get_current_lights_setting)
task = self.bot.loop.run_in_executor(None, task)
try:
temp = await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
return
for i in range(5):
task = functools.partial(self.oilers_hex_set, x=1.0, y=1.0)
task = self.bot.loop.run_in_executor(None, task)
try:
temp = await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
pass
# await self.oilers_hex_set(1.0, 1.0)
await asyncio.sleep(0.5)
task = functools.partial(self.oilers_hex_set, x=0, y=0)
task = self.bot.loop.run_in_executor(None, task)
try:
temp = await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
pass
# await self.oilers_hex_set(0, 0)
await asyncio.sleep(0.5)
task = functools.partial(self.reset_light_setting)
task = self.bot.loop.run_in_executor(None, task)
try:
temp = await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
return
def reset_light_setting(self):
for light in self.lights:
old_temp = self.cur_lights[light.name][1]
if old_temp < 154:
old_temp = 154
if old_temp > 500:
old_temp = 499
light.colortemp = old_temp
light.on = self.cur_lights[light.name][0]
for light in self.lights2:
old_temp = self.cur_lights2[light.name][1]
if old_temp < 154:
old_temp = 154
if old_temp > 500:
old_temp = 499
light.colortemp = old_temp
light.on = self.cur_lights2[light.name][0]
return
def get_current_lights_setting(self):
for light in self.lights:
self.cur_lights[light.name] = [light.on, light.colortemp]
for light in self.lights2:
self.cur_lights2[light.name] = [light.on, light.colortemp]
return
def oilers_hex_set(self, x:float, y:float):
"""Sets the colour for Oilers Goals"""
if x > 1.0 or x < 0.0:
x = 1.0
if y > 1.0 or y < 0.0:
y = 1.0
for light in self.lights:
if not light.on:
light.on = True
light.xy = [x, y]
for light in self.lights2:
if not light.on:
light.on = True
light.xy = [x, y]
+207
View File
@@ -0,0 +1,207 @@
from .errors import *
from datetime import datetime
from .constants import TEAMS
from .helper import *
from redbot.core.i18n import Translator
_ = Translator("Hockey", __file__)
class Pickems:
"""
Pickems object for handling votes on games for the day
"""
def __init__(self, message:list, channel:list, game_start:str, home_team:str, away_team:str, votes:list, winner:str=None):
super().__init__()
self.message = message
self.channel = channel
self.game_start = datetime.strptime(game_start, "%Y-%m-%dT%H:%M:%SZ")
self.home_team = home_team
self.away_team = away_team
self.votes = votes
self.home_emoji = TEAMS[home_team]["emoji"] if home_team in TEAMS else "nhl:496510372828807178"
self.away_emoji = TEAMS[away_team]["emoji"] if away_team in TEAMS else "nhl:496510372828807178"
self.winner = winner
def add_vote(self, user_id, team):
time_now = datetime.utcnow()
team_choice = None
if str(team.id) in self.home_emoji:
team_choice = self.home_team
if str(team.id) in self.away_emoji:
team_choice = self.away_team
if team_choice is None:
raise NotAValidTeamError()
user_voted = False
for user, choice in self.votes:
if user_id == user:
user_voted = True
if time_now > self.game_start:
if choice == self.home_team:
emoji = self.home_emoji
if choice == self.away_team:
emoji = self.away_emoji
raise VotingHasEndedError(_("You have voted for ") + f"<:{emoji}>")
if choice != team_choice:
if (user, choice) in self.votes:
self.votes.remove((user, choice))
if (user, team_choice) in self.votes:
# Redundancy so we don't end up with duplicate votes
self.votes.remove((user, team_choice))
self.votes.append((user_id, team_choice))
raise UserHasVotedError("{} {}".format(team, team_choice))
if time_now > self.game_start and not user_voted:
raise VotingHasEndedError(_("You did not vote on this game!"))
if not user_voted and team_choice is not None:
self.votes.append((user_id, team_choice))
async def set_pickem_winner(self, game):
"""
Sets the pickem object winner from game object
"""
if game.home_score > game.away_score:
self.winner = self.home_team
if game.away_score > game.home_score:
self.winner = self.away_team
@staticmethod
async def find_pickems_object(bot, game):
"""
Returns a list of all pickems on the bot for that game
"""
config = hockey_config()
return_pickems = []
for guild_id in await config.all_guilds():
guild = bot.get_guild(int(guild_id))
pickems = await config.guild(guild).pickems()
if pickems is None:
pickems = []
for p in pickems:
if p["home_team"] == game.home_team and p["away_team"] == game.away_team:
if p["game_start"] == game.game_start.strftime("%Y-%m-%dT%H:%M:%SZ"):
# Only use the old one if the date is the same and the same teams are playing
return_pickems.append(Pickems.from_json(p))
return return_pickems
@staticmethod
async def set_guild_pickem_winner(bot, game):
pickem_obj = await Pickems.find_pickems_object(bot, game)
config = hockey_config()
for pickem in pickem_obj:
for channel in pickem.channel:
chn = bot.get_channel(channel)
if chn is None:
continue
if pickem.winner != None:
continue
p_data = await config.guild(chn.guild).pickems()
p_data.remove(pickem.to_json())
await pickem.set_pickem_winner(game)
p_data.append(pickem.to_json())
await config.guild(chn.guild).pickems.set(p_data)
@staticmethod
async def create_pickem_object(guild, message, channel, game):
"""
Checks to see if a pickem object is already created for the game
if not it creates one or adds the message, channel to the current ones
"""
config = hockey_config()
pickems = await config.guild(guild).pickems()
if pickems is None:
pickems = []
old_pickem = None
for p in pickems:
if p["home_team"] == game.home_team and p["away_team"] == game.away_team:
if p["game_start"] == game.game_start.strftime("%Y-%m-%dT%H:%M:%SZ"):
# Only use the old one if the date is the same and the same teams are playing
print(_("Pickem already exists, adding channel"))
old_pickem = p
if old_pickem is None:
pickems.append({"message":[message.id],
"channel":[channel.id],
"game_start": game.game_start.strftime("%Y-%m-%dT%H:%M:%SZ"),
"home_team":game.home_team,
"away_team": game.away_team,
"votes": [],
"winner":None})
else:
pickems.remove(old_pickem)
old_pickem["message"].append(message.id)
old_pickem["channel"].append(channel.id)
pickems.append(old_pickem)
await config.guild(guild).pickems.set(pickems)
@staticmethod
async def reset_weekly(bot):
# Reset the weekly leaderboard for all servers
config =hockey_config()
for guild_id in await config.all_guilds():
guild = bot.get_guild(id=guild_id)
if guild is None:
continue
leaderboard = await config.guild(guild).leaderboard()
if leaderboard is None:
leaderboard = {}
for user in leaderboard:
leaderboard[str(user)]["weekly"] = 0
await config.guild(guild).leaderboard.set(leaderboard)
@staticmethod
async def tally_leaderboard(bot):
"""
This should be where the pickems is removed and tallies are added
to the leaderboard
"""
config = hockey_config()
for guild_id in await config.all_guilds():
guild = bot.get_guild(id=guild_id)
if guild is None:
continue
try:
pickem_list_json = await config.guild(guild).pickems()
if pickem_list_json is None:
continue
pickem_list = [Pickems.from_json(p) for p in pickem_list_json]
for pickems in pickem_list:
if pickems.winner is not None:
leaderboard = await config.guild(guild).leaderboard()
if leaderboard is None:
leaderboard = {}
for user, choice in pickems.votes:
if str(user) not in leaderboard:
leaderboard[str(user)] = {"season": 0, "weekly": 0, "total":0}
if choice == pickems.winner:
if str(user) not in leaderboard:
leaderboard[str(user)] = {"season": 1, "weekly": 1, "total":0}
else:
leaderboard[str(user)]["season"] += 1
leaderboard[str(user)]["weekly"] += 1
if "total" not in leaderboard[str(user)]:
leaderboard[str(user)]["total"] = 0
leaderboard[str(user)]["total"] += 1
await config.guild(guild).leaderboard.set(leaderboard)
await config.guild(guild).pickems.set([p.to_json() for p in pickem_list if p.winner is None])
except Exception as e:
print(_("Error tallying leaderboard in ") + f"{guild.name} {e}")
def to_json(self) -> dict:
return {
"message" : self.message,
"channel" : self.channel,
"game_start" : self.game_start.strftime("%Y-%m-%dT%H:%M:%SZ"),
"home_team" : self.home_team,
"away_team" : self.away_team,
"votes" : self.votes,
"winner" : self.winner
}
@classmethod
def from_json(cls, data: dict):
return cls(data["message"], data["channel"], data["game_start"],
data["home_team"], data["away_team"], data["votes"], data["winner"])
+253
View File
@@ -0,0 +1,253 @@
from datetime import datetime
import aiohttp
import discord
from .constants import BASE_URL, TEAMS
from .helper import hockey_config
class Standings:
def __init__(self, name:str, division:str, conference:str, division_rank:int, conference_rank:int,
league_rank:int, wins:int, losses:int, ot:int, gp:int, pts:int, streak:int, streak_type:str,
goals:int, gaa:int, last_updated:str):
super().__init__()
self.name = name
self.division = division
self.conference = conference
self.division_rank = division_rank
self.conference_rank = conference_rank
self.league_rank = league_rank
self.wins = wins
self.losses = losses
self.ot = ot
self.gp = gp
self.pts = pts
self.streak = streak
self.streak_type = streak_type
self.goals = goals
self.gaa = gaa
self.last_updated = datetime.strptime(last_updated, "%Y-%m-%dT%H:%M:%SZ")
def to_json(self) -> dict:
return {
"team" : self.team,
"division": self.division_rank,
"conference" : self.conference_rank,
"division_rank" : self.division_rank,
"conference_rank" : self.conference_rank,
"league_rank" : self.league_rank,
"wins" : self.wins,
"losses" : self.losses,
"ot" : self.ot,
"gp" : self.gp,
"pts" : self.pts,
"streak" : self.streak,
"streak_type" : self.streak_type,
"goals" : self.goals,
"gaa" : self.gaa,
"last_updated": self.last_updated.strftime("%Y-%m-%dT%H:%M:%SZ"),
}
@staticmethod
async def get_team_standings(style):
"""
Creates a list of standings when given a particular style
accepts Division names, Conference names, and Team names
returns a list of standings objects and the location of the given
style in the list
"""
async with aiohttp.ClientSession() as session:
async with session.get(BASE_URL + "/api/v1/standings") as resp:
data = await resp.json()
conference = ["eastern", "western", "conference"]
division = ["metropolitan", "atlantic", "pacific", "central", "division"]
if style.lower() in conference:
e = [await Standings.from_json(team, record["division"]["name"], record["conference"]["name"])\
for record in data["records"] for team in record["teamRecords"] \
if record["conference"]["name"] =="Eastern"]
w = [await Standings.from_json(team, record["division"]["name"], record["conference"]["name"])\
for record in data["records"] for team in record["teamRecords"] \
if record["conference"]["name"] =="Western"]
index = 0
for div in [e, w]:
print(div[0].conference)
if div[0].conference.lower() == style and style != "conference":
index = [e, w].index(div)
return [e, w], index
if style.lower() in division:
new_list = []
for record in data["records"]:
new_list.append([await Standings.from_json(team, record["division"]["name"],\
record["conference"]["name"]) for team in record["teamRecords"]])
index = 0
for div in new_list:
if div[0].division.lower() == style and style != "division":
index = new_list.index(div)
return new_list, index
else:
all_teams = [await Standings.from_json(team, record["division"]["name"], record["conference"]["name"])\
for record in data["records"] for team in record["teamRecords"]]
index = 0
for team in all_teams:
if team.name.lower() == style:
index = all_teams.index(team)
return all_teams, index
@staticmethod
async def post_automatic_standings(bot):
"""
Automatically update a standings embed with the latest stats
run when new games for the day is updated
"""
print("Updating Standings.")
config = hockey_config()
all_guilds = await config.all_guilds()
for guilds in all_guilds:
guild = bot.get_guild(guilds)
if guild is None:
continue
print(guild.name)
if await config.guild(guild).post_standings():
search = await config.guild(guild).standings_type()
if search is None:
continue
standings_channel = await config.guild(guild).standings_channel()
if standings_channel is None:
continue
channel = bot.get_channel(standings_channel)
if channel is None:
continue
standings_msg = await config.guild(guild).standings_msg()
if standings_msg is None:
continue
message = await channel.get_message(standings_msg)
standings, page = await Standings.get_team_standings(search)
if search != "all":
em = await Standings.build_standing_embed(standings, page)
else:
em = await Standings.all_standing_embed(standings, page)
if message is not None:
await message.edit(embed=em)
@classmethod
async def from_json(cls, data: dict, division:str, conference:str):
if "streak" in data:
streak_number = data["streak"]["streakNumber"]
streak_type = data["streak"]["streakType"]
else:
streak_number = 0
streak_type = 0
return cls(data["team"]["name"],
division,
conference,
data["divisionRank"],
data["conferenceRank"],
data["leagueRank"],
data["leagueRecord"]["wins"],
data["leagueRecord"]["losses"],
data["leagueRecord"]["ot"],
data["gamesPlayed"],
data["points"],
streak_number,
streak_type,
data["goalsScored"],
data["goalsAgainst"],
data["lastUpdated"]
)
@staticmethod
async def all_standing_embed(post_standings, page=0):
"""
Builds the standing embed when all TEAMS are selected
"""
em = discord.Embed()
new_dict = {}
nhl_icon = "https://cdn.bleacherreport.net/images/team_logos/328x328/nhl.png"
latest_timestamp = post_standings[0].last_updated
for team in post_standings:
if team.division not in new_dict:
new_dict[team.division] = ""
emoji=TEAMS[team.name]["emoji"]
new_dict[team.division] += (f"{team.division_rank}. <:{emoji}> GP: **{team.gp}** "
f"W: **{team.wins}** L: **{team.losses}** OT: "
f"**{team.ot}** PTS: **{team.pts}**\n")
if team == post_standings[-1]:
new_dict[team.division] += "\nFrom: https://www.nhl.com/standings"
for div in new_dict:
em.add_field(name=f"{div} Division", value=new_dict[div])
em.set_author(name="NHL Standings", url="https://www.nhl.com/standings",
icon_url="https://cdn.bleacherreport.net/images/team_logos/328x328/nhl.png")
em.set_thumbnail(url=nhl_icon)
em.timestamp = latest_timestamp
em.set_footer(text="Stats Last Updated", icon_url=nhl_icon)
return em
@staticmethod
async def build_standing_embed(post_list, page=0):
"""
Builds the standings type based on number of items in the list
"""
team_stats = post_list[page]
em = discord.Embed()
if type(team_stats) is not list:
em.set_author(name="# {} {}".format(team_stats.league_rank, team_stats.name),
url="https://www.nhl.com/standings",
icon_url=TEAMS[team_stats.name]["logo"])
em.colour = int(TEAMS[team_stats.name]["home"].replace("#", ""), 16)
em.set_thumbnail(url=TEAMS[team_stats.name]["logo"])
em.add_field(name="Division", value="# " + team_stats.division_rank)
em.add_field(name="Conference", value="# " + team_stats.conference_rank)
em.add_field(name="Wins", value=team_stats.wins)
em.add_field(name="Losses", value=team_stats.losses)
em.add_field(name="OT", value=team_stats.ot)
em.add_field(name="Points", value=team_stats.pts)
em.add_field(name="Games Played", value=team_stats.gp)
em.add_field(name="Goals Scored", value=team_stats.goals)
em.add_field(name="Goals Against", value=team_stats.gaa)
em.add_field(name="Current Streak", value="{} {}".format(team_stats.streak, team_stats.streak_type))
# timestamp = datetime.strptime(team_stats.last_updated, "%Y-%m-%dT%H:%M:%SZ")
em.timestamp = team_stats.last_updated
em.set_footer(text="Stats last Updated", icon_url=TEAMS[team_stats.name]["logo"])
return em
msg = ""
# timestamp = datetime.strptime(team_stats[0].last_updated, "%Y-%m-%dT%H:%M:%SZ")
em.timestamp = team_stats[0].last_updated
if len(team_stats) <= 8:
for team in team_stats:
emoji=TEAMS[team.name]["emoji"]
msg += (f"{team.division_rank}. <:{emoji}> GP: **{team.gp}** "
f"W: **{team.wins}** L: **{team.losses}** OT: "
f"**{team.ot}** PTS: **{team.pts}**\n")
em.description = msg
division = team_stats[0].division
division_logo = TEAMS["Team {}".format(division)]["logo"]
em.colour = int(TEAMS["Team {}".format(division)]["home"].replace("#", ""), 16)
em.set_author(name=division + " Division", url="https://www.nhl.com/standings", icon_url=division_logo)
em.set_footer(text="Stats last Updated", icon_url=division_logo)
em.set_thumbnail(url=division_logo)
return em
if len(team_stats) > 8 and len(team_stats) <= 16:
newteam_stats = sorted(team_stats, key=lambda k: int(k.conference_rank))
for team in newteam_stats:
emoji=TEAMS[team.name]["emoji"]
msg += (f"{team.conference_rank}. <:{emoji}> GP: **{team.gp}** "
f"W: **{team.wins}** L: **{team.losses}** OT: "
f"**{team.ot}** PTS: **{team.pts}**\n")
em.description = msg
conference = team_stats[0].conference
em.colour = int("c41230", 16) if conference == "Eastern" else int("003e7e", 16)
logo = {"Eastern":"https://upload.wikimedia.org/wikipedia/en/thumb/1/16/NHL_Eastern_Conference.svg/1280px-NHL_Eastern_Conference.svg.png",
"Western":"https://upload.wikimedia.org/wikipedia/en/thumb/6/65/NHL_Western_Conference.svg/1280px-NHL_Western_Conference.svg.png"}
em.set_author(name=conference + " Conference", url="https://www.nhl.com/standings", icon_url=logo[conference])
em.set_thumbnail(url=logo[conference])
em.set_footer(text="Stats last Updated", icon_url=logo[conference])
return em
+27
View File
@@ -0,0 +1,27 @@
class TeamEntry:
def __init__(self, game_state:str, team_name: str, period:int,
channel: list, goal_id: dict, created_channel:list, game_start:str):
super().__init__()
self.game_state = game_state
self.team_name = team_name
self.period = period
self.channel = channel
self.goal_id = goal_id
self.created_channel = created_channel
self.game_start = game_start
def to_json(self) -> dict:
return {
"team_name": self.team_name,
"game_state": self.game_state,
"channel": self.channel,
"period": self.period,
"created_channel": self.created_channel,
"game_start": self.game_start,
"goal_id": self.goal_id
}
@classmethod
def from_json(cls, data: dict):
return cls(data["team_name"], data["game_state"], data["game_start"],
data["channel"], data["period"], data["goal_id"], data["created_channel"])
+16288
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
from .hue import Hue
def setup(bot):
bot.add_cog(Hue(bot))
+336
View File
@@ -0,0 +1,336 @@
from random import choice as randchoice
from datetime import datetime as dt
from redbot.core import commands
import discord
from redbot.core import Config
from redbot.core import checks
import random
import os
import asyncio
from phue import Bridge
class Hue(getattr(commands, "Cog", object)):
"""
Control philips hue light on the same network as the bot
"""
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 1384534876565)
default_global = {"ip":None}
self.bridge = None
self.lights = None
async def get_bridge(self):
if self.bridge is None:
try:
self.bridge = Bridge(await self.config.ip())
self.lights = self.bridge.lights
return True
except Exception as e:
print(e)
return False
else:
return True
# @commands.command(pass_context=True)
async def oilersgoal(self):
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
old_lights = {}
for light in self.lights:
old_lights[light.name] = [light.on, light.colortemp]
for i in range(10):
await self.oilers_hex_set(1.0, 1.0)
await asyncio.sleep(0.5)
await self.oilers_hex_set(0, 0)
await asyncio.sleep(0.5)
for light in self.lights:
light.on = old_lights[light.name][0]
light.colortemp = old_lights[light.name][1]
async def oilers_hex_set(self, x:float, y:float, *, name=None):
"""Sets the colour for Oilers Goals"""
if x > 1.0 or x < 0.0:
x = 1.0
if y > 1.0 or y < 0.0:
y = 1.0
for light in self.lights:
if not light.on:
light.on = True
light.xy = [x, y]
@commands.group(pass_context=True, name="hue")
@checks.is_owner()
async def _hue(self, ctx):
"""Commands for interacting with Hue lights"""
pass
@_hue.command(name="connect")
async def hue_connect(self):
"""Setup command if bridge cannot connect"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
self.bridge.connect()
@_hue.command(pass_context=True, name="set")
async def hue_setup(self, ctx, ip):
"""
Set the IP address of the hue bridge
`ip` is the bridges IP address
"""
await self.config.ip.set(ip)
self.bridge = Bridge(await self.config.ip())
self.lights = self.bridge.lights
@_hue.command(pass_context=True, name="check")
async def check_api(self, ctx):
"""Gets light data from bridge and prints to terminal"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
print(self.bridge.get_api())
async def max_min_check(self, value, max, min):
if value > max:
return max
if value < min:
return min
else:
return value
@_hue.command(pass_context=True, name="brightness")
async def brightness_set(self, ctx, brightness:int=254, *, name=None):
"""
Sets the brightness for lights
`brightness` the level of brightness to set
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
brightness = await self.max_min_check(brightness, 254, 0)
for light in self.lights:
if name is None or light.name.lower() == name.lower() and light.on:
light.brightness = brightness
@_hue.command(pass_context=True, name="temp", aliases=["ct", "colourtemp", "temperature"])
async def colourtemp_set(self, ctx, ct:int=500, *, name=None):
"""
Sets the colour temperature for lights
`ct` must be a number the colour temperature to set
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
ct = await self.max_min_check(ct, 600, 154)
for light in self.lights:
if name is None or light.name.lower() == name.lower() and light.on:
light.colortemp = ct
@_hue.command(pass_context=True, name="hue")
async def hue_set(self, ctx, hue:int=25000, *, name=None):
"""
Sets the hue for lights
`hue` must be a number the hue value to set the light to
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
for light in self.lights:
if name is None or light.name.lower() == name.lower() and light.on:
light.hue = hue
@_hue.command(pass_context=True, name="saturation", aliases=["sat"])
async def saturation_set(self, ctx, saturation:int=254, *, name=None):
"""
Sets the saturation for lights
`saturation` must be a number the saturation value to set the light to
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
saturation = await self.max_min_check(saturation, 254, 0)
for light in self.lights:
if name is None or light.name.lower() == name.lower() and light.on:
light.saturation = saturation
@_hue.command(pass_context=True, name="random")
async def hue_random_colour(self, ctx, *, name=None):
"""
Sets the light to a random colour
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
colours = [random.random(), random.random()]
for light in self.lights:
if name is None or light.name.lower() == name.lower() and light.on:
light.xy = colours
@_hue.command(pass_context=True, name="colourloop", aliases=["cl"])
async def hue_colourloop(self, ctx, *, name=None):
"""
Toggles the light on colour looping all colours
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
for light in self.lights:
if name is None or light.name.lower() == name.lower():
if light.effect != "colorloop" and light.on:
light.effect = "colorloop"
continue
if light.effect == "colorloop" and light.on:
light.effect = "none"
continue
@_hue.group(pass_context=True, name="colour")
async def _colour(self, ctx):
"""Sets the colour for lights"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
pass
async def rgb_to_xy(self, red:float, green:float, blue:float):
X = 0.4124*red + 0.3576*green + 0.1805*blue
Y = 0.2126*red + 0.7152*green + 0.0722*blue
Z = 0.0193*red + 0.1192*green + 0.9505*blue
try:
x = X / (X + Y + Z)
y = Y / (X + Y + Z)
except ZeroDivisionError:
x = 1.0
y = 1.0
return x, y
@_colour.command(pass_context=True, name="rgb")
async def hue_colour_rgb(self, ctx, red:float, green:float, blue:float, *, name=None):
"""
Sets the colour using RGB colour coordinates
`red` must be a number the red value to set
`green` must be a number the green value to set
`blue` must be a number the blue value to set
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
x, y = await self.rgb_to_xy(red, green, blue)
for light in self.lights:
if name is None or light.name.lower() == name.lower() and light.on:
light.xy = [x, y]
@_colour.command(pass_context=True, name="xy", aliases=["xyz"])
async def hue_colour_xy(self, ctx, x:float, y:float, *, name=None):
"""
Sets the colour using xyz colour values
`x` must be a number the x value to set
`y` must be a number the y value to set
`name` the name of the light to adjust
Note: The z value is determined from two other values
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
if x > 1.0 or x < 0.0:
x = 1.0
if y > 1.0 or y < 0.0:
y = 1.0
for light in self.lights:
if name is None or light.name.lower() == name.lower() and light.on:
light.xy = [x, y]
@_colour.command(pass_context=True, name="hex")
async def hue_colour_hex(self, ctx, hex, *, name=None):
"""
Attempt to set the colour based on hex values
Not 100% accurate
`hex` the hex code colour to try to change to
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
if "#" in hex:
hex.replace("#", "")
r, g, b = tuple(int(hex[i:i+2], 16) for i in (0, 2 ,4))
x, y = await self.rgb_to_xy(r, g, b)
for light in self.lights:
if name is None or light.name.lower() == name.lower() and light.on:
light.xy = [x, y]
@_hue.command(pass_context=True, name="test")
async def hue_test(self, ctx, cl1:float, cl2:float):
"""Testing function"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
for light in self.lights:
light.xy = [cl1, cl2]
@_hue.command(pass_context=True, name="switch")
async def hue_switch(self, ctx, *, name=None):
"""
Toggles lights on or off
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
for light in self.lights:
if name is None or light.name.lower() == name.lower():
if light.on:
light.on = False
continue
if not light.on:
light.on = True
continue
@_hue.command(pass_context=True, name="off")
async def turn_off(self, ctx, *, name=None):
"""
Turns off light
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
for light in self.lights:
if name is None or light.name.lower() == name.lower():
light.on = False
@_hue.command(pass_context=True, name="on")
async def turn_on(self, ctx, name=None):
"""
Turns on Light
`name` the name of the light to adjust
"""
if not await self.get_bridge():
await ctx.send("No IP has been set.")
return
for light in self.lights:
if name is None or light.name.lower() == name.lower():
light.on = True
+22
View File
@@ -0,0 +1,22 @@
{
"author":[
"TrustyJAID"
],
"description":"Lets you control your philips hue lights with redbot.",
"install_msg":"Type `[p]hue` to see available commands.",
"min_python_version":[
3,
6,
2
],
"name":"Hue",
"permissions":[],
"requirements":[
"phue"
],
"short":"Control your philips hue lights with redbot!",
"tags":[
"general",
"utility"
]
}
+7
View File
@@ -0,0 +1,7 @@
from .imagemaker import ImageMaker
from redbot.core import data_manager
def setup(bot):
cog = ImageMaker(bot)
data_manager.load_bundled_data(cog, __file__)
bot.add_cog(cog)
Binary file not shown.

After

Width:  |  Height:  |  Size: 260 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Loaded 100 of 254 files, more files were not shown because too many files have changed in this diff. Show more