mirror of
https://github.com/RustyRaptor/Trusty-cogs.git
synced 2026-12-03 15:55:21 -07:00
Some logging enhancements (#317)
* make use of trace and verbose logging and cleanup some of the logging statements and make use of lazy logging instead of formatting/fstrings and translated logs * make use of trace and verbose logging and cleanup some of the logging statements and make use of lazy logging instead of formatting/fstrings and translated logs * change a few configuration logs to verbose to reduce the frequency they show up at a debug level as they are very spammy and not actionable by the user * Apply suggestions from code review Co-authored-by: TrustyJAID <TrustyJAID@gmail.com> --------- Co-authored-by: TrustyJAID <TrustyJAID@gmail.com>
This commit is contained in:
1 parent
10418da9d6
commit
5aa5675e33
100 files changed
+591
-721
No files matched your search
+13
-22
@@ -11,6 +11,7 @@ from typing import List, Mapping, Optional
|
||||
import click
|
||||
import tabulate
|
||||
from babel.lists import format_list as babel_list
|
||||
from red_commons.logging import getLogger
|
||||
|
||||
DEFAULT_INFO = {
|
||||
"author": [],
|
||||
@@ -25,7 +26,7 @@ DEFAULT_INFO = {
|
||||
}
|
||||
|
||||
logging.basicConfig(filename="scripts.log", level=logging.INFO)
|
||||
log = logging.getLogger(__file__)
|
||||
log = getLogger(__file__)
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
formatter = logging.Formatter(
|
||||
"[{asctime}] [{levelname}] {name}: {message}",
|
||||
@@ -216,9 +217,7 @@ def edit(key, value):
|
||||
|
||||
@cli.command()
|
||||
@click.option("--author", default=DEFAULT_AUTHOR, help="Author of the cog", prompt=True)
|
||||
@click.option(
|
||||
"--name", prompt="Enter the name of the cog", help="Name of the cog being added"
|
||||
)
|
||||
@click.option("--name", prompt="Enter the name of the cog", help="Name of the cog being added")
|
||||
@click.option(
|
||||
"--description",
|
||||
prompt="Enter a longer description for the cog.",
|
||||
@@ -261,21 +260,15 @@ def edit(key, value):
|
||||
prompt=True,
|
||||
type=bool,
|
||||
)
|
||||
@click.option(
|
||||
"--required-cogs", default={}, help="Required cogs for this cog to function."
|
||||
)
|
||||
@click.option(
|
||||
"--requirements", prompt=True, default=[], help="Requirements for the cog."
|
||||
)
|
||||
@click.option("--required-cogs", default={}, help="Required cogs for this cog to function.")
|
||||
@click.option("--requirements", prompt=True, default=[], help="Requirements for the cog.")
|
||||
@click.option(
|
||||
"--tags",
|
||||
default=[],
|
||||
prompt=True,
|
||||
help="Any tags to help people find the cog better.",
|
||||
)
|
||||
@click.option(
|
||||
"--permissions", prompt=True, default=[], help="Any permissions the cog requires."
|
||||
)
|
||||
@click.option("--permissions", prompt=True, default=[], help="Any permissions the cog requires.")
|
||||
@click.option(
|
||||
"--min-python-version",
|
||||
default=[3, 8, 0],
|
||||
@@ -336,7 +329,7 @@ def make(
|
||||
min_python_version,
|
||||
end_user_data_statement,
|
||||
)
|
||||
log.debug(data_obj)
|
||||
log.verbose("make data_obj: %s", data_obj)
|
||||
save_json(f"{ROOT}/{name}/info.json", data_obj.__dict__)
|
||||
|
||||
|
||||
@@ -347,21 +340,21 @@ def countlines(include_hidden: bool = False, include_disabled: bool = False):
|
||||
"""Count the number of lines of .py files in all folders"""
|
||||
total = 0
|
||||
totals = []
|
||||
log.debug(ROOT)
|
||||
log.verbose("countlines root: %s", ROOT)
|
||||
for folder in os.listdir(ROOT):
|
||||
cog_path = ROOT / folder
|
||||
cog = 0
|
||||
if folder.startswith("."):
|
||||
continue
|
||||
if not cog_path.is_dir():
|
||||
log.debug(f"{cog_path} is not a directory")
|
||||
log.debug("%s is not a directory", cog_path)
|
||||
continue
|
||||
try:
|
||||
with open(cog_path / "info.json", "r") as infile:
|
||||
info = InfoJson.from_json(json.load(infile))
|
||||
except Exception:
|
||||
info = InfoJson(DEFAULT_AUTHOR, hidden=True, disabled=True)
|
||||
log.debug(f"Error opening {cog_path} info.json")
|
||||
log.debug("Error opening %s info.json", cog_path)
|
||||
if info.hidden and not include_hidden:
|
||||
continue
|
||||
if info.disabled and not include_disabled:
|
||||
@@ -376,7 +369,7 @@ def countlines(include_hidden: bool = False, include_disabled: bool = False):
|
||||
try:
|
||||
with open(file_path, "r") as infile:
|
||||
lines = len(infile.readlines())
|
||||
log.debug(f"{file_path} has {lines} lines of code")
|
||||
log.verbose("%s has %s lines of code", file_path, lines)
|
||||
cog += lines
|
||||
total += lines
|
||||
except Exception:
|
||||
@@ -397,7 +390,7 @@ def countchars(include_hidden: bool = False, include_disabled: bool = False):
|
||||
"""Count the number of lines of .py files in all folders"""
|
||||
total = 0
|
||||
totals = []
|
||||
log.info(f"{ROOT}")
|
||||
log.info("countchars %s", ROOT)
|
||||
for folder in os.listdir(f"{ROOT}/"):
|
||||
cog = 0
|
||||
if folder.startswith("."):
|
||||
@@ -456,9 +449,7 @@ def makereadme():
|
||||
_version = maybe_version.group(1)
|
||||
if info and not (info.disabled or info.hidden):
|
||||
to_append = [info.name, _version]
|
||||
description = (
|
||||
f"<details><summary>{info.short}</summary>{info.description}</details>"
|
||||
)
|
||||
description = f"<details><summary>{info.short}</summary>{info.description}</details>"
|
||||
to_append.append(description)
|
||||
to_append.append(babel_list(info.author, style="standard", locale="en"))
|
||||
table_data.append(to_append)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import string
|
||||
@@ -7,6 +6,7 @@ from pathlib import Path
|
||||
from typing import Literal, Optional, cast
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot import VersionInfo, version_info
|
||||
from redbot.core import Config, VersionInfo, checks, commands, version_info
|
||||
from redbot.core.data_manager import cog_data_path
|
||||
@@ -14,7 +14,7 @@ from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils.menus import DEFAULT_CONTROLS, menu
|
||||
|
||||
_ = Translator("AddImage", __file__)
|
||||
log = logging.getLogger("red.Trusty-cogs.addimage")
|
||||
log = getLogger("red.Trusty-cogs.addimage")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
@@ -60,7 +60,8 @@ class AddImage(commands.Cog):
|
||||
os.remove(cog_data_path(self) / str(guild_id) / image["file_loc"])
|
||||
except Exception:
|
||||
log.error(
|
||||
_("Error deleting image {image}").format(image=image["file_loc"]),
|
||||
"Error deleting image %s",
|
||||
image["file_loc"],
|
||||
exc_info=True,
|
||||
)
|
||||
pass
|
||||
@@ -405,9 +406,7 @@ class AddImage(commands.Cog):
|
||||
try:
|
||||
os.remove(cog_data_path(self) / str(guild.id) / image["file_loc"])
|
||||
except Exception:
|
||||
log.error(
|
||||
_("Error deleting image {image}").format(image=image["file_loc"]), exc_info=True
|
||||
)
|
||||
log.error("Error deleting image %s", image["file_loc"], exc_info=True)
|
||||
pass
|
||||
await self.config.guild(guild).images.set(all_imgs)
|
||||
await ctx.send(name + _(" has been deleted from this guild!"))
|
||||
@@ -433,9 +432,7 @@ class AddImage(commands.Cog):
|
||||
try:
|
||||
os.remove(cog_data_path(self) / "global" / image["file_loc"])
|
||||
except Exception:
|
||||
log.error(
|
||||
_("Error deleting image {image}").format(image=image["file_loc"]), exc_info=True
|
||||
)
|
||||
log.error("Error deleting image %s", image["file_loc"], exc_info=True)
|
||||
pass
|
||||
await self.config.images.set(all_imgs)
|
||||
await ctx.send(name + _(" has been deleted globally!"))
|
||||
|
||||
+3
-3
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
import functools
|
||||
import logging
|
||||
import sys
|
||||
from io import BytesIO
|
||||
from typing import Optional, Union, cast
|
||||
@@ -8,6 +7,7 @@ from typing import Optional, Union, cast
|
||||
import aiohttp
|
||||
import discord
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageSequence
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.data_manager import bundled_data_path
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
@@ -17,7 +17,7 @@ from .barcode import ImageWriter, generate
|
||||
from .templates import blank_template
|
||||
|
||||
_ = Translator("Badges", __file__)
|
||||
log = logging.getLogger("red.Trusty-cogs.badges")
|
||||
log = getLogger("red.Trusty-cogs.badges")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
@@ -112,7 +112,7 @@ class Badges(commands.Cog):
|
||||
if str(status) == "dnd":
|
||||
status = _("MIA")
|
||||
barcode = BytesIO()
|
||||
log.debug(type(barcode))
|
||||
log.trace("Badges make_template barcode: %s", type(barcode))
|
||||
generate("code39", str(user.id), writer=ImageWriter(self), output=barcode)
|
||||
barcode = Image.open(barcode)
|
||||
barcode = self.remove_white_barcode(barcode)
|
||||
|
||||
+2
-3
@@ -6,11 +6,11 @@ Which is itself a port of python-barcode which is no longer available
|
||||
"""
|
||||
|
||||
import gzip
|
||||
import logging
|
||||
import os
|
||||
import string
|
||||
import xml.dom
|
||||
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.data_manager import bundled_data_path
|
||||
|
||||
try:
|
||||
@@ -31,7 +31,7 @@ try:
|
||||
except NameError:
|
||||
_strbase = str
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.badges")
|
||||
log = getLogger("red.Trusty-cogs.badges")
|
||||
|
||||
|
||||
def mm2px(mm, dpi=300):
|
||||
@@ -424,7 +424,6 @@ else:
|
||||
|
||||
|
||||
class Barcode(object):
|
||||
|
||||
name = ""
|
||||
|
||||
raw = None
|
||||
|
||||
+4
-5
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
import functools
|
||||
import logging
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
@@ -11,12 +10,13 @@ from typing import List, Optional, Pattern, Tuple
|
||||
import aiohttp
|
||||
import discord
|
||||
from PIL import Image, ImageColor, ImageDraw, ImageFont
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.data_manager import bundled_data_path, cog_data_path
|
||||
|
||||
from .converter import Stamp
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.bingo")
|
||||
log = getLogger("red.trusty-cogs.bingo")
|
||||
|
||||
IMAGE_LINKS: Pattern = re.compile(
|
||||
r"(https?:\/\/[^\"\'\s]*\.(?:png|jpg|jpeg)(\?size=[0-9]*)?)", flags=re.I
|
||||
@@ -24,7 +24,6 @@ IMAGE_LINKS: Pattern = re.compile(
|
||||
|
||||
|
||||
class Bingo(commands.Cog):
|
||||
|
||||
__version__ = "1.2.0"
|
||||
__author__ = ["TrustyJAID"]
|
||||
|
||||
@@ -481,7 +480,7 @@ class Bingo(commands.Cog):
|
||||
font=font,
|
||||
)
|
||||
letter_count += 1
|
||||
log.info(name)
|
||||
log.trace("_create_bingo_card name: %s", name)
|
||||
draw.text(
|
||||
(350, 200),
|
||||
name,
|
||||
@@ -509,7 +508,7 @@ class Bingo(commands.Cog):
|
||||
count += 1
|
||||
draw.rectangle((x0, y0, x1, y1), outline=box_colour)
|
||||
if [x, y] in stamps or [x, y] == [2, 2]:
|
||||
log.info(f"Filling square {x} {y}")
|
||||
log.info("Filling square %s %s", x, y)
|
||||
colour = list(ImageColor.getrgb(stamp_colour))
|
||||
colour.append(128)
|
||||
nb = base.copy()
|
||||
|
||||
+3
-3
@@ -1,18 +1,18 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.data_manager import cog_data_path
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
|
||||
from .game import CAHGame, CardSet
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.cah")
|
||||
log = getLogger("red.trusty-cogs.cah")
|
||||
|
||||
WHITE_CARD_URL = "https://i.imgur.com/mlkVIxg.png"
|
||||
BLACK_CARD_URL = "https://i.imgur.com/OrM8UcC.png"
|
||||
@@ -31,7 +31,7 @@ class CardSetTransformer(discord.app_commands.Transformer):
|
||||
white_cards = []
|
||||
black_cards = []
|
||||
official = False
|
||||
log.info(f"{argument} card set searching")
|
||||
log.info("%s card set searching", argument)
|
||||
if argument.lower() == "official":
|
||||
official = True
|
||||
for cardset in card_sets.values():
|
||||
|
||||
+2
-2
@@ -2,7 +2,6 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import functools
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import textwrap
|
||||
@@ -14,11 +13,12 @@ from typing import Dict, List, NamedTuple, Optional, Tuple, Union
|
||||
|
||||
import discord
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.data_manager import cog_data_path
|
||||
from redbot.core.utils.chat_formatting import escape, humanize_list, pagify
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.cah")
|
||||
log = getLogger("red.trusty-cogs.cah")
|
||||
|
||||
|
||||
class CAHException(Exception):
|
||||
|
||||
+3
-3
@@ -1,4 +1,3 @@
|
||||
import logging
|
||||
import re
|
||||
from typing import Optional, Tuple, Union
|
||||
|
||||
@@ -6,6 +5,7 @@ import aiohttp
|
||||
import discord
|
||||
from discord.ext.commands.converter import Converter, IDConverter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot import VersionInfo, version_info
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
@@ -21,7 +21,7 @@ except ImportError:
|
||||
API_URL = "https://www.cleverbot.com/getreply"
|
||||
IO_API_URL = "https://cleverbot.io/1.0"
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Cleverbot")
|
||||
log = getLogger("red.trusty-cogs.Cleverbot")
|
||||
|
||||
_ = Translator("cleverbot", __file__)
|
||||
|
||||
@@ -288,7 +288,7 @@ class CleverbotAPI:
|
||||
is_reply = reference.author.id == self.bot.user.id and ctx.me in message.mentions
|
||||
if is_mention:
|
||||
text = text[len(ctx.me.display_name) + 2 :]
|
||||
log.debug(text)
|
||||
log.trace("CleverbotAPI text: %s", text)
|
||||
if not text:
|
||||
log.debug("No text to send to cleverbot.")
|
||||
return
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, checks, commands
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils.chat_formatting import humanize_list, pagify
|
||||
|
||||
from .api import ChannelUserRole, CleverbotAPI, IntRange
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Cleverbot")
|
||||
log = getLogger("red.trusty-cogs.Cleverbot")
|
||||
|
||||
_ = Translator("cleverbot", __file__)
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import datetime
|
||||
import logging
|
||||
from typing import Dict, List, Optional, Union
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.bot import Red
|
||||
|
||||
from .coin import Coin, CoinBase
|
||||
from .errors import CoinMarketCapError
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.Conversions")
|
||||
log = getLogger("red.Trusty-cogs.Conversions")
|
||||
|
||||
|
||||
class Conversions(commands.Cog):
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
import functools
|
||||
import logging
|
||||
import os
|
||||
|
||||
import aiohttp
|
||||
@@ -8,6 +7,7 @@ import discord
|
||||
import moviepy
|
||||
import yt_dlp as youtube_dl
|
||||
from moviepy.editor import CompositeVideoClip, TextClip, VideoFileClip
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import checks, commands
|
||||
from redbot.core.data_manager import cog_data_path
|
||||
|
||||
@@ -19,7 +19,7 @@ CRAB_LINK = "https://youtu.be/gDLE3LikgUs"
|
||||
MIKU_LINK = "https://youtu.be/qeJjQGF6gz4"
|
||||
|
||||
FONT_FILE = "https://github.com/matomo-org/travis-scripts/raw/master/fonts/Verdana.ttf"
|
||||
log = logging.getLogger("red.trusty-cogs.crabrave")
|
||||
log = getLogger("red.trusty-cogs.crabrave")
|
||||
|
||||
|
||||
class CrabRave(commands.Cog):
|
||||
|
||||
+7
-7
@@ -1,7 +1,6 @@
|
||||
import asyncio
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from base64 import b64encode
|
||||
from datetime import datetime
|
||||
@@ -10,6 +9,7 @@ from typing import Dict, List, Optional, Tuple, Union
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.data_manager import cog_data_path
|
||||
@@ -92,7 +92,7 @@ COMPONENTS = DestinyComponents(
|
||||
|
||||
|
||||
_ = Translator("Destiny", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.Destiny")
|
||||
log = getLogger("red.trusty-cogs.Destiny")
|
||||
|
||||
|
||||
class MyTyping(discord.ext.commands.context.DeferTyping):
|
||||
@@ -131,10 +131,10 @@ class DestinyAPI:
|
||||
return data["Response"]
|
||||
else:
|
||||
if "message" in data:
|
||||
log.error(data["message"])
|
||||
log.error("DestinyAPI request_url error message: %s", data["message"])
|
||||
else:
|
||||
log.error("Incorrect response data")
|
||||
log.debug(url)
|
||||
log.verbose("request_url: %s", url)
|
||||
raise Destiny2InvalidParameters(data)
|
||||
elif resp.status >= 500:
|
||||
raise ServersUnavailable
|
||||
@@ -168,7 +168,7 @@ class DestinyAPI:
|
||||
return data["Response"]
|
||||
else:
|
||||
if "message" in data:
|
||||
log.error(data["message"])
|
||||
log.error("DestinyAPI post_url error message: %s", data["message"])
|
||||
else:
|
||||
log.error("Incorrect response data")
|
||||
raise Destiny2InvalidParameters(data["Message"])
|
||||
@@ -584,7 +584,7 @@ class DestinyAPI:
|
||||
try:
|
||||
data = await self.get_entities(entity, d1)
|
||||
except Exception:
|
||||
log.info(_("No manifest found, getting response from API."))
|
||||
log.info("No manifest found, getting response from API.")
|
||||
return await self.get_definition_from_api(entity.replace("Lite", ""), entity_hash)
|
||||
for item in entity_hash:
|
||||
try:
|
||||
@@ -1075,7 +1075,7 @@ class DestinyAPI:
|
||||
message = await ctx.channel.send(msg)
|
||||
|
||||
emojis = ReactionPredicate.NUMBER_EMOJIS[1 : -(len(profile["destinyMemberships"]) + 1)]
|
||||
log.debug(emojis)
|
||||
log.verbose("pick_account emojis: %s", emojis)
|
||||
start_adding_reactions(message, emojis)
|
||||
pred = ReactionPredicate.with_emojis(emojis=emojis, message=message, user=author)
|
||||
try:
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from enum import Enum, EnumMeta
|
||||
@@ -9,13 +8,14 @@ from typing import List, Optional, Union
|
||||
import discord
|
||||
from discord.ext.commands.converter import Converter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
|
||||
_ = Translator("Destiny", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Destiny")
|
||||
log = getLogger("red.trusty-cogs.Destiny")
|
||||
|
||||
STRING_VAR_RE = re.compile(r"{var:(?P<hash>\d+)}")
|
||||
|
||||
@@ -580,7 +580,6 @@ class SearchInfo(Converter):
|
||||
"""
|
||||
|
||||
async def convert(self, ctx: commands.Context, argument: str) -> Optional[bool]:
|
||||
|
||||
possible_results = {
|
||||
"lore": {"code": False, "alt": ["lore"]},
|
||||
"details": {
|
||||
|
||||
+13
-22
@@ -1,6 +1,5 @@
|
||||
import csv
|
||||
import datetime
|
||||
import logging
|
||||
import random
|
||||
import re
|
||||
from io import BytesIO, StringIO
|
||||
@@ -10,6 +9,7 @@ import aiohttp
|
||||
import discord
|
||||
from discord import app_commands
|
||||
from discord.ext import tasks
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils.chat_formatting import (
|
||||
@@ -54,7 +54,7 @@ IMAGE_URL = "https://www.bungie.net"
|
||||
AUTH_URL = "https://www.bungie.net/en/oauth/authorize"
|
||||
TOKEN_URL = "https://www.bungie.net/platform/app/oauth/token/"
|
||||
_ = Translator("Destiny", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.Destiny")
|
||||
log = getLogger("red.trusty-cogs.Destiny")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
@@ -121,7 +121,7 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
if payload["provider"] != "destiny":
|
||||
return
|
||||
if "code" not in payload:
|
||||
log.error(f"Received Destiny OAuth without a code parameter {user_id} - {payload}")
|
||||
log.error("Received Destiny OAuth without a code parameter %s - %s", user_id, payload)
|
||||
return
|
||||
self.dashboard_authed[int(user_id)] = payload
|
||||
|
||||
@@ -237,7 +237,7 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
await ctx.send(_("`{search}` could not be found.").format(search=search))
|
||||
return
|
||||
embeds = []
|
||||
# log.debug(items[0])
|
||||
log.trace("Item: %s", items[0])
|
||||
for item_hash, item in items.items():
|
||||
embed = discord.Embed()
|
||||
|
||||
@@ -260,7 +260,6 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
+ "\n\n"
|
||||
)
|
||||
if item["itemType"] in [3] and not show_lore:
|
||||
|
||||
stats_str = ""
|
||||
rpm = ""
|
||||
recoil = ""
|
||||
@@ -539,7 +538,6 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
await ctx.send(msg)
|
||||
return
|
||||
async with MyTyping(ctx, ephemeral=False):
|
||||
|
||||
clan = await self.get_clan_members(ctx.author, clan_id)
|
||||
headers = [
|
||||
"Discord Name",
|
||||
@@ -1040,7 +1038,7 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
name = data["displayProperties"]["name"]
|
||||
if current.lower() in name.lower():
|
||||
choices.append(app_commands.Choice(name=name, value=name))
|
||||
log.debug(len(choices))
|
||||
log.trace("parse_search_lore choices: %s", len(choices))
|
||||
return choices[:25]
|
||||
|
||||
@destiny.command(aliases=["whereisxûr"])
|
||||
@@ -1416,7 +1414,6 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
|
||||
@vendor_search.autocomplete("vendor")
|
||||
async def find_vendor(self, interaction: discord.Interaction, current: str):
|
||||
|
||||
possible_options = await self.search_definition("DestinyVendorDefinition", current)
|
||||
choices = []
|
||||
for key, choice in possible_options.items():
|
||||
@@ -1880,7 +1877,7 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
if not any(i in v.get("parentNodeHashes", []) for i in weapon_slots):
|
||||
continue
|
||||
presentation_node_hashes.add(int(k))
|
||||
log.debug(f"Presentation Node {presentation_node_hashes}")
|
||||
log.trace("Presentation Node %s", presentation_node_hashes)
|
||||
msg = ""
|
||||
for r_hash, i in weapon_info.items():
|
||||
if not any(h in i.get("parentNodeHashes", []) for h in presentation_node_hashes):
|
||||
@@ -2214,7 +2211,6 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
continue
|
||||
name = data["displayProperties"]["name"]
|
||||
if data["equippable"] and data["itemType"] == 3:
|
||||
|
||||
desc = data["displayProperties"]["description"]
|
||||
item_type = data["itemTypeAndTierDisplayName"]
|
||||
try:
|
||||
@@ -2361,9 +2357,9 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
data = await self.get_activity_history(user, char_id, activity)
|
||||
except Exception:
|
||||
log.error(
|
||||
_(
|
||||
"Something went wrong I couldn't get info on character {char_id} for activity {activity}"
|
||||
).format(char_id=char_id, activity=activity)
|
||||
"Something went wrong I couldn't get info on character %s for activity %s",
|
||||
char_id,
|
||||
activity,
|
||||
)
|
||||
continue
|
||||
if not data:
|
||||
@@ -2449,7 +2445,6 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
async def build_character_stats(
|
||||
self, user: discord.Member, chars: dict, stat_type: str
|
||||
) -> List[discord.Embed]:
|
||||
|
||||
embeds: List[discord.Embed] = []
|
||||
for char_id, char in chars["characters"]["data"].items():
|
||||
# log.debug(char)
|
||||
@@ -2462,11 +2457,7 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
agg_hashes = [a["activityHash"] for a in aggregate["activities"]]
|
||||
acts = await self.get_definition("DestinyActivityDefinition", agg_hashes)
|
||||
except Exception:
|
||||
log.error(
|
||||
_("Something went wrong I couldn't get info on character {char_id}").format(
|
||||
char_id=char_id
|
||||
)
|
||||
)
|
||||
log.error("Something went wrong I couldn't get info on character %s", char_id)
|
||||
continue
|
||||
if not data:
|
||||
continue
|
||||
@@ -2482,7 +2473,9 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
embeds.append(embed)
|
||||
except Exception:
|
||||
log.error(
|
||||
f"User {user.id} had an issue generating stats for character {char_id}",
|
||||
"User %s had an issue generating stats for character %s",
|
||||
user.id,
|
||||
char_id,
|
||||
exc_info=True,
|
||||
)
|
||||
continue
|
||||
@@ -2547,7 +2540,6 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
if "emblemPath" in char:
|
||||
embed.set_thumbnail(url=IMAGE_URL + char["emblemPath"])
|
||||
for stat, values in data[stat_type]["allTime"].items():
|
||||
|
||||
if values["basic"]["value"] < 0 or stat not in ATTRS:
|
||||
continue
|
||||
embed.add_field(name=ATTRS[stat], value=str(values["basic"]["displayValue"]))
|
||||
@@ -2652,7 +2644,6 @@ class Destiny(DestinyAPI, commands.Cog):
|
||||
if "emblemPath" in char:
|
||||
embed.set_thumbnail(url=IMAGE_URL + char["emblemPath"])
|
||||
for stat, values in data.items():
|
||||
|
||||
if values["basic"]["value"] < 0 or stat not in ATTRS:
|
||||
continue
|
||||
embed.add_field(name=ATTRS[stat], value=str(values["basic"]["displayValue"]))
|
||||
|
||||
+3
-3
@@ -1,10 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
|
||||
# from discord.ext.commands.errors import BadArgument
|
||||
from redbot.core.commands import commands
|
||||
@@ -17,7 +17,7 @@ from .errors import Destiny2APIError
|
||||
BASE_URL = "https://bungie.net"
|
||||
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.destiny")
|
||||
log = getLogger("red.Trusty-cogs.destiny")
|
||||
_ = Translator("Destiny", __file__)
|
||||
|
||||
|
||||
@@ -428,7 +428,7 @@ class PostmasterPages(menus.ListPageSource):
|
||||
pass
|
||||
|
||||
async def format_page(self, menu: menus.MenuPages, page: int):
|
||||
log.info(page)
|
||||
log.trace("PostmasterPages %s", page)
|
||||
self.current_char = page
|
||||
self.current_select = PostmasterSelect(self.postmasters[page])
|
||||
msg = ""
|
||||
|
||||
+7
-7
@@ -1,14 +1,14 @@
|
||||
import logging
|
||||
from typing import Any, List, NamedTuple, Optional, Union
|
||||
|
||||
import discord
|
||||
import mendeleev
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.vendored.discord.ext import menus
|
||||
|
||||
from .data import IMAGES, LATTICES, UNITS
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.elements")
|
||||
log = getLogger("red.trusty-cogs.elements")
|
||||
|
||||
|
||||
class ElementConverter(discord.app_commands.Transformer):
|
||||
@@ -61,7 +61,7 @@ class MeasurementConverter(discord.app_commands.Transformer):
|
||||
|
||||
@classmethod
|
||||
async def convert(cls, ctx: commands.Context, argument: str) -> Optional[Measurements]:
|
||||
log.debug("this converter is being hit")
|
||||
log.trace("MeasurementConverter is being hit")
|
||||
result = None
|
||||
if argument.lower() in UNITS:
|
||||
value = argument.lower()
|
||||
@@ -103,25 +103,25 @@ class MeasurementConverter(discord.app_commands.Transformer):
|
||||
def get_xray_wavelength(element: mendeleev.models.Element) -> str:
|
||||
try:
|
||||
ka = 1239.84 / (
|
||||
13.6057 * ((element.atomic_number - 1) ** 2) * ((1 / 1 ** 2) - (1 / 2 ** 2))
|
||||
13.6057 * ((element.atomic_number - 1) ** 2) * ((1 / 1**2) - (1 / 2**2))
|
||||
)
|
||||
except Exception:
|
||||
ka = ""
|
||||
try:
|
||||
kb = 1239.84 / (
|
||||
13.6057 * ((element.atomic_number - 1) ** 2) * ((1 / 1 ** 2) - (1 / 3 ** 2))
|
||||
13.6057 * ((element.atomic_number - 1) ** 2) * ((1 / 1**2) - (1 / 3**2))
|
||||
)
|
||||
except Exception:
|
||||
kb = ""
|
||||
try:
|
||||
la = 1239.84 / (
|
||||
13.6057 * ((element.atomic_number - 7.4) ** 2) * ((1 / 1 ** 2) - (1 / 2 ** 3))
|
||||
13.6057 * ((element.atomic_number - 7.4) ** 2) * ((1 / 1**2) - (1 / 2**3))
|
||||
)
|
||||
except Exception:
|
||||
la = ""
|
||||
try:
|
||||
lb = 1239.84 / (
|
||||
13.6057 * ((element.atomic_number - 7.4) ** 2) * ((1 / 1 ** 2) - (1 / 2 ** 4))
|
||||
13.6057 * ((element.atomic_number - 7.4) ** 2) * ((1 / 1**2) - (1 / 2**4))
|
||||
)
|
||||
except Exception:
|
||||
lb = ""
|
||||
|
||||
+12
-12
@@ -1,4 +1,3 @@
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, List, Optional, Tuple, Union, cast
|
||||
@@ -10,12 +9,13 @@ from dateutil.tz import gettz
|
||||
from discord.ext.commands.converter import Converter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from discord.utils import snowflake_time
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils.chat_formatting import humanize_list, humanize_timedelta, pagify
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.EventPoster")
|
||||
log = getLogger("red.trusty-cogs.EventPoster")
|
||||
|
||||
_ = Translator("EventPoster", __file__)
|
||||
|
||||
@@ -372,7 +372,7 @@ class Event(discord.ui.View):
|
||||
self.add_item(self.maybe_button)
|
||||
self.add_item(self.leave_button)
|
||||
self.select_view = None
|
||||
log.debug(self.select_options)
|
||||
log.trace("Event select_options: %s", self.select_options)
|
||||
if self.select_options:
|
||||
self.select_view = PlayerClassSelect(
|
||||
custom_id=f"playerclass-{self.hoster}",
|
||||
@@ -388,11 +388,11 @@ class Event(discord.ui.View):
|
||||
if self.max_slots and len(self.members) >= self.max_slots:
|
||||
self.join_button.disabled = True
|
||||
self.select_view.disabled = True
|
||||
log.debug(f"Setting Join Button to {self.join_button.disabled}")
|
||||
log.trace("Setting Join Button to %s", self.join_button.disabled)
|
||||
if self.max_slots and len(self.members) < self.max_slots:
|
||||
self.join_button.disabled = False
|
||||
self.select_view.disabled = False
|
||||
log.debug(f"Setting Join Button to {self.join_button.disabled}")
|
||||
log.debug("Setting Join Button to %s", self.join_button.disabled)
|
||||
|
||||
async def interaction_check(self, interaction: discord.Interaction):
|
||||
"""
|
||||
@@ -445,14 +445,14 @@ class Event(discord.ui.View):
|
||||
return True
|
||||
if self.start:
|
||||
future = (self.start + timedelta(seconds=seconds)).timestamp()
|
||||
log.debug(f"{humanize_timedelta(seconds = future-now)}")
|
||||
log.verbose("should_remove self.start %s", humanize_timedelta(seconds=future - now))
|
||||
return now > future
|
||||
else:
|
||||
future = (
|
||||
snowflake_time(self.message).replace(tzinfo=timezone.utc)
|
||||
+ timedelta(seconds=seconds)
|
||||
).timestamp()
|
||||
log.debug(f"{humanize_timedelta(seconds = future-now)}")
|
||||
log.verbose("should_remove else %s", humanize_timedelta(seconds=future - now))
|
||||
return now > future
|
||||
|
||||
def remaining(self, seconds: int) -> str:
|
||||
@@ -467,7 +467,7 @@ class Event(discord.ui.View):
|
||||
if self.start:
|
||||
future = (self.start + timedelta(seconds=seconds)).timestamp()
|
||||
diff = future - now
|
||||
log.debug(f"Set time {future=} {now=} {diff=}")
|
||||
log.debug("Set time self.start future=%s now=%s diff=%s", future, now, diff)
|
||||
return humanize_timedelta(seconds=future - now)
|
||||
else:
|
||||
future = (
|
||||
@@ -475,7 +475,7 @@ class Event(discord.ui.View):
|
||||
+ timedelta(seconds=seconds)
|
||||
).timestamp()
|
||||
diff = future - now
|
||||
log.debug(f"Message Time {future=} {now=} {diff=}")
|
||||
log.debug("Message Time ellse future=%s now=%s diff=%s", future, now, diff)
|
||||
return humanize_timedelta(seconds=future - now)
|
||||
|
||||
async def update_event(self):
|
||||
@@ -638,7 +638,7 @@ class Event(discord.ui.View):
|
||||
config = self.get_config()
|
||||
thumbnails = await config.guild(ctx.guild).custom_links()
|
||||
for name, link in thumbnails.items():
|
||||
if re.search(fr"(?i)\b{name}\b", self.event):
|
||||
if re.search(rf"(?i)\b{name}\b", self.event):
|
||||
return link
|
||||
return None
|
||||
|
||||
@@ -648,7 +648,7 @@ class Event(discord.ui.View):
|
||||
config = self.get_config()
|
||||
large_links = await config.guild(ctx.guild).large_links()
|
||||
for name, link in large_links.items():
|
||||
if re.search(fr"(?i)\b{name}\b", self.event):
|
||||
if re.search(rf"(?i)\b{name}\b", self.event):
|
||||
return link
|
||||
return None
|
||||
|
||||
@@ -658,7 +658,7 @@ class Event(discord.ui.View):
|
||||
new_members = []
|
||||
for m in members:
|
||||
if isinstance(m, tuple) or isinstance(m, list):
|
||||
log.debug(f"Converting to new members list in {data.get('channel')}")
|
||||
log.debug("Converting to new members list in %s", data.get("channel"))
|
||||
new_members.append(m[0])
|
||||
else:
|
||||
new_members.append(m)
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Dict, Literal, Optional, Tuple, Union
|
||||
|
||||
import discord
|
||||
from discord.ext import tasks
|
||||
from pytz import NonExistentTimeError
|
||||
from red_commons.logging import getLogger
|
||||
from redbot import VersionInfo, version_info
|
||||
from redbot.core import Config, checks, commands
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
@@ -13,7 +13,7 @@ from redbot.core.utils.views import SimpleMenu
|
||||
|
||||
from .event_obj import ApproveView, ConfirmView, Event, ValidImage
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.EventPoster")
|
||||
log = getLogger("red.trusty-cogs.EventPoster")
|
||||
|
||||
_ = Translator("EventPoster", __file__)
|
||||
|
||||
@@ -192,7 +192,6 @@ class EventPoster(commands.Cog):
|
||||
return
|
||||
|
||||
async def remove_user_from_event(self, user: discord.Member, event: Event) -> None:
|
||||
|
||||
ctx = await event.get_ctx(self.bot)
|
||||
if not ctx:
|
||||
return
|
||||
@@ -340,7 +339,6 @@ class EventPoster(commands.Cog):
|
||||
members.insert(0, ctx.author)
|
||||
member_list = [m.id for m in members if m is not None]
|
||||
if not max_slots:
|
||||
|
||||
max_slots = await self.config.guild(ctx.guild).default_max()
|
||||
# log.debug(f"using default {max_slots}")
|
||||
select_options = await self.config.guild(ctx.guild).playerclass_options()
|
||||
@@ -792,7 +790,6 @@ class EventPoster(commands.Cog):
|
||||
return False
|
||||
|
||||
async def check_clear_event(self, ctx: commands.Context) -> bool:
|
||||
|
||||
new_view = ConfirmView(ctx)
|
||||
msg = _("You already have an event running, would you like to cancel it?")
|
||||
await ctx.send(msg, view=new_view)
|
||||
@@ -832,7 +829,7 @@ class EventPoster(commands.Cog):
|
||||
default_slots=data["default_max"]
|
||||
)
|
||||
if data["cleanup_seconds"] is not None:
|
||||
log.debug(data["cleanup_seconds"])
|
||||
log.trace("show_event_settings cleanup_seconds: %s", data["cleanup_seconds"])
|
||||
msg += _("__Events End After:__ **{time}**\n").format(
|
||||
time=humanize_timedelta(seconds=data["cleanup_seconds"])
|
||||
)
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import asyncio
|
||||
import datetime
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast
|
||||
|
||||
import discord
|
||||
from discord.ext import tasks
|
||||
from discord.ext.commands.converter import Converter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands, i18n, modlog
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.utils.chat_formatting import (
|
||||
@@ -18,7 +18,7 @@ from redbot.core.utils.chat_formatting import (
|
||||
)
|
||||
|
||||
_ = i18n.Translator("ExtendedModLog", __file__)
|
||||
logger = logging.getLogger("red.trusty-cogs.ExtendedModLog")
|
||||
logger = getLogger("red.trusty-cogs.ExtendedModLog")
|
||||
|
||||
|
||||
class CommandPrivs(Converter):
|
||||
@@ -185,7 +185,7 @@ class EventMixin:
|
||||
can_x = _("**See:** {can_see}\n**Run:** {can_run}").format(
|
||||
can_run=can_run, can_see=can_see
|
||||
)
|
||||
logger.debug(f"{ctx.command.qualified_name}")
|
||||
logger.verbose("on_command name: %s", ctx.command.qualified_name)
|
||||
parent = ""
|
||||
if ctx.interaction:
|
||||
parent = ctx.command.app_command.qualified_name
|
||||
@@ -205,7 +205,7 @@ class EventMixin:
|
||||
except Exception:
|
||||
return
|
||||
if privs.name not in self.settings[guild.id]["commands_used"]["privs"]:
|
||||
logger.debug(f"command not in list {privs}")
|
||||
logger.debug("command not in list %s", privs)
|
||||
return
|
||||
|
||||
if privs is commands.PrivilegeLevel.MOD:
|
||||
@@ -343,7 +343,7 @@ class EventMixin:
|
||||
and self.settings[guild.id]["message_delete"]["embed"]
|
||||
)
|
||||
ctx = await self.bot.get_context(message)
|
||||
logger.debug(ctx.valid)
|
||||
logger.trace("_cached_message_delete ctx.valid: %s", ctx.valid)
|
||||
if ctx.valid and self.settings[guild.id]["message_delete"]["ignore_commands"]:
|
||||
logger.debug("Ignoring valid command messages.")
|
||||
return
|
||||
@@ -1739,7 +1739,7 @@ class EventMixin:
|
||||
a = set(after.roles)
|
||||
before_roles = list(b - a)
|
||||
after_roles = list(a - b)
|
||||
logger.debug(after_roles)
|
||||
logger.debug("on_member_update after_roles: %s", after_roles)
|
||||
if before_roles:
|
||||
for role in before_roles:
|
||||
msg += _("{author} had the {role} role removed.").format(
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, checks, commands, modlog
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
@@ -11,7 +11,7 @@ from .eventmixin import CommandPrivs, EventChooser, EventMixin
|
||||
from .settings import inv_settings
|
||||
|
||||
_ = Translator("ExtendedModLog", __file__)
|
||||
logger = logging.getLogger("red.trusty-cogs.ExtendedModLog")
|
||||
logger = getLogger("red.trusty-cogs.ExtendedModLog")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
@@ -57,7 +57,6 @@ class ExtendedModLog(EventMixin, commands.Cog):
|
||||
if entry not in data:
|
||||
all_data[guild_id][entry] = inv_settings[entry]
|
||||
if type(default) == dict:
|
||||
|
||||
for key, _default in inv_settings[entry].items():
|
||||
if not isinstance(all_data[guild_id][entry], dict):
|
||||
all_data[guild_id][entry] = default
|
||||
|
||||
+2
-2
@@ -1,13 +1,13 @@
|
||||
import logging
|
||||
from typing import Dict, Optional, Set
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot import VersionInfo, version_info
|
||||
from redbot.core import Config, checks, commands
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Fenrir")
|
||||
log = getLogger("red.trusty-cogs.Fenrir")
|
||||
|
||||
|
||||
class Fenrir(commands.Cog):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import List, Optional, Pattern
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.i18n import Translator
|
||||
|
||||
from .constants import TEAMS
|
||||
@@ -11,7 +11,7 @@ from .errors import NoSchedule
|
||||
from .helper import DATE_RE
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.hockey")
|
||||
log = getLogger("red.trusty-cogs.hockey")
|
||||
|
||||
__all__ = (
|
||||
"StopButton",
|
||||
@@ -189,7 +189,7 @@ class FilterModal(discord.ui.Modal):
|
||||
pattern = rf"{short}\b|" + r"|".join(rf"\b{i}\b" for i in team.split())
|
||||
if nick:
|
||||
pattern += r"|" + r"|".join(rf"\b{i}\b" for i in nick)
|
||||
# log.debug(pattern)
|
||||
log.trace("FilterModal pattern: %s", pattern)
|
||||
reg: Pattern = re.compile(rf"\b{pattern}", flags=re.I)
|
||||
for pot in potential_teams:
|
||||
find = reg.findall(pot)
|
||||
@@ -232,12 +232,12 @@ class TeamModal(discord.ui.Modal):
|
||||
if "Team" in team:
|
||||
continue
|
||||
pattern = rf"{team}|{data['tri_code']}|{'|'.join(n for n in data['nickname'])}"
|
||||
# log.debug(pattern)
|
||||
log.trace("TeamModal pattern: %s", pattern)
|
||||
reg: Pattern = re.compile(pattern, flags=re.I)
|
||||
find = reg.search(self.team.value)
|
||||
if find:
|
||||
teams.append(team)
|
||||
log.debug(teams)
|
||||
log.trace("TeamModal teams: %s", teams)
|
||||
if not teams:
|
||||
await interaction.response.send_message(
|
||||
_("`{content}` is not a valid team.").format(content=self.view.value[:200]),
|
||||
@@ -250,7 +250,7 @@ class TeamModal(discord.ui.Modal):
|
||||
for page in self.view.pages:
|
||||
if teams[0].lower() in page.author.name.lower():
|
||||
page_num = self.view.pages.index(page)
|
||||
log.debug(f"Setting page number {page_num} {teams[0]}")
|
||||
log.trace("Setting page number %s %s", page_num, teams[0])
|
||||
await self.view.show_page(page_num, interaction=interaction)
|
||||
|
||||
|
||||
|
||||
+9
-9
@@ -1,9 +1,9 @@
|
||||
import json
|
||||
import logging
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils import AsyncIter
|
||||
@@ -28,7 +28,7 @@ except ImportError:
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.hockey")
|
||||
log = getLogger("red.trusty-cogs.hockey")
|
||||
|
||||
|
||||
class HockeyDev(MixinMeta):
|
||||
@@ -100,7 +100,7 @@ class HockeyDev(MixinMeta):
|
||||
# log.debug(link)
|
||||
with open("/mnt/e/github/Trusty-cogs/hockey/testgame.json", "r") as infile:
|
||||
data = json.loads(infile.read())
|
||||
# log.debug(data)
|
||||
log.verbose("getgoals testgame.json data: %s", data)
|
||||
game = await Game.from_json(data)
|
||||
await game.check_game_state(self.bot)
|
||||
if (game.home_score + game.away_score) != 0:
|
||||
@@ -220,7 +220,7 @@ class HockeyDev(MixinMeta):
|
||||
# log.debug(link)
|
||||
with open("/mnt/e/github/Trusty-cogs/hockey/testgame.json", "r") as infile:
|
||||
data = json.loads(infile.read())
|
||||
# log.debug(data)
|
||||
log.verbose("make_fake_pickems - testgame.json: %s", data)
|
||||
game = await Game.from_json(data)
|
||||
fake_pickem = await self.get_pickem_object(ctx.guild, game)
|
||||
msg = await self.make_pickems_msg(ctx.guild, game)
|
||||
@@ -235,7 +235,7 @@ class HockeyDev(MixinMeta):
|
||||
"""
|
||||
with open("/mnt/e/github/Trusty-cogs/hockey/testgame.json", "r") as infile:
|
||||
data = json.loads(infile.read())
|
||||
# log.debug(data)
|
||||
log.verbose("disable_fake_pickems - testgame.json: %s", data)
|
||||
game = await Game.from_json(data)
|
||||
await self.disable_pickems_buttons(game)
|
||||
|
||||
@@ -246,7 +246,7 @@ class HockeyDev(MixinMeta):
|
||||
"""
|
||||
with open("/mnt/e/github/Trusty-cogs/hockey/testgame.json", "r") as infile:
|
||||
data = json.loads(infile.read())
|
||||
# log.debug(data)
|
||||
log.verbose("finalize_fake_pickems - testgame.json: %s", data)
|
||||
game = await Game.from_json(data)
|
||||
await self.set_guild_pickem_winner(game)
|
||||
|
||||
@@ -519,7 +519,7 @@ class HockeyDev(MixinMeta):
|
||||
channel = guild.get_channel(channel_id)
|
||||
if channel is None:
|
||||
await self.config.channel_from_id(channel_id).clear()
|
||||
log.info(f"Removed the following channels {channel_id}")
|
||||
log.info("Removed the following channels %s", channel_id)
|
||||
continue
|
||||
else:
|
||||
good_channels.append(channel.id)
|
||||
@@ -542,13 +542,13 @@ class HockeyDev(MixinMeta):
|
||||
if not guild:
|
||||
await self.config.channel_from_id(channel_id).clear()
|
||||
await self.config.guild_from_id(int(data["guild_id"])).clear()
|
||||
log.info(f"Removed the following channels {channel_id}")
|
||||
log.info("Removed the following channels %s", channel_id)
|
||||
continue
|
||||
channel = guild.get_channel
|
||||
|
||||
if channel is None:
|
||||
await self.config.channel_from_id(channel_id).clear()
|
||||
log.info(f"Removed the following channels {channel_id}")
|
||||
log.info("Removed the following channels %s", channel_id)
|
||||
continue
|
||||
# if await self.config.channel(channel).to_delete():
|
||||
# await self.config._clear_scope(Config.CHANNEL, str(channels))
|
||||
|
||||
+3
-5
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
@@ -9,6 +8,7 @@ from typing import Dict, List, Literal, Optional, Tuple, Union
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils import AsyncIter
|
||||
@@ -27,7 +27,7 @@ from .standings import LeagueRecord, Playoffs, Standings
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
|
||||
class GameType(Enum):
|
||||
@@ -334,7 +334,7 @@ class Game:
|
||||
else:
|
||||
async with session.get(BASE_URL + games["link"]) as resp:
|
||||
data = await resp.json()
|
||||
# log.debug(BASE_URL + games["link"])
|
||||
log.verbose("get_games, url: %s%s", BASE_URL, games["link"])
|
||||
return_games_list.append(await Game.from_json(data))
|
||||
except Exception:
|
||||
log.error("Error grabbing game data:", exc_info=True)
|
||||
@@ -824,7 +824,6 @@ class Game:
|
||||
) or count >= 20:
|
||||
"""Final game state checks"""
|
||||
if home["game_state"] != self.game_state and home["game_state"] != "Null":
|
||||
|
||||
# Post game final data and check for next game
|
||||
log.debug("Game Final %s @ %s", self.away_team, self.home_team)
|
||||
await self.post_game_state(bot)
|
||||
@@ -931,7 +930,6 @@ class Game:
|
||||
# can_manage_webhooks = False # channel.permissions_for(guild.me).manage_webhooks
|
||||
|
||||
if self.game_state == "Live":
|
||||
|
||||
guild_notifications = guild_settings["game_state_notifications"]
|
||||
channel_notifications = channel_settings["game_state_notifications"]
|
||||
state_notifications = guild_notifications or channel_notifications
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
@@ -11,7 +11,7 @@ from .abc import MixinMeta
|
||||
from .game import Game
|
||||
from .helper import StateFinder, TeamFinder, get_chn_name
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
@@ -325,14 +325,10 @@ class GameDayChannels(MixinMeta):
|
||||
# Return none if there's no category to create the channel
|
||||
return
|
||||
if not category.permissions_for(guild.me).manage_channels:
|
||||
log.info(
|
||||
f"Cannot create new GDC in {repr(guild)} due to too many missing permissions."
|
||||
)
|
||||
log.info("Cannot create new GDC in %r due to too many missing permissions.", guild)
|
||||
return
|
||||
if len(category.channels) >= 50:
|
||||
log.info(
|
||||
f"Cannot create new GDC in {repr(guild)} due to too many channels in category."
|
||||
)
|
||||
log.info("Cannot create new GDC in %r due to too many channels in category.", guild)
|
||||
return
|
||||
if game_data is None:
|
||||
team = await self.config.guild(guild).gdc_team()
|
||||
@@ -353,7 +349,7 @@ class GameDayChannels(MixinMeta):
|
||||
try:
|
||||
new_chn = await guild.create_text_channel(chn_name, category=category)
|
||||
except discord.Forbidden:
|
||||
log.error(f"Error creating channel in {repr(guild)}")
|
||||
log.error("Error creating channel in %r", guild)
|
||||
except Exception:
|
||||
log.exception(f"Error creating channels in {repr(guild)}")
|
||||
return
|
||||
@@ -413,7 +409,7 @@ class GameDayChannels(MixinMeta):
|
||||
await self.config.channel(chn).clear()
|
||||
await chn.delete()
|
||||
except discord.errors.Forbidden:
|
||||
log.error(f"Cannot delete GDC channels in {guild.id} due to permissions issue.")
|
||||
log.error("Cannot delete GDC channels in %s due to permissions issue.", guild.id)
|
||||
except Exception:
|
||||
log.exception(f"Cannot delete GDC channels in {guild.id}")
|
||||
await self.config.guild(guild).gdc.clear()
|
||||
@@ -1,8 +1,8 @@
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
@@ -11,7 +11,7 @@ from .abc import MixinMeta
|
||||
from .game import Game
|
||||
from .helper import StateFinder, TeamFinder, get_chn_name
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
@@ -342,9 +342,7 @@ class GameDayThreads(MixinMeta):
|
||||
if guild.me.is_timed_out():
|
||||
return
|
||||
if not channel.permissions_for(guild.me).create_public_threads:
|
||||
log.info(
|
||||
f"Cannot create new GDT in {repr(guild)} due to too many missing permissions."
|
||||
)
|
||||
log.info("Cannot create new GDT in %r due to too many missing permissions.", guild)
|
||||
return
|
||||
# if len(category.channels) >= 50:
|
||||
# log.info(
|
||||
@@ -394,10 +392,10 @@ class GameDayThreads(MixinMeta):
|
||||
try:
|
||||
new_chn = await channel.create_thread(name=chn_name, message=preview_msg)
|
||||
except discord.Forbidden:
|
||||
log.error(f"Error creating channel in {repr(guild)}")
|
||||
log.error("Error creating channel in %r", guild)
|
||||
return
|
||||
except Exception:
|
||||
log.exception(f"Error creating channels in {repr(guild)}")
|
||||
log.exception("Error creating channels in %r", guild)
|
||||
return
|
||||
async with self.config.guild(guild).gdt() as current_gdc:
|
||||
current_gdc.append(new_chn.id)
|
||||
|
||||
+4
-6
@@ -1,11 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils import AsyncIter
|
||||
@@ -19,11 +19,10 @@ if TYPE_CHECKING:
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
|
||||
class Goal:
|
||||
|
||||
goal_id: str
|
||||
team_name: str
|
||||
scorer_id: int
|
||||
@@ -234,7 +233,7 @@ class Goal:
|
||||
try:
|
||||
guild = channel.guild
|
||||
if not channel.permissions_for(guild.me).send_messages:
|
||||
log.debug("No permission to send messages in %s", repr(channel))
|
||||
log.debug("No permission to send messages in %r", channel)
|
||||
return None
|
||||
|
||||
config = bot.get_cog("Hockey").config
|
||||
@@ -266,7 +265,7 @@ class Goal:
|
||||
except Exception:
|
||||
log.error("Error trying to find montreal goal role")
|
||||
if goal_notifications:
|
||||
log.debug(goal_notifications)
|
||||
log.debug("actually_post_goal goal_notifications: %s", goal_notifications)
|
||||
allowed_mentions = {"allowed_mentions": discord.AllowedMentions(roles=True)}
|
||||
else:
|
||||
allowed_mentions = {"allowed_mentions": discord.AllowedMentions(roles=False)}
|
||||
@@ -501,7 +500,6 @@ class Goal:
|
||||
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=f"{self.description}\n<t:{self.timestamp}:T>")
|
||||
if self.link:
|
||||
em.description = f"[{self.description}]({self.link})\n<t:{self.timestamp}:T>"
|
||||
|
||||
+10
-11
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from enum import Enum
|
||||
@@ -21,6 +20,7 @@ import discord
|
||||
import pytz
|
||||
from discord.ext.commands.converter import Converter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.commands import Context
|
||||
from redbot.core.data_manager import cog_data_path
|
||||
@@ -38,7 +38,7 @@ if TYPE_CHECKING:
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
DATE_RE = re.compile(
|
||||
r"((19|20)\d\d)[- \/.](0[1-9]|1[012]|[1-9])[- \/.](0[1-9]|[12][0-9]|3[01]|[1-9])"
|
||||
@@ -148,16 +148,16 @@ class TeamFinder(discord.app_commands.Transformer):
|
||||
continue
|
||||
nick = data["nickname"]
|
||||
short = data["tri_code"]
|
||||
pattern = fr"{short}\b|" + r"|".join(fr"\b{i}\b" for i in team.split())
|
||||
pattern = rf"{short}\b|" + r"|".join(rf"\b{i}\b" for i in team.split())
|
||||
if nick:
|
||||
pattern += r"|" + r"|".join(fr"\b{i}\b" for i in nick)
|
||||
pattern += r"|" + r"|".join(rf"\b{i}\b" for i in nick)
|
||||
# log.debug(pattern)
|
||||
reg: Pattern = re.compile(fr"\b{pattern}", flags=re.I)
|
||||
reg: Pattern = re.compile(rf"\b{pattern}", flags=re.I)
|
||||
for pot in potential_teams:
|
||||
find = reg.findall(pot)
|
||||
if find:
|
||||
log.debug(reg)
|
||||
log.debug(find)
|
||||
log.verbose("TeamFinder reg: %s", reg)
|
||||
log.verbose("TeamFinder find: %s", find)
|
||||
result.add(team)
|
||||
if include_all and "all" in argument:
|
||||
result.add("all")
|
||||
@@ -195,7 +195,6 @@ class PlayerFinder(discord.app_commands.Transformer):
|
||||
path = cog_data_path(cog) / "players.json"
|
||||
await cls().check_and_download(cog)
|
||||
with path.open(encoding="utf-8", mode="r") as f:
|
||||
|
||||
players = []
|
||||
async for player in AsyncIter(json.loads(f.read())["data"], steps=100):
|
||||
if argument.lower() in player["fullName"].lower():
|
||||
@@ -563,7 +562,7 @@ async def get_channel_obj(
|
||||
if not channel:
|
||||
# await bot.get_cog("Hockey").config.channel_from_id(channel_id).clear()
|
||||
# log.info(f"{channel_id} channel was removed because it no longer exists")
|
||||
log.info(f"{channel_id} Could not be found")
|
||||
log.info("%s Could not be found", channel_id)
|
||||
return None
|
||||
guild = channel.guild
|
||||
await bot.get_cog("Hockey").config.channel(channel).guild_id.set(guild.id)
|
||||
@@ -572,13 +571,13 @@ async def get_channel_obj(
|
||||
if not guild:
|
||||
# await bot.get_cog("Hockey").config.channel_from_id(channel_id).clear()
|
||||
# log.info(f"{channel_id} channel was removed because it no longer exists")
|
||||
log.info(f"{channel_id} Could not be found")
|
||||
log.info("%s Could not be found", channel_id)
|
||||
return None
|
||||
channel = guild.get_channel(channel_id)
|
||||
thread = guild.get_thread(channel_id)
|
||||
if channel is None and thread is None:
|
||||
# await bot.get_cog("Hockey").config.channel_from_id(channel_id).clear()
|
||||
# log.info(f"{channel_id} channel was removed because it no longer exists")
|
||||
log.info(f"{channel_id} Could not be found")
|
||||
log.info("%s Could not be found", channel_id)
|
||||
return None
|
||||
return channel or thread
|
||||
+9
-9
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from abc import ABC
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
@@ -9,6 +8,7 @@ from typing import Any, Dict, List, Literal, Optional
|
||||
import aiohttp
|
||||
import discord
|
||||
import yaml
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils import AsyncIter
|
||||
@@ -29,7 +29,7 @@ from .teamentry import TeamEntry
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
|
||||
class CompositeMetaClass(type(commands.Cog), type(ABC)):
|
||||
@@ -253,13 +253,13 @@ class Hockey(
|
||||
await self.config.guild_from_id(int(guild_id)).leaderboard.clear()
|
||||
except Exception:
|
||||
pass
|
||||
log.info(f"Migrating leaderboard for {guild_id}")
|
||||
log.info("Migrating leaderboard for %s", guild_id)
|
||||
if data.get("pickems"):
|
||||
try:
|
||||
await self.config.guild_from_id(int(guild_id)).pickems.clear()
|
||||
except Exception:
|
||||
pass
|
||||
log.info(f"Migrating pickems for {guild_id}")
|
||||
log.info("Migrating pickems for %s", guild_id)
|
||||
if data.get("pickems_channels"):
|
||||
if not isinstance(data["pickems_channels"], list):
|
||||
# this is just because I don't care but should get it working
|
||||
@@ -270,7 +270,7 @@ class Hockey(
|
||||
await self.config.guild_from_id(int(guild_id)).pickems_channels.clear()
|
||||
except Exception:
|
||||
pass
|
||||
log.info(f"Migrating pickems channels for {guild_id}")
|
||||
log.info("Migrating pickems channels for %s", guild_id)
|
||||
if data.get("pickems_category"):
|
||||
await self.pickems_config.guild_from_id(int(guild_id)).pickems_category.set(
|
||||
data["pickems_category"]
|
||||
@@ -279,7 +279,7 @@ class Hockey(
|
||||
await self.config.guild_from_id(int(guild_id)).pickems_category.clear()
|
||||
except Exception:
|
||||
pass
|
||||
log.info(f"Migrating pickems categories for {guild_id}")
|
||||
log.info("Migrating pickems categories for %s", guild_id)
|
||||
|
||||
##############################################################################
|
||||
# Here is all the logic for gathering game data and updating information #
|
||||
@@ -350,7 +350,7 @@ class Hockey(
|
||||
if data["game"] is not None and data["game"].game_start - timedelta(
|
||||
hours=1
|
||||
) >= datetime.now(timezone.utc):
|
||||
log.debug(
|
||||
log.trace(
|
||||
"Skipping %s @ %s checks until closer to game start.",
|
||||
data["game"].away_team,
|
||||
data["game"].home_team,
|
||||
@@ -377,11 +377,11 @@ class Hockey(
|
||||
game.game_state in ["Live"]
|
||||
and not self.current_games[link]["disabled_buttons"]
|
||||
):
|
||||
log.debug("Disabling buttons for %r", game)
|
||||
log.verbose("Disabling buttons for %r", game)
|
||||
await self.disable_pickems_buttons(game)
|
||||
self.current_games[link]["disabled_buttons"] = True
|
||||
|
||||
log.debug(
|
||||
log.trace(
|
||||
"%s @ %s %s %s - %s",
|
||||
game.away_team,
|
||||
game.home_team,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from io import BytesIO
|
||||
from typing import List, Literal, Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list, pagify
|
||||
@@ -28,7 +28,7 @@ from .stats import LeaderCategories, LeaderView
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
|
||||
hockey_commands = MixinMeta.hockey_commands
|
||||
@@ -148,8 +148,8 @@ class HockeyCommands(MixinMeta):
|
||||
Team and Date can be provided at the same time and then
|
||||
only that teams games may appear in that date range if they exist.
|
||||
"""
|
||||
log.debug(team)
|
||||
log.debug(date)
|
||||
log.verbose("games team: %s", team)
|
||||
log.verbose("games date: %s", date)
|
||||
await ctx.defer()
|
||||
teams = []
|
||||
if team is not None:
|
||||
@@ -389,9 +389,9 @@ class HockeyCommands(MixinMeta):
|
||||
)
|
||||
url = f"{BASE_URL}/api/v1/schedule?season={season}"
|
||||
url += "&teamId=" + ",".join([str(TEAMS[team]["id"])])
|
||||
log.debug(team)
|
||||
log.debug(TEAMS[team]["id"])
|
||||
log.debug(url)
|
||||
log.verbose("season team: %s", team)
|
||||
log.verbose("season team id: %s", TEAMS[team]["id"])
|
||||
log.verbose("season team url: %s", url)
|
||||
async with self.session.get(url) as resp:
|
||||
data = await resp.json()
|
||||
games = [game for date in data["dates"] for game in date["games"]]
|
||||
@@ -428,7 +428,7 @@ class HockeyCommands(MixinMeta):
|
||||
`[season]` The season to get stats data on format can be `YYYY` or `YYYYYYYY`
|
||||
`<player>` The name of the player to search for
|
||||
"""
|
||||
log.info(player)
|
||||
log.verbose("player %s", player)
|
||||
await ctx.defer()
|
||||
season_str = None
|
||||
if season:
|
||||
|
||||
+18
-18
@@ -1,10 +1,10 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, List, Optional, Union
|
||||
|
||||
import discord
|
||||
from discord.ext import tasks
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import bank, commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils import AsyncIter
|
||||
@@ -17,7 +17,7 @@ from .game import Game
|
||||
from .pickems import Pickems
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
hockey_commands = MixinMeta.hockey_commands
|
||||
# defined in abc.py allowing this to be inherited by multiple files
|
||||
@@ -52,7 +52,7 @@ class HockeyPickems(MixinMeta):
|
||||
await self.save_pickems_data()
|
||||
except Exception:
|
||||
log.exception("Error saving pickems data")
|
||||
log.debug("Saved pickems data.")
|
||||
log.verbose("Saved pickems data.")
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_thread_update(self, before: discord.Thread, after: discord.Thread):
|
||||
@@ -66,10 +66,10 @@ class HockeyPickems(MixinMeta):
|
||||
return
|
||||
if str(before.id) in await self.pickems_config.guild(guild).pickems_channels():
|
||||
await after.edit(archived=False)
|
||||
log.debug("Unarchiving %r", after)
|
||||
log.debug("Unarchiving thread %r", after)
|
||||
if before.id in await self.config.guild(guild).gdt():
|
||||
await after.edit(archived=False)
|
||||
log.debug("Unarchiving %r", after)
|
||||
log.debug("Unarchiving thread %r", after)
|
||||
if (
|
||||
before.parent
|
||||
and before.parent.id == await self.pickems_config.guild(guild).pickems_channel()
|
||||
@@ -78,17 +78,17 @@ class HockeyPickems(MixinMeta):
|
||||
return
|
||||
if (datetime.now(timezone.utc) - before.created_at) < timedelta(days=9):
|
||||
await after.edit(archived=False)
|
||||
log.debug("Unarchiving %r", after)
|
||||
log.debug("Unarchiving thread %r", after)
|
||||
|
||||
async def save_pickems_data(self) -> None:
|
||||
to_del: Dict[str, List[str]] = {}
|
||||
# log.debug("Saving pickems data")
|
||||
log.trace("Saving pickems data")
|
||||
# all_pickems = self.all_pickems.copy()
|
||||
async for guild_id, pickems in AsyncIter(self.all_pickems.items(), steps=10):
|
||||
async with self.pickems_config.guild_from_id(int(guild_id)).pickems() as data:
|
||||
for name, pickem in pickems.items():
|
||||
if pickem._should_save:
|
||||
# log.debug("Saving pickem %r", pickem)
|
||||
log.trace("Saving pickem %r", pickem)
|
||||
data[name] = pickem.to_json()
|
||||
self.all_pickems[guild_id][name]._should_save = False
|
||||
if pickem.game_type in ["P", "PR"]:
|
||||
@@ -114,7 +114,7 @@ class HockeyPickems(MixinMeta):
|
||||
for guild_id, pickems in self.all_pickems.items():
|
||||
for game, pickem in pickems.items():
|
||||
# Don't forget to remove persistent views when the cog is unloaded.
|
||||
log.debug(f"Stopping {pickem.name}")
|
||||
log.verbose("Stopping %s", pickem.name)
|
||||
pickem.stop()
|
||||
|
||||
@pickems_loop.before_loop
|
||||
@@ -126,11 +126,11 @@ class HockeyPickems(MixinMeta):
|
||||
for guild_id, data in all_data.items():
|
||||
pickems_list = data.get("pickems", {})
|
||||
if pickems_list is None:
|
||||
log.info(f"Resetting pickems in {guild_id} for incompatible type")
|
||||
log.info("Resetting pickems in %s for incompatible type", guild_id)
|
||||
await self.pickems_config.guild_from_id(int(guild_id)).pickems.clear()
|
||||
continue
|
||||
if type(pickems_list) is list:
|
||||
log.info(f"Resetting pickems in {guild_id} for incompatible type")
|
||||
log.info("Resetting pickems in %S for incompatible type", guild_id)
|
||||
await self.pickems_config.guild_from_id(int(guild_id)).pickems.clear()
|
||||
continue
|
||||
# pickems = [Pickems.from_json(p) for p in pickems_list]
|
||||
@@ -168,10 +168,10 @@ class HockeyPickems(MixinMeta):
|
||||
for guild_id, pickems in all_pickems.items():
|
||||
guild = self.bot.get_guild(int(guild_id))
|
||||
if guild is None:
|
||||
# log.debug("Guild ID %s Not available", guild_id)
|
||||
log.trace("Guild ID %s Not available", guild_id)
|
||||
continue
|
||||
if str(game.game_id) not in pickems:
|
||||
# log.debug("Game %r not in pickems", game)
|
||||
log.trace("Game %r not in pickems", game)
|
||||
continue
|
||||
pickem = self.all_pickems[str(guild_id)][str(game.game_id)]
|
||||
should_edit = pickem.disable_buttons()
|
||||
@@ -181,7 +181,7 @@ class HockeyPickems(MixinMeta):
|
||||
try:
|
||||
channel_id, message_id = message.split("-")
|
||||
except ValueError:
|
||||
log.debug("Game %r missing message %s", game, message)
|
||||
log.verbose("Game %r missing message %s", game, message)
|
||||
continue
|
||||
channel = guild.get_channel_or_thread(int(channel_id))
|
||||
if not channel:
|
||||
@@ -691,7 +691,7 @@ class HockeyPickems(MixinMeta):
|
||||
# keep adding more of these to memory
|
||||
# requiring us to reload over time
|
||||
except discord.errors.Forbidden:
|
||||
log.error(f"Missing permissions to delete old pickems channel in {repr(guild)}")
|
||||
log.error("Missing permissions to delete old pickems channel in %r", guild)
|
||||
pass
|
||||
except Exception:
|
||||
log.exception(f"Error deleting old pickems channels in {repr(guild)}")
|
||||
@@ -719,7 +719,7 @@ class HockeyPickems(MixinMeta):
|
||||
# the main loop still get checked
|
||||
if not await pickems.check_winner(self.pickems_games[name]):
|
||||
continue
|
||||
log.debug("Tallying results for %s", repr(pickems))
|
||||
log.debug("Tallying results for %r", pickems)
|
||||
to_remove.append(name)
|
||||
DEFAULT_LEADERBOARD = {
|
||||
"season": 0,
|
||||
@@ -746,7 +746,7 @@ class HockeyPickems(MixinMeta):
|
||||
try:
|
||||
await bank.deposit_credits(member, int(base_credits))
|
||||
except Exception:
|
||||
log.debug("Could not deposit pickems credits for %s", repr(member))
|
||||
log.debug("Could not deposit pickems credits for %r", member)
|
||||
if pickems.game_type == "P":
|
||||
leaderboard[str(user)]["playoffs"] += 1
|
||||
leaderboard[str(user)]["playoffs_weekly"] += 1
|
||||
@@ -774,7 +774,7 @@ class HockeyPickems(MixinMeta):
|
||||
# leaving this comment so I remember
|
||||
for name in to_remove:
|
||||
try:
|
||||
log.debug(f"Removing pickem {name}")
|
||||
log.verbose("Removing pickem %s", name)
|
||||
del self.all_pickems[str(guild.id)][name]
|
||||
async with self.pickems_config.guild(guild).pickems() as data:
|
||||
if name in data:
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
@@ -13,7 +13,7 @@ from .standings import Conferences, Divisions, Standings
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
hockeyset_commands = MixinMeta.hockeyset_commands
|
||||
|
||||
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any, List, Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
@@ -28,7 +28,7 @@ from .player import Player, SimplePlayer
|
||||
from .schedule import Schedule, ScheduleList
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.hockey")
|
||||
log = getLogger("red.trusty-cogs.hockey")
|
||||
|
||||
|
||||
class GamesMenu(discord.ui.View):
|
||||
@@ -225,7 +225,7 @@ class PlayerPages(menus.ListPageSource):
|
||||
|
||||
async def format_page(self, view: discord.ui.View, player: SimplePlayer) -> discord.Embed:
|
||||
# player = await Player.from_id(page, session=view.cog.session)
|
||||
log.debug(player)
|
||||
log.trace("PlayerPages player: %s", player)
|
||||
player = await player.get_full_stats(self.season, session=view.cog.session)
|
||||
em = player.get_embed()
|
||||
em.set_footer(text=f"Page {view.current_page + 1}/{self.get_max_pages()}")
|
||||
|
||||
+8
-9
@@ -1,10 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.i18n import Translator
|
||||
|
||||
from .constants import TEAMS
|
||||
@@ -12,7 +12,7 @@ from .errors import NotAValidTeamError, UserHasVotedError, VotingHasEndedError
|
||||
from .game import Game
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
|
||||
class PickemsButton(discord.ui.Button):
|
||||
@@ -43,13 +43,12 @@ class PickemsButton(discord.ui.Button):
|
||||
|
||||
async def callback(self, interaction: discord.Interaction):
|
||||
time_now = datetime.now(tz=timezone.utc)
|
||||
log.debug(time_now)
|
||||
log.debug(self.view.game_start)
|
||||
log.verbose("PickemsButton time_now: %s", time_now)
|
||||
log.verbose("PickemsButton game_start: %s", self.view.game_start)
|
||||
if str(interaction.user.id) in self.view.votes:
|
||||
vote = self.view.votes[str(interaction.user.id)]
|
||||
emoji = discord.PartialEmoji.from_str(TEAMS[vote]["emoji"])
|
||||
if time_now > self.view.game_start:
|
||||
|
||||
await self.respond(
|
||||
interaction,
|
||||
_("Voting has ended! You have voted for {emoji} {team}").format(
|
||||
@@ -161,7 +160,7 @@ class Pickems(discord.ui.View):
|
||||
async def on_error(
|
||||
self, interaction: discord.Interaction, error: Exception, item: discord.ui.Item
|
||||
):
|
||||
log.error(f"{error} - {item}")
|
||||
log.error("Pickems %s - %s", error, item)
|
||||
|
||||
def disable_buttons(self) -> bool:
|
||||
if self.home_button.disabled and self.away_button.disabled:
|
||||
@@ -231,7 +230,7 @@ class Pickems(discord.ui.View):
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, data: Dict[str, Optional[Union[str, Dict[str, str]]]]) -> Pickems:
|
||||
# log.debug(data)
|
||||
log.trace("Pickems from_json data: %s", data)
|
||||
game_start = datetime.strptime(data["game_start"], "%Y-%m-%dT%H:%M:%SZ")
|
||||
game_start = game_start.replace(tzinfo=timezone.utc)
|
||||
return cls(
|
||||
@@ -258,7 +257,7 @@ class Pickems(discord.ui.View):
|
||||
`True` if the winner has been set or the game is postponed
|
||||
`False` if the winner has not set and it's not time to clear it yet.
|
||||
"""
|
||||
log.debug("Setting winner for %r", self)
|
||||
log.trace("Setting winner for %r", self)
|
||||
if not game:
|
||||
return False
|
||||
if game.game_state == "Postponed":
|
||||
@@ -297,7 +296,7 @@ class Pickems(discord.ui.View):
|
||||
if game is not None:
|
||||
return await self.set_pickem_winner(game)
|
||||
if self.link and after_game:
|
||||
log.debug("Checking winner for %s", repr(self))
|
||||
log.debug("Checking winner for %r", self)
|
||||
game = await Game.from_url(self.link)
|
||||
return await self.set_pickem_winner(game)
|
||||
return False
|
||||
+19
-19
@@ -1,12 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional, Union
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import box
|
||||
from tabulate import tabulate
|
||||
@@ -15,7 +15,7 @@ from .constants import HEADSHOT_URL, TEAMS
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.hockey")
|
||||
log = getLogger("red.trusty-cogs.hockey")
|
||||
|
||||
|
||||
# This is somewhat unnecessary but for consistency we have the expected
|
||||
@@ -248,7 +248,7 @@ class SimplePlayer:
|
||||
def get_embed(self) -> discord.Embed:
|
||||
try:
|
||||
team_id = self.current_team_id or self.last_nhl_team_id
|
||||
log.debug(team_id)
|
||||
log.verbose("SimplePlayer team_id: %s", team_id)
|
||||
team_name = [name for name, team in TEAMS.items() if team["id"] == team_id][0]
|
||||
colour = int(TEAMS[team_name]["home"].replace("#", ""), 16)
|
||||
logo = TEAMS[team_name]["logo"]
|
||||
@@ -269,8 +269,8 @@ class SimplePlayer:
|
||||
self, season: Optional[str], session: Optional[aiohttp.ClientSession] = None
|
||||
) -> Union[Player, Goalie, Skater]:
|
||||
url = f"https://statsapi.web.nhl.com/api/v1/people/{self.id}/stats?stats=yearByYear"
|
||||
log.debug(url)
|
||||
log.debug(season)
|
||||
log.verbose("get_full_stats url: %s", url)
|
||||
log.verbose("get_full_stats url: %s", season)
|
||||
if session is None:
|
||||
async with aiohttp.ClientSession() as new_session:
|
||||
async with new_session.get(url) as resp:
|
||||
@@ -300,7 +300,7 @@ class SimplePlayer:
|
||||
*stats,
|
||||
)
|
||||
return await player.get_full_stats(season or stats_season)
|
||||
log.debug(f"Returning {repr(self)}")
|
||||
log.verbose("Returning %r", self)
|
||||
return self
|
||||
|
||||
def full_name_url(self) -> str:
|
||||
@@ -324,7 +324,7 @@ class SimplePlayer:
|
||||
else:
|
||||
async with session.get(url) as resp:
|
||||
data = await resp.json()
|
||||
log.info(data)
|
||||
log.info("SimplePlayer from_id data %s", data)
|
||||
return cls(*data["data"][0].values())
|
||||
|
||||
|
||||
@@ -436,8 +436,8 @@ class Skater(SimplePlayer):
|
||||
url = (
|
||||
f"https://statsapi.web.nhl.com/api/v1/people/{self.id}/stats?stats=yearByYearPlayoffs"
|
||||
)
|
||||
log.debug(url)
|
||||
log.debug(season)
|
||||
log.debug("Skater get_full_stats url: %s", url)
|
||||
log.debug("Skater get_full_stats season: %s", season)
|
||||
if session is None:
|
||||
async with aiohttp.ClientSession() as new_session:
|
||||
async with new_session.get(url) as resp:
|
||||
@@ -471,7 +471,7 @@ class Skater(SimplePlayer):
|
||||
def get_embed(self) -> discord.Embed:
|
||||
try:
|
||||
team_id = self.current_team_id
|
||||
log.debug(team_id)
|
||||
log.debug("Skater get_embed team_id: %s", team_id)
|
||||
team_name = [name for name, team in TEAMS.items() if team["id"] == team_id][0]
|
||||
colour = int(TEAMS[team_name]["home"].replace("#", ""), 16)
|
||||
logo = TEAMS[team_name]["logo"]
|
||||
@@ -481,7 +481,7 @@ class Skater(SimplePlayer):
|
||||
logo = "https://cdn.bleacherreport.net/images/team_logos/328x328/nhl.png"
|
||||
try:
|
||||
team_id = self.last_nhl_team_id
|
||||
log.debug(team_id)
|
||||
log.debug("Skater get_embed team_id: %s", team_id)
|
||||
team_name = [name for name, team in TEAMS.items() if team["id"] == team_id][0]
|
||||
emoji = f'<:{TEAMS[team_name]["emoji"]}>'
|
||||
except IndexError:
|
||||
@@ -563,7 +563,7 @@ class SkaterPlayoffs(Skater):
|
||||
def get_embed(self) -> discord.Embed:
|
||||
try:
|
||||
team_id = self.current_team_id
|
||||
log.debug(team_id)
|
||||
log.debug("SkaterPlayoffs get_embed team_id: %s", team_id)
|
||||
team_name = [name for name, team in TEAMS.items() if team["id"] == team_id][0]
|
||||
colour = int(TEAMS[team_name]["home"].replace("#", ""), 16)
|
||||
logo = TEAMS[team_name]["logo"]
|
||||
@@ -573,7 +573,7 @@ class SkaterPlayoffs(Skater):
|
||||
logo = "https://cdn.bleacherreport.net/images/team_logos/328x328/nhl.png"
|
||||
try:
|
||||
team_id = self.last_nhl_team_id
|
||||
log.debug(team_id)
|
||||
log.debug("SkaterPlayoffs get_embed team_id: %s", team_id)
|
||||
team_name = [name for name, team in TEAMS.items() if team["id"] == team_id][0]
|
||||
emoji = f'<:{TEAMS[team_name]["emoji"]}>'
|
||||
except IndexError:
|
||||
@@ -649,8 +649,8 @@ class Goalie(SimplePlayer):
|
||||
url = (
|
||||
f"https://statsapi.web.nhl.com/api/v1/people/{self.id}/stats?stats=yearByYearPlayoffs"
|
||||
)
|
||||
log.debug(url)
|
||||
log.debug(season)
|
||||
log.verbose("Goalie get_full_stats url: %s", url)
|
||||
log.verbose("Goalie get_full_stats season: %s", season)
|
||||
if session is None:
|
||||
async with aiohttp.ClientSession() as new_session:
|
||||
async with new_session.get(url) as resp:
|
||||
@@ -673,7 +673,7 @@ class Goalie(SimplePlayer):
|
||||
def get_embed(self) -> discord.Embed:
|
||||
try:
|
||||
team_id = self.current_team_id
|
||||
log.debug(team_id)
|
||||
log.verbose("Goalie team_id: %s", team_id)
|
||||
team_name = [name for name, team in TEAMS.items() if team["id"] == team_id][0]
|
||||
colour = int(TEAMS[team_name]["home"].replace("#", ""), 16)
|
||||
logo = TEAMS[team_name]["logo"]
|
||||
@@ -683,7 +683,7 @@ class Goalie(SimplePlayer):
|
||||
logo = "https://cdn.bleacherreport.net/images/team_logos/328x328/nhl.png"
|
||||
try:
|
||||
team_id = self.last_nhl_team_id
|
||||
log.debug(team_id)
|
||||
log.verbose("Goalie team_id: %s", team_id)
|
||||
team_name = [name for name, team in TEAMS.items() if team["id"] == team_id][0]
|
||||
emoji = f'<:{TEAMS[team_name]["emoji"]}>'
|
||||
except IndexError:
|
||||
@@ -746,7 +746,7 @@ class GoaliePlayoffs(Goalie):
|
||||
def get_embed(self) -> discord.Embed:
|
||||
try:
|
||||
team_id = self.current_team_id
|
||||
log.debug(team_id)
|
||||
log.verbose("GoaliePlayoffs team_id: %s", team_id)
|
||||
team_name = [name for name, team in TEAMS.items() if team["id"] == team_id][0]
|
||||
colour = int(TEAMS[team_name]["home"].replace("#", ""), 16)
|
||||
logo = TEAMS[team_name]["logo"]
|
||||
@@ -756,7 +756,7 @@ class GoaliePlayoffs(Goalie):
|
||||
logo = "https://cdn.bleacherreport.net/images/team_logos/328x328/nhl.png"
|
||||
try:
|
||||
team_id = self.last_nhl_team_id
|
||||
log.debug(team_id)
|
||||
log.verbose("GoaliePlayoffs team_id: %s", team_id)
|
||||
team_name = [name for name, team in TEAMS.items() if team["id"] == team_id][0]
|
||||
emoji = f'<:{TEAMS[team_name]["emoji"]}>'
|
||||
except IndexError:
|
||||
|
||||
+16
-9
@@ -1,9 +1,9 @@
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, Optional
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list, pagify
|
||||
from redbot.vendored.discord.ext import menus
|
||||
@@ -14,7 +14,7 @@ from .game import Game
|
||||
from .helper import utc_to_local
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.hockey")
|
||||
log = getLogger("red.trusty-cogs.hockey")
|
||||
|
||||
|
||||
class Schedule(menus.PageSource):
|
||||
@@ -61,13 +61,20 @@ class Schedule(menus.PageSource):
|
||||
skip_prev: bool = False,
|
||||
game_id: Optional[int] = None,
|
||||
) -> dict:
|
||||
log.debug(f"Cache size is {len(self._cache)} {page_number=} {game_id=}")
|
||||
log.debug(
|
||||
"Cache size is %s page_number=%s game_id=%s", len(self._cache), page_number, game_id
|
||||
)
|
||||
if game_id is not None:
|
||||
for game in self._cache:
|
||||
if game["gamePk"] == game_id:
|
||||
log.debug("getting game")
|
||||
log.verbose("getting game %s", game_id)
|
||||
page_number = self._cache.index(game)
|
||||
log.debug(f"{page_number=} {self.last_page=}")
|
||||
log.verbose(
|
||||
"game_id=%s page_number=%s last_page=%s",
|
||||
game_id,
|
||||
page_number,
|
||||
self.last_page,
|
||||
)
|
||||
self._last_page = page_number
|
||||
self._index = page_number
|
||||
return self._cache[page_number]
|
||||
@@ -88,7 +95,7 @@ class Schedule(menus.PageSource):
|
||||
return page
|
||||
|
||||
async def format_page(self, menu: menus.MenuPages, game: dict) -> discord.Embed:
|
||||
log.debug(BASE_URL + game["link"])
|
||||
log.trace("%s%s", BASE_URL, game["link"])
|
||||
if self._session is not None:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(BASE_URL + game["link"]) as resp:
|
||||
@@ -332,7 +339,7 @@ class ScheduleList(menus.PageSource):
|
||||
home_abr = home_team
|
||||
away_abr = away_team
|
||||
broadcast_str = ""
|
||||
log.debug(game)
|
||||
log.verbose("ScheduleList game: %s", game)
|
||||
if "broadcasts" in game and self.show_broadcasts:
|
||||
broadcasts = game["broadcasts"]
|
||||
if broadcasts:
|
||||
@@ -493,7 +500,7 @@ class ScheduleList(menus.PageSource):
|
||||
Actually grab the list of games.
|
||||
"""
|
||||
# compare_date = datetime.utcnow().strftime("%Y-%m-%d")
|
||||
log.debug(date)
|
||||
log.verbose("_next_batch date: %s", date)
|
||||
days_to_check = 0
|
||||
if self.team != []:
|
||||
days_to_check = 7
|
||||
@@ -524,7 +531,7 @@ class ScheduleList(menus.PageSource):
|
||||
params["teamId"] = ",".join(str(TEAMS[t]["id"]) for t in self.team)
|
||||
self._last_searched = f"<t:{date_timestamp}> to <t:{end_date_timestamp}>"
|
||||
async with self._session.get(url, params=params) as resp:
|
||||
log.debug(resp.url)
|
||||
log.verbose("_next_batch Response URL: %s", resp.url)
|
||||
data = await resp.json()
|
||||
games = [game for date in data["dates"] for game in date["games"]]
|
||||
if not games:
|
||||
|
||||
+3
-4
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
@@ -10,6 +9,7 @@ from typing import TYPE_CHECKING, Dict, List, Literal, NamedTuple, Optional, Uni
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils import AsyncIter
|
||||
from redbot.vendored.discord.ext import menus
|
||||
@@ -31,7 +31,7 @@ if TYPE_CHECKING:
|
||||
|
||||
_ = Translator("Hockey", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Hockey")
|
||||
log = getLogger("red.trusty-cogs.Hockey")
|
||||
|
||||
|
||||
class StreakType(Enum):
|
||||
@@ -532,9 +532,8 @@ class Standings:
|
||||
guild = bot.get_guild(guild_id)
|
||||
if guild is None:
|
||||
continue
|
||||
log.debug(guild.name)
|
||||
log.verbose("post_automatic_standings, guild name: ", guild.name)
|
||||
if data["post_standings"]:
|
||||
|
||||
search = data["standings_type"]
|
||||
if search is None:
|
||||
continue
|
||||
|
||||
@@ -21,6 +21,8 @@ _ = Translator("Hockey", __file__)
|
||||
|
||||
# https://github.com/Rapptz/discord.py/blob/1bfe6b2bb160ce802a1f08afed73941a19a0a651/discord/app_commands/commands.py#L132
|
||||
CAMEL_CASE_REGEX = re.compile(r"(?<!^)(?=[A-Z])")
|
||||
|
||||
|
||||
# https://github.com/Rapptz/discord.py/blob/1bfe6b2bb160ce802a1f08afed73941a19a0a651/discord/app_commands/commands.py#L190-L191
|
||||
def _fix_camel_case(text: str) -> str:
|
||||
return CAMEL_CASE_REGEX.sub(" ", text).title()
|
||||
|
||||
+5
-5
@@ -1,16 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, List, NamedTuple, Optional, Tuple
|
||||
|
||||
import aiohttp
|
||||
from red_commons.logging import getLogger
|
||||
|
||||
BASE_URL = "https://{ip}/clip/v2/"
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.hue")
|
||||
log = getLogger("red.trusty-cogs.hue")
|
||||
|
||||
|
||||
class HueError(Exception):
|
||||
@@ -382,7 +382,7 @@ class Light:
|
||||
|
||||
async def edit(self):
|
||||
body = self.to_json()
|
||||
log.info(body)
|
||||
log.verbose("Light - edit - body: $s", body)
|
||||
return await self._client.request("PUT", self.url, body=body)
|
||||
|
||||
async def flash(
|
||||
@@ -485,10 +485,10 @@ class Client:
|
||||
) -> dict:
|
||||
async with self.session.request(method, url, json=body, params=params) as resp:
|
||||
data = await resp.json()
|
||||
log.info(data)
|
||||
log.verbose("Light - request - data: $s", data)
|
||||
if "errors" in data:
|
||||
for error in data["errors"]:
|
||||
log.debug(error["description"])
|
||||
log.verbose("Client, error description: %s", error["description"])
|
||||
return data
|
||||
|
||||
async def auth(self):
|
||||
|
||||
+2
-2
@@ -1,11 +1,11 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, checks, commands
|
||||
|
||||
from .api import Client, HueError
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.hue")
|
||||
log = getLogger("red.trusty-cogs.hue")
|
||||
|
||||
|
||||
class Hue(commands.Cog):
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import asyncio
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import textwrap
|
||||
@@ -13,12 +12,13 @@ import aiohttp
|
||||
import discord
|
||||
import numpy as np
|
||||
from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageSequence
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.data_manager import bundled_data_path
|
||||
|
||||
from .converter import ImageFinder
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.imagemaker")
|
||||
log = getLogger("red.trusty-cogs.imagemaker")
|
||||
|
||||
try:
|
||||
import cv2
|
||||
|
||||
+3
-3
@@ -1,16 +1,16 @@
|
||||
import logging
|
||||
import re
|
||||
from typing import Dict, List, Tuple
|
||||
|
||||
import aiohttp
|
||||
from discord.ext.commands.converter import Converter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, checks, commands
|
||||
from redbot.core.utils.chat_formatting import pagify
|
||||
|
||||
SEARCH_URL = "https://api.imgflip.com/get_memes"
|
||||
CAPTION_URL = "https://api.imgflip.com/caption_image"
|
||||
log = logging.getLogger("red.trusty-cogs.ImgFlip")
|
||||
log = getLogger("red.trusty-cogs.ImgFlip")
|
||||
|
||||
|
||||
class Meme(Converter):
|
||||
@@ -84,7 +84,7 @@ class Imgflip(commands.Cog):
|
||||
async def get_meme(
|
||||
self, meme: int, boxes: List[Dict[str, str]], username: str, password: str
|
||||
) -> str:
|
||||
log.debug(boxes)
|
||||
log.verbose("Imgflip get_meme boxes: %s", boxes)
|
||||
try:
|
||||
form_data = aiohttp.FormData()
|
||||
form_data.add_field("template_id", meme)
|
||||
|
||||
+19
-58
@@ -29,39 +29,27 @@ insults: List[str] = [
|
||||
_(
|
||||
"You're so fat when you went to the circus the little girl asked if she could ride the elephant."
|
||||
),
|
||||
_(
|
||||
"You're so fat when you go on an airplane, you have to pay baggage fees for your ass."
|
||||
),
|
||||
_("You're so fat when you go on an airplane, you have to pay baggage fees for your ass."),
|
||||
_("You're so fat whenever you go to the beach the tide comes in."),
|
||||
_("You're so fat I could slap your butt and ride the waves."),
|
||||
_(
|
||||
"You're so fat I'd have to grease the door frame and hold a Twinkie on the other side just to get you through."
|
||||
),
|
||||
_(
|
||||
"Yo Mama so dumb I told her Christmas was around the corner and she went looking for it."
|
||||
),
|
||||
_("Yo Mama so dumb I told her Christmas was around the corner and she went looking for it."),
|
||||
_("You're so dumb it took you 2 hours to watch 60 minutes."),
|
||||
_("Yo Mama so dumb she bought tickets to Xbox Live."),
|
||||
_("You're so dumb that you thought The Exorcist was a workout video."),
|
||||
_(
|
||||
"You're so ugly that you went to the salon and it took 3 hours just to get an estimate."
|
||||
),
|
||||
_("You're so ugly that you went to the salon and it took 3 hours just to get an estimate."),
|
||||
_("You're so ugly that even Scooby Doo couldn't solve that mystery."),
|
||||
_("What is the weighted center between Planet X and Planet Y? Oh it's YOU!"),
|
||||
_(":eggplant: :eggplant: :eggplant:"),
|
||||
_("Your birth certificate is an apology letter from the condom factory."),
|
||||
_("I wasn't born with enough middle fingers to let you know how I feel about you."),
|
||||
_(
|
||||
"You must have been born on a highway because that's where most accidents happen."
|
||||
),
|
||||
_("You must have been born on a highway because that's where most accidents happen."),
|
||||
_("I'm jealous of all the people that haven't met you."),
|
||||
_("I bet your brain feels as good as new, seeing that you never use it."),
|
||||
_(
|
||||
"I'm not saying I hate you, but I would unplug your life support to charge my phone."
|
||||
),
|
||||
_(
|
||||
"You're so ugly, when your mom dropped you off at school she got a fine for littering."
|
||||
),
|
||||
_("I'm not saying I hate you, but I would unplug your life support to charge my phone."),
|
||||
_("You're so ugly, when your mom dropped you off at school she got a fine for littering."),
|
||||
_("You bring everyone a lot of joy, when you leave the room."),
|
||||
_("What's the difference between you and eggs? Eggs get laid and you don't."),
|
||||
_("You're as bright as a black hole, and twice as dense."),
|
||||
@@ -77,15 +65,11 @@ insults: List[str] = [
|
||||
_("I have neither the time nor the crayons to explain this to you."),
|
||||
_("You have two brains cells, one is lost and the other is out looking for it."),
|
||||
_("How many times do I have to flush to get rid of you?"),
|
||||
_(
|
||||
"I don't exactly hate you, but if you were on fire and I had water, I'd drink it."
|
||||
),
|
||||
_("I don't exactly hate you, but if you were on fire and I had water, I'd drink it."),
|
||||
_("You shouldn't play hide and seek, no one would look for you."),
|
||||
_("Some drink from the fountain of knowledge; you only gargled."),
|
||||
_("Roses are red violets are blue, God made me pretty, what happened to you?"),
|
||||
_(
|
||||
"It's better to let someone think you are an Idiot than to open your mouth and prove it."
|
||||
),
|
||||
_("It's better to let someone think you are an Idiot than to open your mouth and prove it."),
|
||||
_(
|
||||
"Somewhere out there is a tree, tirelessly producing oxygen so you can breathe. I think you owe it an apology."
|
||||
),
|
||||
@@ -100,9 +84,7 @@ insults: List[str] = [
|
||||
_("What are you going to do for a face when the baboon wants his butt back?"),
|
||||
_("Well I could agree with you, but then we'd both be wrong."),
|
||||
_("You're so fat, you could sell shade."),
|
||||
_(
|
||||
"It looks like your face caught on fire and someone tried to put it out with a hammer."
|
||||
),
|
||||
_("It looks like your face caught on fire and someone tried to put it out with a hammer."),
|
||||
_("You're not funny, but your life, now that's a joke."),
|
||||
_("You're so fat the only letters of the alphabet you know are KFC."),
|
||||
_("Oh my God, look at you. Was anyone else hurt in the accident?"),
|
||||
@@ -121,9 +103,7 @@ insults: List[str] = [
|
||||
_("Your parents hated you so much your bath toys were an iron and a toaster"),
|
||||
_("Don't feel sad, don't feel blue, Frankenstein was ugly too."),
|
||||
_("You're so ugly, you scared the crap out of the toilet."),
|
||||
_(
|
||||
"It's kinda sad watching you attempt to fit your entire vocabulary into a sentence."
|
||||
),
|
||||
_("It's kinda sad watching you attempt to fit your entire vocabulary into a sentence."),
|
||||
_("I fart to make you smell better."),
|
||||
_("You're so ugly you make blind kids cry."),
|
||||
_("You're a person of rare intelligence. It's rare when you show any."),
|
||||
@@ -183,20 +163,14 @@ insults: List[str] = [
|
||||
_("I thought of you today. It reminded me to take the garbage out."),
|
||||
_("I'm sorry I didn't get that - I don't speak idiot."),
|
||||
_("Hey, your village called \u2013 they want their idiot back."),
|
||||
_(
|
||||
"I just stepped in something that was smarter than you\u2026 and smelled better too."
|
||||
),
|
||||
_("I just stepped in something that was smarter than you\u2026 and smelled better too."),
|
||||
_("You're so fat that at the zoo the elephants started throwing you peanuts."),
|
||||
_("You're so fat every time you turn around, it's your birthday."),
|
||||
_(
|
||||
"You're so fat your idea of dieting is deleting the cookies from your internet cache."
|
||||
),
|
||||
_("You're so fat your idea of dieting is deleting the cookies from your internet cache."),
|
||||
_("You're so fat your shadow weighs 35 pounds."),
|
||||
_("You're so fat I could tell you to haul ass and you'd have to make two trips."),
|
||||
_("You're so fat I took a picture of you at Christmas and it's still printing."),
|
||||
_(
|
||||
"You're so fat I tried to hang a picture of you on my wall, and my wall fell over."
|
||||
),
|
||||
_("You're so fat I tried to hang a picture of you on my wall, and my wall fell over."),
|
||||
_("You're so fat Mount Everest tried to climb you."),
|
||||
_("You're so fat you can't even jump to a conclusion."),
|
||||
_("You're so fat you can't fit in any timeline."),
|
||||
@@ -222,9 +196,7 @@ insults: List[str] = [
|
||||
_("If your IQ was 3 points higher, you'd be a rock."),
|
||||
_("I would insult you but nature did a better job."),
|
||||
_("Does your ass get jealous of all the shit that comes out of your mouth?"),
|
||||
_(
|
||||
"If I ate a bowl of alphabet soup, I could shit out a smarter sentence than any of yours."
|
||||
),
|
||||
_("If I ate a bowl of alphabet soup, I could shit out a smarter sentence than any of yours."),
|
||||
_("You're not pretty enough to be this stupid."),
|
||||
_(
|
||||
"That little voice in the back of your head, telling you you'll never be good enough? It's right."
|
||||
@@ -236,9 +208,7 @@ insults: List[str] = [
|
||||
_("I bite my thumb at you, sir."),
|
||||
_("I'd call you a tool, but that would imply you were useful in at least one way."),
|
||||
_("I hope you outlive your children."),
|
||||
_(
|
||||
"Are you and your dick having a competition to see who can disappoint me the most?"
|
||||
),
|
||||
_("Are you and your dick having a competition to see who can disappoint me the most?"),
|
||||
_("Yo mamma is so ugly her portraits hang themselves."),
|
||||
_("Your birth certificate is an apology from the abortion clinic."),
|
||||
_("If you were anymore inbred you'd be a sandwich."),
|
||||
@@ -248,9 +218,7 @@ insults: List[str] = [
|
||||
),
|
||||
_("Don’t feel bad, there are many people who have no talent!"),
|
||||
_("I’d like to kick you in the teeth, but why should I improve your looks?"),
|
||||
_(
|
||||
"At least there’s one thing good about your body, it’s not as ugly as your face."
|
||||
),
|
||||
_("At least there’s one thing good about your body, it’s not as ugly as your face."),
|
||||
_("Brains aren’t everything. In fact, in your case they’re nothing."),
|
||||
_("If I had a face like yours I’d sue my parents."),
|
||||
_("Don’t think, it might sprain your brain."),
|
||||
@@ -262,9 +230,7 @@ insults: List[str] = [
|
||||
_(
|
||||
"Your psychiatrist told you you were crazy and when you wanted a second opinion. He said okay, you're ugly too."
|
||||
),
|
||||
_(
|
||||
"Behind every fat person there is a beautiful person. No seriously, your in the way."
|
||||
),
|
||||
_("Behind every fat person there is a beautiful person. No seriously, your in the way."),
|
||||
_("Calling you an idiot would be an insult to all the stupid people."),
|
||||
_("Some babies were dropped on their heads but you were clearly thrown at a wall."),
|
||||
_("Why don't you go play in the traffic."),
|
||||
@@ -305,9 +271,7 @@ insults: List[str] = [
|
||||
_("Your IQ is actually lower than The Mariana Trench."),
|
||||
_("You're so annoying even the flies stay away from your stench."),
|
||||
_("Go away, please."),
|
||||
_(
|
||||
"It looks like your face caught fire and someone tried to put it out with a hammer."
|
||||
),
|
||||
_("It looks like your face caught fire and someone tried to put it out with a hammer."),
|
||||
_("Your family tree must be a cactus because everyone on it is a prick."),
|
||||
_("Someday you will go far, and I hope you stay there."),
|
||||
_("The zoo called. They're wondering how you got out of your cage."),
|
||||
@@ -347,9 +311,7 @@ insults: List[str] = [
|
||||
_("What language are you speaking? Cause it sounds like bullshit."),
|
||||
_("You have a room temperature IQ - if the room is in Antarctica."),
|
||||
_("I would ask you how old you are but I know you can't count that high."),
|
||||
_(
|
||||
"Do you want to know how I get all these insults? I use something called intelligence."
|
||||
),
|
||||
_("Do you want to know how I get all these insults? I use something called intelligence."),
|
||||
_("I was going to give you a nasty look, but you already have one."),
|
||||
_("As an outsider, what do you think of the human race?"),
|
||||
_("Oh, what? Sorry. I was trying to imagine you with a personality."),
|
||||
@@ -403,7 +365,6 @@ class Insult(commands.Cog):
|
||||
|
||||
msg = " "
|
||||
if user:
|
||||
|
||||
if user.id == self.bot.user.id:
|
||||
user = ctx.message.author
|
||||
bot_msg = [
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import logging
|
||||
import re
|
||||
from typing import Pattern, Union
|
||||
|
||||
import discord
|
||||
from discord.ext.commands.converter import IDConverter, InviteConverter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, VersionInfo, commands, version_info
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list, pagify
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.inviteblocklist")
|
||||
log = getLogger("red.trusty-cogs.inviteblocklist")
|
||||
|
||||
_ = Translator("ExtendedModLog", __file__)
|
||||
|
||||
@@ -77,7 +77,6 @@ class ChannelUserRole(IDConverter):
|
||||
|
||||
|
||||
class InviteBlocklist(commands.Cog):
|
||||
|
||||
__author__ = ["TrustyJAID"]
|
||||
__version__ = "1.1.3"
|
||||
|
||||
@@ -175,10 +174,9 @@ class InviteBlocklist(commands.Cog):
|
||||
await message.delete()
|
||||
except discord.errors.Forbidden:
|
||||
log.error(
|
||||
_(
|
||||
"I tried to delete an invite link posted in {guild} "
|
||||
"but lacked the permission to do so"
|
||||
).format(guild=guild.name)
|
||||
"I tried to delete an invite link posted in %s "
|
||||
"but lacked the permission to do so",
|
||||
guild.name,
|
||||
)
|
||||
return
|
||||
if whitelist := await self.config.guild(message.guild).whitelist():
|
||||
@@ -191,10 +189,9 @@ class InviteBlocklist(commands.Cog):
|
||||
await message.delete()
|
||||
except discord.errors.Forbidden:
|
||||
log.error(
|
||||
_(
|
||||
"I tried to delete an invite link posted in {guild} "
|
||||
"but lacked the permission to do so"
|
||||
).format(guild=guild.name)
|
||||
"I tried to delete an invite link posted in %s "
|
||||
"but lacked the permission to do so",
|
||||
guild.name,
|
||||
)
|
||||
return
|
||||
return
|
||||
@@ -208,10 +205,9 @@ class InviteBlocklist(commands.Cog):
|
||||
await message.delete()
|
||||
except discord.errors.Forbidden:
|
||||
log.error(
|
||||
_(
|
||||
"I tried to delete an invite link posted in {guild} "
|
||||
"but lacked the permission to do so"
|
||||
).format(guild=guild.name)
|
||||
"I tried to delete an invite link posted in %s "
|
||||
"but lacked the permission to do so",
|
||||
guild.name,
|
||||
)
|
||||
return
|
||||
return
|
||||
|
||||
+3
-3
@@ -1,11 +1,11 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from red_commons.logging import getLogger
|
||||
from redbot import version_info
|
||||
from redbot.core import Config, checks, commands, i18n
|
||||
from redbot.core.dev_commands import Dev
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.loaddev")
|
||||
log = getLogger("red.trusty-cogs.loaddev")
|
||||
|
||||
_ = i18n.Translator("LoadDev", __file__)
|
||||
|
||||
@@ -114,7 +114,7 @@ class LoadDev(commands.Cog):
|
||||
del dev.all_commands[str(command)]
|
||||
command.name = replace_mock
|
||||
dev.all_commands[replace_mock] = command
|
||||
log.debug(command.name)
|
||||
log.verbose("load_dev loading command: %s", command.name)
|
||||
await self.bot.remove_cog("Dev")
|
||||
# remove currently existing dev cog if it's loaded
|
||||
await self.bot.add_cog(dev)
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from datetime import timedelta
|
||||
from typing import Dict, Optional, Set
|
||||
|
||||
import discord
|
||||
from discord.ext.commands.view import StringView
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.commands import Context
|
||||
from redbot.core.utils.antispam import AntiSpam
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
|
||||
log = logging.getLogger("red.Trusty-Cogs.mentionprefix")
|
||||
log = getLogger("red.Trusty-Cogs.mentionprefix")
|
||||
|
||||
HELP_RE = re.compile(r"^.*help$", flags=re.I)
|
||||
|
||||
|
||||
+6
-6
@@ -1,11 +1,11 @@
|
||||
import logging
|
||||
import random
|
||||
from typing import Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.mock")
|
||||
log = getLogger("red.trusty-cogs.mock")
|
||||
|
||||
|
||||
class Mock(commands.Cog):
|
||||
@@ -57,12 +57,12 @@ class Mock(commands.Cog):
|
||||
the `channel` and put them all together
|
||||
"""
|
||||
if isinstance(msg, str):
|
||||
log.debug("Mocking a given string")
|
||||
log.verbose("Mocking a given string")
|
||||
result = await self.cap_change(str(msg))
|
||||
result += f"\n\n[Mocking Message]({ctx.message.jump_url})"
|
||||
author = ctx.message.author
|
||||
elif isinstance(msg, discord.Member):
|
||||
log.debug("Mocking a user")
|
||||
log.verbose("Mocking a user")
|
||||
total_msg = ""
|
||||
async for message in ctx.channel.history(limit=10):
|
||||
if message.author == msg:
|
||||
@@ -70,13 +70,13 @@ class Mock(commands.Cog):
|
||||
result = await self.cap_change(total_msg)
|
||||
author = msg
|
||||
elif isinstance(msg, discord.Message):
|
||||
log.debug("Mocking a message")
|
||||
log.verbose("Mocking a message")
|
||||
result = await self.cap_change(msg.content)
|
||||
result += f"\n\n[Mocking Message]({msg.jump_url})"
|
||||
author = msg.author
|
||||
search_msg = msg
|
||||
else:
|
||||
log.debug("Mocking last message in chat")
|
||||
log.verbose("Mocking last message in chat")
|
||||
async for message in ctx.channel.history(limit=2):
|
||||
search_msg = message
|
||||
author = search_msg.author
|
||||
|
||||
+3
-5
@@ -1,11 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Literal, Optional
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from discord.ext import tasks
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils import bounded_gather
|
||||
@@ -46,12 +46,11 @@ if TYPE_CHECKING:
|
||||
|
||||
_ = Translator("NASA", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.NASACog")
|
||||
log = getLogger("red.trusty-cogs.NASACog")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
class NASACog(commands.Cog):
|
||||
|
||||
__author__ = ["TrustyJAID"]
|
||||
__version__ = "1.0.0"
|
||||
|
||||
@@ -506,7 +505,6 @@ class NASACog(commands.Cog):
|
||||
await BaseMenu(source=TLEPages(feed)).start(ctx=ctx)
|
||||
|
||||
async def request(self, url: str, parameters: dict = {}, include_api_key: bool = True) -> dict:
|
||||
|
||||
if include_api_key:
|
||||
tokens = await self.bot.get_shared_api_tokens("nasa")
|
||||
parameters["api_key"] = tokens.get("api_key", "DEMO_KEY")
|
||||
@@ -515,7 +513,7 @@ class NASACog(commands.Cog):
|
||||
self._last_rate_limit_limit = resp.headers.get("X-RateLimit-Limit", None)
|
||||
if resp.status == 200:
|
||||
data = await resp.json()
|
||||
log.debug(resp.url)
|
||||
log.verbose("Response URL: %s", resp.url)
|
||||
else:
|
||||
raise APIError(
|
||||
f"There was an error with the API: Error Code {resp.status}\n"
|
||||
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
|
||||
# from discord.ext.commands.errors import BadArgument
|
||||
from redbot.core.commands import commands
|
||||
@@ -25,7 +25,7 @@ from .models import (
|
||||
TLEMember,
|
||||
)
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.NASACog")
|
||||
log = getLogger("red.Trusty-cogs.NASACog")
|
||||
_ = Translator("NASA", __file__)
|
||||
|
||||
|
||||
|
||||
+5
-5
@@ -1,6 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
@@ -10,6 +9,7 @@ from typing import Dict, List, NamedTuple, Optional, Union
|
||||
import aiohttp
|
||||
import discord
|
||||
import skyfield
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_number
|
||||
@@ -18,7 +18,7 @@ from skyfield.toposlib import wgs84
|
||||
|
||||
_ = Translator("NASA", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.NASACog")
|
||||
log = getLogger("red.trusty-cogs.NASACog")
|
||||
|
||||
HEADERS = {"User-Agent": "Trusty-cogs NASA cog for Red-DiscordBot"}
|
||||
|
||||
@@ -790,8 +790,8 @@ class Event:
|
||||
lon = self.geometry[-1].coordinates[0]
|
||||
lat = self.geometry[-1].coordinates[1]
|
||||
date = self.geometry[-1].date
|
||||
row = int((90 - lat) * (2 ** 3) / 288)
|
||||
col = int((180 + lon) * (2 ** 3) / 288)
|
||||
row = int((90 - lat) * (2**3) / 288)
|
||||
col = int((180 + lon) * (2**3) / 288)
|
||||
date_str = date.strftime("%Y-%m-%d")
|
||||
return f"https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/MODIS_Terra_CorrectedReflectance_TrueColor/default/{date_str}/250m/3/{row}/{col}.jpg"
|
||||
|
||||
@@ -840,7 +840,7 @@ class XYZPoint(NamedTuple):
|
||||
|
||||
@property
|
||||
def distance(self):
|
||||
return sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
|
||||
return sqrt(self.x**2 + self.y**2 + self.z**2)
|
||||
|
||||
|
||||
class Quaternion(NamedTuple):
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# https://github.com/NotSoSuper/NotSoBot
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
@@ -22,13 +21,14 @@ import wand.color
|
||||
import wand.drawing
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageOps, ImageSequence
|
||||
from pyfiglet import figlet_format
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.data_manager import bundled_data_path, cog_data_path
|
||||
|
||||
from .converter import ImageFinder
|
||||
from .vw import macintoshplus
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.NotSoBot")
|
||||
log = getLogger("red.trusty-cogs.NotSoBot")
|
||||
|
||||
try:
|
||||
import aalib
|
||||
@@ -340,7 +340,7 @@ class NotSoBot(commands.Cog):
|
||||
if len(getattr(img, "sequence", [])) > 1:
|
||||
is_gif = True
|
||||
if is_gif:
|
||||
log.debug("Is gif")
|
||||
log.verbose("Is gif")
|
||||
for change in img.sequence:
|
||||
change.transform(resize="512x512")
|
||||
change.liquid_rescale(
|
||||
@@ -361,7 +361,7 @@ class NotSoBot(commands.Cog):
|
||||
# for i in range(len(img.sequence)):
|
||||
# with img.sequence[i] as change:
|
||||
else:
|
||||
log.debug("Is not gif")
|
||||
log.verbose("Is not gif")
|
||||
for x in range(0, 30):
|
||||
if x == 0:
|
||||
log.debug("Cloning initial image")
|
||||
@@ -870,7 +870,7 @@ class NotSoBot(commands.Cog):
|
||||
count = 0
|
||||
list_im = []
|
||||
for url in urls:
|
||||
log.debug(url)
|
||||
log.verbose("merge url: %s", url)
|
||||
count += 1
|
||||
b, mime = await self.bytes_download(str(url))
|
||||
if sys.getsizeof(b) == 215:
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
# https://github.com/rickyhan/macintoshplus
|
||||
"""Vaporwaveは音楽のジャンルや芸術運動である[3] [4]このようなバウンスハウス、またはchillwave、そして、より広く、エレクトロニックダンスミュージック、などのインディーseapunkから2010年代初頭のダンスのジャンルに出現した。 、その態度やメッセージに多くの多様性と曖昧さ、vaporwaveがありますが:時々の両方が、大量消費社会の批判とパロディとして機能し80年代のヤッピー文化、[5]とニューエイジの音楽、音響的および審美的に彼らのノスタルジックで好奇心の魅力を紹介しながら、アーティファクト。"""
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
from math import cos, sin, tan
|
||||
from random import Random, choice, randint
|
||||
|
||||
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont
|
||||
from red_commons.logging import getLogger
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.NotSoBot.macintoshplus")
|
||||
log = getLogger("red.trusty-cogs.NotSoBot.macintoshplus")
|
||||
|
||||
|
||||
japanese_corpus = """それは20年前の今日だった
|
||||
@@ -123,7 +123,7 @@ def draw_text(txt, image, k=0, x=0, y=30):
|
||||
|
||||
def insert_bubble(foreground_path, im):
|
||||
"""insert notification bubble on the bottom right corner"""
|
||||
log.debug("adding bubble:", foreground_path)
|
||||
log.verbose("adding bubble: %s", foreground_path)
|
||||
foreground = Image.open(foreground_path)
|
||||
background_size = im.size
|
||||
foreground_size = foreground.size
|
||||
@@ -137,7 +137,7 @@ def insert_bubble(foreground_path, im):
|
||||
|
||||
def insert_window_as_background(foreground_path, im, k=0):
|
||||
"""fractal generative art, not a great idea for vaporwave though. not ironic enough"""
|
||||
log.debug("adding window:", foreground_path)
|
||||
log.verbose("adding window: %s", foreground_path)
|
||||
foreground = Image.open(foreground_path)
|
||||
background_size = im.size
|
||||
foreground_size = foreground.size
|
||||
@@ -156,7 +156,7 @@ def insert_window_as_background(foreground_path, im, k=0):
|
||||
|
||||
def insert_cascade(foreground_path, im, k=0, x=100, y=100):
|
||||
"""another postironic function. raster box drawing"""
|
||||
log.debug("adding window:", foreground_path)
|
||||
log.verbose("adding window: %s", foreground_path)
|
||||
foreground = Image.open(foreground_path)
|
||||
background_size = im.size
|
||||
foreground_size = foreground.size
|
||||
@@ -165,7 +165,7 @@ def insert_cascade(foreground_path, im, k=0, x=100, y=100):
|
||||
v = 0.0
|
||||
dy = 0.0
|
||||
for i in range(int(k * 100)): # the step determines the distances between
|
||||
dy = v * i + 0.5 * acc * (i ** 2)
|
||||
dy = v * i + 0.5 * acc * (i**2)
|
||||
v = v + acc * i
|
||||
pos = (int(x + 11 * i), int(y - dy))
|
||||
im.paste(foreground, pos)
|
||||
@@ -178,7 +178,7 @@ def insert_cascade(foreground_path, im, k=0, x=100, y=100):
|
||||
|
||||
def insert_window_as_background2(foreground_path, im):
|
||||
"""another postironic function. raster box drawing"""
|
||||
log.debug("adding window:", foreground_path)
|
||||
log.verbose("adding window: %s", foreground_path)
|
||||
foreground = Image.open(foreground_path)
|
||||
background_size = im.size
|
||||
foreground_size = foreground.size
|
||||
@@ -203,7 +203,7 @@ def horizon(background_path, im):
|
||||
def insert_pic(foreground_path, im, k=0, x=0, y=1000):
|
||||
"""add Vaporwaveは音楽のジャンルや芸術運動である style pic. k is for nuanced
|
||||
transformations such as rotation and oscillation"""
|
||||
log.debug("adding pic:", foreground_path)
|
||||
log.verbose("adding pic: %s", foreground_path)
|
||||
|
||||
foreground = Image.open(foreground_path)
|
||||
background_size = im.size
|
||||
|
||||
+4
-4
@@ -1,4 +1,3 @@
|
||||
import logging
|
||||
import re
|
||||
from typing import Dict, Optional, Union
|
||||
|
||||
@@ -7,6 +6,7 @@ import discord
|
||||
from apraw.models import Submission, Subreddit
|
||||
from discord.ext.commands.converter import Converter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
|
||||
@@ -16,7 +16,7 @@ SELF_POST_SCRUB = re.compile(r"^(​[\s\n]+)(https?://.+)$")
|
||||
|
||||
REDDIT_RE = re.compile(r"\/?r\/([a-zA-Z0-9_]+)")
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.reddit")
|
||||
log = getLogger("red.Trusty-cogs.reddit")
|
||||
|
||||
_ = Translator("Reddit", __file__)
|
||||
|
||||
@@ -111,12 +111,12 @@ async def make_embed_from_submission(
|
||||
if data["e"] == "RedditVideo":
|
||||
continue
|
||||
if data["e"] == "Image":
|
||||
log.debug(data)
|
||||
log.verbose("make_embed_from_submission Image data: %s", data)
|
||||
has_image = True
|
||||
em.set_image(url=data["s"]["u"])
|
||||
break
|
||||
if data["e"] == "AnimatedImage":
|
||||
log.debug(data)
|
||||
log.verbose("make_embed_from_submission AnimatedImage data: %s", data)
|
||||
has_image = True
|
||||
em.set_image(url=data["s"]["gif"])
|
||||
break
|
||||
|
||||
+4
-3
@@ -1,16 +1,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, AsyncGenerator, Optional
|
||||
|
||||
import discord
|
||||
from apraw.models import Submission, Subreddit
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.vendored.discord.ext import menus
|
||||
|
||||
from .helpers import make_embed_from_submission
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.reddit")
|
||||
log = getLogger("red.Trusty-cogs.reddit")
|
||||
|
||||
_ = Translator("Reddit", __file__)
|
||||
|
||||
@@ -172,7 +173,7 @@ class BaseMenu(discord.ui.View):
|
||||
return self.message
|
||||
|
||||
async def show_page(self, page_number):
|
||||
log.info(page_number)
|
||||
log.verbose("BaseMenu page_number %s", page_number)
|
||||
page = await self._source.get_page(page_number)
|
||||
self.current_page = page_number
|
||||
kwargs = await self._get_kwargs_from_page(page)
|
||||
|
||||
+4
-4
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Mapping, Optional
|
||||
|
||||
import aiohttp
|
||||
@@ -7,6 +6,7 @@ import apraw
|
||||
import discord
|
||||
from apraw.models import Submission, Subreddit
|
||||
from discord.ext import tasks
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, checks, commands
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils import bounded_gather
|
||||
@@ -14,7 +14,7 @@ from redbot.core.utils import bounded_gather
|
||||
from .helpers import SubredditConverter, make_embed_from_submission
|
||||
from .menus import BaseMenu, RedditMenu
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.reddit")
|
||||
log = getLogger("red.Trusty-cogs.reddit")
|
||||
_ = Translator("Reddit", __file__)
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ class Reddit(commands.Cog):
|
||||
try:
|
||||
stream.cancel()
|
||||
except Exception:
|
||||
log.debug(f"Error closing stream in {name}")
|
||||
log.debug("Error closing stream in %s", name)
|
||||
await self.initialize()
|
||||
self.stream_loop.restart()
|
||||
|
||||
@@ -205,7 +205,7 @@ class Reddit(commands.Cog):
|
||||
try:
|
||||
stream.cancel()
|
||||
except Exception:
|
||||
log.debug(f"Error closing stream in {name}")
|
||||
log.debug("Error closing stream in %s", name)
|
||||
|
||||
@commands.group()
|
||||
async def redditset(self, ctx: commands.Context) -> None:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Dict, List, Optional, Pattern, Tuple, Union
|
||||
@@ -7,12 +6,13 @@ from typing import Dict, List, Optional, Pattern, Tuple, Union
|
||||
import discord
|
||||
from discord.ext.commands.converter import Converter, IDConverter, RoleConverter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.menus import start_adding_reactions
|
||||
from redbot.core.utils.predicates import ReactionPredicate
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.ReTrigger")
|
||||
log = getLogger("red.trusty-cogs.ReTrigger")
|
||||
_ = Translator("ReTrigger", __file__)
|
||||
|
||||
try:
|
||||
@@ -141,7 +141,7 @@ class MultiResponse(Converter):
|
||||
result = []
|
||||
match = re.split(r"(;)", argument)
|
||||
|
||||
log.debug(match)
|
||||
log.verbose("MultiResponse match: %s", match)
|
||||
my_perms = ctx.channel.permissions_for(ctx.me)
|
||||
if match[0].lower() not in MULTI_RESPONSES:
|
||||
raise BadArgument(
|
||||
@@ -199,7 +199,7 @@ class MultiResponse(Converter):
|
||||
if role < ctx.guild.me.top_role and author_perms(ctx, role):
|
||||
good_roles.append(role.id)
|
||||
except BadArgument:
|
||||
log.error("Role `{}` not found.".format(r))
|
||||
log.error("Role `%s` not found.", r)
|
||||
result = [result[0]]
|
||||
for r_id in good_roles:
|
||||
result.append(r_id)
|
||||
@@ -210,8 +210,8 @@ class MultiResponse(Converter):
|
||||
emoji = await ValidEmoji().convert(ctx, r)
|
||||
good_emojis.append(emoji)
|
||||
except BadArgument:
|
||||
log.error("Emoji `{}` not found.".format(r))
|
||||
log.debug(good_emojis)
|
||||
log.error("Emoji `%s` not found.", r)
|
||||
log.verbose("MultiResponse good_emojis: %s", good_emojis)
|
||||
result = [result[0]] + good_emojis
|
||||
return result
|
||||
|
||||
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import discord
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.commands import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import box, humanize_list, pagify
|
||||
@@ -17,7 +17,7 @@ try:
|
||||
except ImportError:
|
||||
import re
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.retrigger")
|
||||
log = getLogger("red.Trusty-cogs.retrigger")
|
||||
_ = Translator("ReTrigger", __file__)
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from abc import ABC
|
||||
from multiprocessing.pool import Pool
|
||||
from pathlib import Path
|
||||
@@ -7,6 +6,7 @@ from typing import Dict, Optional, Union
|
||||
|
||||
import discord
|
||||
from discord.ext import tasks
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, checks, commands, modlog
|
||||
from redbot.core.commands import TimedeltaConverter
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
@@ -30,7 +30,7 @@ from .menus import BaseMenu, ExplainReTriggerPages, ReTriggerMenu, ReTriggerPage
|
||||
from .slash import ReTriggerSlash
|
||||
from .triggerhandler import TriggerHandler
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.ReTrigger")
|
||||
log = getLogger("red.trusty-cogs.ReTrigger")
|
||||
_ = Translator("ReTrigger", __file__)
|
||||
|
||||
try:
|
||||
@@ -232,8 +232,8 @@ class ReTrigger(
|
||||
discord.PartialEmoji.from_str(e.strip()) for e in option["value"].split(" ")
|
||||
]
|
||||
good_emojis = []
|
||||
log.debug(option["value"])
|
||||
log.debug(list_emojis)
|
||||
log.verbose("ReTrigger _find_good_emojis value: %s", option["value"])
|
||||
log.verbose("ReTrigger _find_good_emojis list_emojis: %s", list_emojis)
|
||||
if any([e.is_unicode_emoji() for e in list_emojis]):
|
||||
await interaction.response.send_message(
|
||||
"Some emojis were not found, attempting to find unicode emojis."
|
||||
@@ -1326,7 +1326,7 @@ class ReTrigger(
|
||||
See `[p]retrigger explain` or click the link below for more details.
|
||||
[For more details click here.](https://github.com/TrustyJAID/Trusty-cogs/blob/master/retrigger/README.md)
|
||||
"""
|
||||
log.debug(trigger)
|
||||
log.debug("disable_trigger trigger: %s", trigger)
|
||||
if type(trigger) is str:
|
||||
return await self._no_trigger(ctx, trigger)
|
||||
trigger.enabled = False
|
||||
|
||||
+2
-3
@@ -1,11 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from typing import TYPE_CHECKING, Literal, Optional
|
||||
|
||||
import discord
|
||||
from discord import app_commands
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config
|
||||
from redbot.core.i18n import Translator
|
||||
|
||||
@@ -19,7 +19,7 @@ except ImportError:
|
||||
from .converters import Trigger
|
||||
|
||||
_ = Translator("ReTrigger", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.ReTrigger")
|
||||
log = getLogger("red.trusty-cogs.ReTrigger")
|
||||
|
||||
|
||||
class PartialEmojiTransformer(app_commands.Transformer):
|
||||
@@ -75,7 +75,6 @@ class TriggerTransformer(app_commands.Transformer):
|
||||
|
||||
|
||||
class ReTriggerSlash(ReTriggerMixin):
|
||||
|
||||
modlog = app_commands.Group(
|
||||
name="modlog", description="Set which events to record in the modlog."
|
||||
)
|
||||
|
||||
+35
-19
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
import functools
|
||||
import logging
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import random
|
||||
@@ -12,6 +11,7 @@ from typing import Any, Dict, List, Literal, Optional, Pattern, Tuple, cast
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands, modlog
|
||||
from redbot.core.data_manager import cog_data_path
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -43,7 +43,7 @@ except ImportError:
|
||||
import re
|
||||
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.ReTrigger")
|
||||
log = getLogger("red.trusty-cogs.ReTrigger")
|
||||
_ = Translator("ReTrigger", __file__)
|
||||
|
||||
RE_CTX: Pattern = re.compile(r"{([^}]+)\}")
|
||||
@@ -237,7 +237,7 @@ class TriggerHandler(ReTriggerMixin):
|
||||
if await self.bot.cog_disabled_in_guild(self, message.guild):
|
||||
return
|
||||
if getattr(message, "retrigger", False):
|
||||
log.debug("A ReTrigger dispatched message, ignoring.")
|
||||
log.trace("A ReTrigger dispatched message, ignoring.")
|
||||
return
|
||||
await self.check_triggers(message, False)
|
||||
|
||||
@@ -264,7 +264,7 @@ class TriggerHandler(ReTriggerMixin):
|
||||
message = await channel.fetch_message(int(payload.data["id"]))
|
||||
except (discord.errors.Forbidden, discord.errors.NotFound):
|
||||
log.debug(
|
||||
_("I don't have permission to read channel history or cannot find the message.")
|
||||
"I don't have permission to read channel history or cannot find the message."
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
@@ -440,25 +440,43 @@ class TriggerHandler(ReTriggerMixin):
|
||||
except mp.TimeoutError:
|
||||
error_msg = (
|
||||
"ReTrigger: regex process took too long. Removing from memory "
|
||||
f"{guild.name} ({guild.id}) Author {trigger.author} "
|
||||
f"Offending regex `{trigger.regex.pattern}` Name: {trigger.name}"
|
||||
"%s (%s) Author %s "
|
||||
"Offending regex `%s` Name: %s"
|
||||
)
|
||||
log.warning(
|
||||
error_msg,
|
||||
guild.name,
|
||||
guild.id,
|
||||
trigger.author,
|
||||
trigger.regex.pattern,
|
||||
trigger.name,
|
||||
)
|
||||
log.warning(error_msg)
|
||||
return (False, [])
|
||||
# we certainly don't want to be performing multiple triggers if this happens
|
||||
except asyncio.TimeoutError:
|
||||
error_msg = (
|
||||
"ReTrigger: regex asyncio timed out."
|
||||
f"{guild.name} ({guild.id}) Author {trigger.author} "
|
||||
f"Offending regex `{trigger.regex.pattern}` Name: {trigger.name}"
|
||||
"%s (%s) Author %s "
|
||||
"Offending regex `%s` Name: %s"
|
||||
)
|
||||
log.warning(
|
||||
error_msg,
|
||||
guild.name,
|
||||
guild.id,
|
||||
trigger.author,
|
||||
trigger.regex.pattern,
|
||||
trigger.name,
|
||||
)
|
||||
log.warning(error_msg)
|
||||
return (False, [])
|
||||
except ValueError:
|
||||
return (False, [])
|
||||
except Exception:
|
||||
log.error(
|
||||
f"ReTrigger encountered an error {trigger.name} {trigger.regex} in {guild.name} {guild.id}",
|
||||
"ReTrigger encountered an error %s %s in %s %s",
|
||||
trigger.name,
|
||||
trigger.regex,
|
||||
guild.name,
|
||||
guild.id,
|
||||
exc_info=True,
|
||||
)
|
||||
return (True, [])
|
||||
@@ -810,9 +828,9 @@ class TriggerHandler(ReTriggerMixin):
|
||||
if await self.config.guild(guild).ban_logs():
|
||||
await self.modlog_action(message, trigger, find, _("Banned"))
|
||||
except discord.errors.Forbidden:
|
||||
log.debug(error_in, exc_info=True)
|
||||
log.debug("Discord forbidden error when banning %s", author, exc_info=True)
|
||||
except Exception:
|
||||
log.error(error_in, exc_info=True)
|
||||
log.error("Exception when banning %s", author, exc_info=True)
|
||||
|
||||
if TriggerResponse.command in trigger.response_type:
|
||||
if trigger.multi_payload:
|
||||
@@ -1031,19 +1049,17 @@ class TriggerHandler(ReTriggerMixin):
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
msg = _("Error deleting saved image in {guild}").format(
|
||||
guild=guild_id
|
||||
log.error(
|
||||
"Error deleting saved image in %s", guild_id, exc_info=True
|
||||
)
|
||||
log.error(msg, exc_info=True)
|
||||
else:
|
||||
path = str(cog_data_path(self)) + f"/{guild_id}/{image}"
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
msg = _("Error deleting saved image in {guild}").format(
|
||||
guild=guild_id
|
||||
log.error(
|
||||
"Error deleting saved image in %s", guild_id, exc_info=True
|
||||
)
|
||||
log.error(msg, exc_info=True)
|
||||
del trigger_list[triggers]
|
||||
del self.triggers[guild_id][trigger_name]
|
||||
return True
|
||||
|
||||
+2
-2
@@ -1,11 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.commands import Context
|
||||
@@ -24,7 +24,7 @@ if TYPE_CHECKING:
|
||||
from .select import SelectOptionRoleConverter, SelectRoleConverter
|
||||
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.ReTrigger")
|
||||
log = getLogger("red.trusty-cogs.ReTrigger")
|
||||
_ = Translator("Roletools", __file__)
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.commands import Context
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -15,7 +15,7 @@ from .menus import BaseMenu, ButtonRolePages
|
||||
|
||||
roletools = RoleToolsMixin.roletools
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
_ = Translator("RoleTools", __file__)
|
||||
|
||||
|
||||
@@ -189,8 +189,7 @@ class RoleToolsButtons(RoleToolsMixin):
|
||||
async def initialize_buttons(self):
|
||||
for guild_id, settings in self.settings.items():
|
||||
for button_name, button_data in settings["buttons"].items():
|
||||
log.debug(f"Adding Button {button_name}")
|
||||
|
||||
log.verbose("Adding Button %s", button_name)
|
||||
role_id = button_data["role_id"]
|
||||
emoji = button_data["emoji"]
|
||||
if emoji is not None:
|
||||
|
||||
+19
-15
@@ -1,15 +1,15 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import bank, commands
|
||||
from redbot.core.i18n import Translator
|
||||
|
||||
from .abc import RoleToolsMixin
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
|
||||
_ = Translator("Roletools", __file__)
|
||||
|
||||
@@ -59,11 +59,11 @@ class RoleToolsEvents(RoleToolsMixin):
|
||||
if member.bot:
|
||||
return
|
||||
if await self.check_guild_verification(member, guild):
|
||||
log.debug("Ignoring user due to verification check.")
|
||||
log.debug("Ignoring user (%s) due to verification check.", member.id)
|
||||
return
|
||||
if getattr(member, "pending", False):
|
||||
return
|
||||
log.debug(f"Adding role to {member.name} in {member.guild}")
|
||||
log.debug("Adding role to %s in %s", member.name, member.guild)
|
||||
await self.give_roles(member, [role], _("Reaction Role"))
|
||||
|
||||
@commands.Cog.listener()
|
||||
@@ -93,7 +93,7 @@ class RoleToolsEvents(RoleToolsMixin):
|
||||
return
|
||||
if member.bot:
|
||||
return
|
||||
log.debug(f"Removing role from {member.name} in {member.guild}")
|
||||
log.debug("Removing role from %s in %s", member.name, member.guild)
|
||||
await self.remove_roles(member, [role], _("Reaction Role"))
|
||||
|
||||
@commands.Cog.listener()
|
||||
@@ -148,17 +148,17 @@ class RoleToolsEvents(RoleToolsMixin):
|
||||
else timedelta(minutes=10)
|
||||
)
|
||||
if guild.verification_level.value >= 2 and allowed_discord <= timedelta(minutes=5):
|
||||
log.debug(f"Waiting 5 minutes for {member.name} in {guild}")
|
||||
log.debug("Waiting 5 minutes for %s in %s", member.name, guild)
|
||||
return 300 - int(allowed_discord.total_seconds())
|
||||
elif guild.verification_level.value >= 3 and allowed_server <= timedelta(minutes=10):
|
||||
log.debug(f"Waiting 10 minutes for {member.name} in {guild}")
|
||||
log.debug("Waiting 10 minutes for %s in %s", member.name, guild)
|
||||
return 600 - int(allowed_server.total_seconds())
|
||||
return False
|
||||
|
||||
async def wait_for_verification(self, member: discord.Member, guild: discord.Guild) -> None:
|
||||
wait = await self.check_guild_verification(member, guild)
|
||||
if wait:
|
||||
log.debug(f"Waiting {wait} seconds before allowing the user to have a role")
|
||||
log.debug("Waiting %s seconds before allowing the user to have a role", wait)
|
||||
await asyncio.sleep(int(wait))
|
||||
|
||||
async def check_atomicity(self, guild: discord.Guild) -> bool:
|
||||
@@ -330,7 +330,9 @@ class RoleToolsEvents(RoleToolsMixin):
|
||||
await bank.withdraw_credits(member, cost)
|
||||
except Exception:
|
||||
log.info(
|
||||
f"Could not assign {role} to {member} as they don't have enough credits."
|
||||
"Could not assign %s to %s as they don't have enough credits.",
|
||||
role,
|
||||
member,
|
||||
)
|
||||
ret.append(
|
||||
RoleChangeResponse(role, _("You do not have enough credits."), False)
|
||||
@@ -338,7 +340,9 @@ class RoleToolsEvents(RoleToolsMixin):
|
||||
continue
|
||||
else:
|
||||
log.info(
|
||||
f"Could not assign {role} to {member} as they don't have enough credits."
|
||||
"Could not assign %s to %s as they don't have enough credits.",
|
||||
role,
|
||||
member,
|
||||
)
|
||||
ret.append(
|
||||
RoleChangeResponse(role, _("You do not have enough credits."), False)
|
||||
@@ -347,7 +351,7 @@ class RoleToolsEvents(RoleToolsMixin):
|
||||
if (inclusive := await self.config.role(role).inclusive_with()) and check_inclusive:
|
||||
inclusive_roles = []
|
||||
for role_id in inclusive:
|
||||
log.debug(role_id)
|
||||
log.verbose("role_id: %s", role_id)
|
||||
r = guild.get_role(role_id)
|
||||
if r is None:
|
||||
async with self.config.role(role).inclusive_with() as inclusive_with:
|
||||
@@ -391,12 +395,12 @@ class RoleToolsEvents(RoleToolsMixin):
|
||||
if atomic:
|
||||
await member.remove_roles(*exclusive_roles, reason=_("Exclusive Roles"))
|
||||
to_add.add(role)
|
||||
log.debug(f"Adding {to_add} to {member.name}")
|
||||
log.debug("Adding %s to %s", to_add, member.name)
|
||||
if atomic:
|
||||
log.debug("Atomic is true")
|
||||
log.verbose("Atomic is true")
|
||||
await member.add_roles(*list(to_add), reason=reason)
|
||||
else:
|
||||
log.debug("Atomic is false")
|
||||
log.verbose("Atomic is false")
|
||||
await member.edit(roles=list(to_add), reason=reason)
|
||||
return ret
|
||||
|
||||
@@ -486,7 +490,7 @@ class RoleToolsEvents(RoleToolsMixin):
|
||||
to_rem.add(role)
|
||||
else:
|
||||
to_rem.remove(role)
|
||||
log.debug(f"{to_rem}")
|
||||
log.verbose("remove_roles to_rem: %s", to_rem)
|
||||
if atomic:
|
||||
await member.remove_roles(*list(to_rem), reason=reason)
|
||||
else:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import logging
|
||||
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.commands import Context
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -10,7 +9,7 @@ from .converter import RoleHierarchyConverter
|
||||
|
||||
roletools = RoleToolsMixin.roletools
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
_ = Translator("RoleTools", __file__)
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import logging
|
||||
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.commands import Context
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -10,7 +9,7 @@ from .converter import RoleHierarchyConverter
|
||||
|
||||
roletools = RoleToolsMixin.roletools
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
_ = Translator("RoleTools", __file__)
|
||||
|
||||
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
|
||||
# from discord.ext.commands.errors import BadArgument
|
||||
from redbot.core import bank
|
||||
@@ -12,7 +12,7 @@ from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list, pagify
|
||||
from redbot.vendored.discord.ext import menus
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
_ = Translator("RoleTools", __file__)
|
||||
|
||||
|
||||
@@ -384,7 +384,7 @@ class RolePages(menus.ListPageSource):
|
||||
else:
|
||||
cdn_fmt = " https://cdnjs.cloudflare.com/ajax/libs/twemoji/14.0.2/72x72/{codepoint:x}.png"
|
||||
url = cdn_fmt.format(codepoint=ord(str(role.display_icon)))
|
||||
log.debug(role.display_icon)
|
||||
log.verbose("RolePages role.display_icon: %s", role.display_icon)
|
||||
em.set_thumbnail(url=url)
|
||||
em.set_footer(text=f"Page {menu.current_page + 1}/{self.get_max_pages()}")
|
||||
return em
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.commands import Context
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -13,7 +12,7 @@ from .select import SelectRoleConverter, SelectRoleView
|
||||
|
||||
roletools = RoleToolsMixin.roletools
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
_ = Translator("RoleTools", __file__)
|
||||
|
||||
|
||||
@@ -240,7 +239,7 @@ class RoleToolsMessages(RoleToolsMixin):
|
||||
if not await self.check_totals(ctx, buttons=len(buttons), menus=0):
|
||||
return
|
||||
new_view = ButtonRoleView(self)
|
||||
log.info(buttons)
|
||||
log.verbose("send_buttons buttons: %s", buttons)
|
||||
for button in buttons:
|
||||
new_view.add_item(button)
|
||||
msg = await channel.send(content=message, view=new_view)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.commands import Context
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -16,7 +16,7 @@ from .menus import BaseMenu, ReactRolePages
|
||||
|
||||
roletools = RoleToolsMixin.roletools
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
_ = Translator("RoleTools", __file__)
|
||||
|
||||
|
||||
@@ -401,7 +401,7 @@ class RoleToolsReactions(RoleToolsMixin):
|
||||
send_to_react = False
|
||||
async with self.config.guild(ctx.guild).reaction_roles() as cur_setting:
|
||||
for role, emoji in role_emoji:
|
||||
log.debug(type(emoji))
|
||||
log.verbose("bulkreact emoji: %s", type(emoji))
|
||||
if isinstance(emoji, discord.PartialEmoji):
|
||||
use_emoji = str(emoji.id)
|
||||
else:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import logging
|
||||
from typing import Union
|
||||
|
||||
from discord import Interaction
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.commands import Context
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -12,7 +12,7 @@ from .converter import RoleHierarchyConverter
|
||||
|
||||
roletools = RoleToolsMixin.roletools
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
_ = Translator("RoleTools", __file__)
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from abc import ABC
|
||||
from typing import Any, Dict, Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, bank, commands
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.commands import Context
|
||||
@@ -26,7 +26,7 @@ from .settings import RoleToolsSettings
|
||||
|
||||
roletools = RoleToolsMixin.roletools
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
_ = Translator("RoleTools", __file__)
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ def custom_cooldown(ctx: commands.Context) -> Optional[discord.app_commands.Cool
|
||||
members = []
|
||||
|
||||
for entity in who:
|
||||
log.debug(entity)
|
||||
log.verbose("custom_cooldown entity: %s", entity)
|
||||
if isinstance(entity, discord.TextChannel) or isinstance(entity, discord.Role):
|
||||
members += entity.members
|
||||
elif isinstance(entity, discord.Member):
|
||||
@@ -190,7 +190,7 @@ class RoleTools(
|
||||
async def cog_unload(self):
|
||||
for view in self.views:
|
||||
# Don't forget to remove persistent views when the cog is unloaded.
|
||||
log.debug(f"Stopping view {view}")
|
||||
log.verbose("Stopping view %s", view)
|
||||
view.stop()
|
||||
|
||||
@roletools.group(invoke_without_command=True)
|
||||
|
||||
+3
-3
@@ -1,10 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, List, Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.commands import Context
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -16,7 +16,7 @@ from .menus import BaseMenu, SelectMenuPages, SelectOptionPages
|
||||
|
||||
roletools = RoleToolsMixin.roletools
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
_ = Translator("RoleTools", __file__)
|
||||
|
||||
|
||||
@@ -319,7 +319,7 @@ class RoleToolsSelect(RoleToolsMixin):
|
||||
async def initialize_select(self) -> None:
|
||||
for guild_id, settings in self.settings.items():
|
||||
for select_name, select_data in settings["select_menus"].items():
|
||||
log.debug(f"Adding Option {select_name}")
|
||||
log.verbose("Adding Option %s", select_name)
|
||||
options = []
|
||||
disabled = []
|
||||
for option_name in select_data["options"]:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
from typing import Optional, Union
|
||||
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import bank, commands
|
||||
from redbot.core.commands import Context
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -10,7 +10,7 @@ from .converter import RoleHierarchyConverter
|
||||
|
||||
roletools = RoleToolsMixin.roletools
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.RoleTools")
|
||||
log = getLogger("red.Trusty-cogs.RoleTools")
|
||||
_ = Translator("RoleTools", __file__)
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
@@ -11,12 +10,13 @@ from typing import List, NamedTuple, Optional, Tuple, Union
|
||||
import aiohttp
|
||||
import discord
|
||||
import pytz
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.utils.chat_formatting import humanize_number, pagify
|
||||
from tabulate import tabulate
|
||||
|
||||
HEADERS = {"User-Agent": f"Red-DiscordBot Trusty-cogs Runescape Cog"}
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.runescape")
|
||||
log = getLogger("red.trusty-cogs.runescape")
|
||||
|
||||
|
||||
class APIError(Exception):
|
||||
@@ -643,7 +643,7 @@ class OSRSProfile:
|
||||
@classmethod
|
||||
def from_str(cls, rsn: str, data: str) -> OSRSProfile:
|
||||
data = data.replace(" ", "\n")
|
||||
log.info(data)
|
||||
log.verbose("OSRSProfile from_str: %s", data)
|
||||
final_data: List[Union[str, OSRSRank]] = [rsn, data]
|
||||
for line_no, ranks in enumerate(data.split("\n")):
|
||||
if line_no >= len(cls._ORDER):
|
||||
@@ -705,10 +705,9 @@ class OSRSProfile:
|
||||
activities_list = []
|
||||
data = data.replace(" ", "\n")
|
||||
for line, ranks in enumerate(data.split("\n")):
|
||||
|
||||
if line >= len(OSRSProfile._ORDER):
|
||||
continue
|
||||
log.info(OSRSProfile._ORDER[line])
|
||||
log.verbose("OSRSProfile table_from_text: %s", OSRSProfile._ORDER[line])
|
||||
rank = [int(i) for i in ranks.split(",")]
|
||||
if len(rank) == 3:
|
||||
skills_list.append(
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, Literal, Optional
|
||||
@@ -6,6 +5,7 @@ from typing import Dict, Literal, Optional
|
||||
import aiohttp
|
||||
import discord
|
||||
from discord.ext import tasks
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.utils.chat_formatting import bold, box, humanize_list, humanize_number
|
||||
@@ -20,7 +20,7 @@ from .profile import (
|
||||
Profile,
|
||||
)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.runescape")
|
||||
log = getLogger("red.trusty-cogs.runescape")
|
||||
|
||||
IMAGE_URL = "https://runescape.wiki/w/Special:FilePath/"
|
||||
|
||||
@@ -297,7 +297,7 @@ class Runescape(commands.Cog):
|
||||
if not data.get("success", True):
|
||||
await ctx.send(error_msg)
|
||||
return
|
||||
log.debug(data)
|
||||
log.trace("runescape_ge data: %s", data)
|
||||
embed = discord.Embed(
|
||||
title=f"Runescape GE Results for `{search}`", colour=await ctx.embed_colour()
|
||||
)
|
||||
@@ -365,7 +365,7 @@ class Runescape(commands.Cog):
|
||||
if not data.get("success", True):
|
||||
await ctx.send(error_msg)
|
||||
return
|
||||
log.debug(data)
|
||||
log.trace("osrs_ge data: %s", data)
|
||||
embed = discord.Embed(
|
||||
title=f"OldSchool Runescape GE Results for `{search}`",
|
||||
colour=await ctx.embed_colour(),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import logging
|
||||
import re
|
||||
from typing import List, Union
|
||||
|
||||
@@ -6,12 +5,13 @@ import discord
|
||||
from discord.ext.commands.converter import IDConverter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from rapidfuzz import process
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from unidecode import unidecode
|
||||
|
||||
_ = Translator("ServerStats", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.ServerStats")
|
||||
log = getLogger("red.trusty-cogs.ServerStats")
|
||||
|
||||
|
||||
class GuildConverter(discord.app_commands.Transformer):
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, List, Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.vendored.discord.ext import menus
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.serverstats")
|
||||
log = getLogger("red.Trusty-cogs.serverstats")
|
||||
|
||||
_ = Translator("serverstats", __file__)
|
||||
|
||||
|
||||
+10
-11
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from copy import copy
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from io import BytesIO
|
||||
@@ -7,6 +6,7 @@ from typing import Dict, List, Literal, Optional, Tuple, Union, cast
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot import VersionInfo, version_info
|
||||
from redbot.core import Config, checks, commands
|
||||
from redbot.core.bot import Red
|
||||
@@ -28,7 +28,7 @@ from .converters import GuildConverter, MultiGuildConverter, PermissionConverter
|
||||
from .menus import AvatarPages, BaseView, GuildPages, ListPages
|
||||
|
||||
_ = Translator("ServerStats", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.ServerStats")
|
||||
log = getLogger("red.trusty-cogs.ServerStats")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
@@ -121,7 +121,7 @@ class ServerStats(commands.GroupCog):
|
||||
em.description = created_at
|
||||
await channel.send(embed=em)
|
||||
except Exception:
|
||||
log.error(f"Error creating guild embed for new guild ID {guild.id}", exc_info=True)
|
||||
log.error("Error creating guild embed for new guild ID %s", guild.id, exc_info=True)
|
||||
|
||||
async def guild_embed(self, guild: discord.Guild) -> discord.Embed:
|
||||
"""
|
||||
@@ -338,7 +338,7 @@ class ServerStats(commands.GroupCog):
|
||||
em.description = created_at
|
||||
await channel.send(embed=em)
|
||||
except Exception:
|
||||
log.error(f"Error creating guild embed for old guild ID {guild.id}", exc_info=True)
|
||||
log.error("Error creating guild embed for old guild ID %s", guild.id, exc_info=True)
|
||||
|
||||
@commands.hybrid_command()
|
||||
async def emoji(self, ctx: commands.Context, emoji: str) -> None:
|
||||
@@ -766,7 +766,6 @@ class ServerStats(commands.GroupCog):
|
||||
count += 1
|
||||
msg_list.append(em)
|
||||
else:
|
||||
|
||||
if not role:
|
||||
estimate = await ctx.guild.estimate_pruned_members(days=days)
|
||||
role_msg = _("Discord Estimate: {estimate}").format(estimate=estimate)
|
||||
@@ -1357,9 +1356,9 @@ class ServerStats(commands.GroupCog):
|
||||
await guild.leave()
|
||||
except Exception:
|
||||
log.error(
|
||||
_("I couldn't leave {guild} ({g_id}).").format(
|
||||
guild=guild.name, g_id=guild.id
|
||||
),
|
||||
"I couldn't leave %s (%s).",
|
||||
guild.name,
|
||||
guild.id,
|
||||
exc_info=True,
|
||||
)
|
||||
await ctx.send(_("I couldn't leave {guild}.").format(guild=guild.name))
|
||||
@@ -1585,12 +1584,12 @@ class ServerStats(commands.GroupCog):
|
||||
if not my_perms.read_message_history or not my_perms.read_messages:
|
||||
continue
|
||||
try:
|
||||
log.debug(check_after)
|
||||
log.verbose("get_server_stats check_after: %s", check_after)
|
||||
async for message in channel.history(
|
||||
limit=None, after=check_after, oldest_first=False
|
||||
):
|
||||
if not set_new_last_read:
|
||||
log.debug(f"Setting last_checked to {message.id}")
|
||||
log.debug("Setting last_checked to %s", message.id)
|
||||
to_return["channels"][str(channel.id)]["last_checked"] = message.id
|
||||
set_new_last_read = True
|
||||
author = message.author
|
||||
@@ -1610,7 +1609,7 @@ class ServerStats(commands.GroupCog):
|
||||
pass
|
||||
_ret = copy(to_return)
|
||||
# copy the data to prevent context manager from removing the reference
|
||||
log.debug(_ret)
|
||||
log.verbose("get_server_stats _ret: %s", _ret)
|
||||
return _ret
|
||||
|
||||
async def get_channel_stats(self, channel: discord.TextChannel) -> dict:
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
|
||||
import discord
|
||||
import tekore
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
@@ -13,7 +13,7 @@ from redbot.vendored.discord.ext import menus
|
||||
|
||||
from .helpers import spotify_emoji_handler
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.spotify")
|
||||
log = getLogger("red.Trusty-cogs.spotify")
|
||||
_ = Translator("Spotify", __file__)
|
||||
|
||||
|
||||
@@ -673,7 +673,7 @@ class StopButton(discord.ui.Button):
|
||||
async def callback(self, interaction: discord.Interaction):
|
||||
log.debug("deleting message")
|
||||
self.view.stop()
|
||||
log.debug(interaction.message.flags)
|
||||
log.verbose("StopButton flags: %s", interaction.message.flags)
|
||||
if interaction.message.flags.ephemeral:
|
||||
await interaction.response.edit_message(view=None)
|
||||
return
|
||||
|
||||
+2
-2
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import re
|
||||
from copy import copy
|
||||
from enum import Enum
|
||||
@@ -11,12 +10,13 @@ import discord
|
||||
import tekore
|
||||
from discord.ext.commands.converter import Converter
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list, humanize_timedelta
|
||||
from tabulate import tabulate
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.spotify")
|
||||
log = getLogger("red.trusty-cogs.spotify")
|
||||
|
||||
SPOTIFY_RE = re.compile(
|
||||
r"(https?:\/\/open\.spotify\.com\/|spotify:?)"
|
||||
|
||||
+9
-5
@@ -1,11 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Any, List, Optional, Tuple
|
||||
|
||||
import discord
|
||||
import tekore
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import box, humanize_list
|
||||
@@ -40,7 +40,7 @@ from .helpers import (
|
||||
spotify_emoji_handler,
|
||||
)
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.spotify")
|
||||
log = getLogger("red.Trusty-cogs.spotify")
|
||||
_ = Translator("Spotify", __file__)
|
||||
|
||||
|
||||
@@ -539,7 +539,6 @@ class SpotifyPages(menus.PageSource):
|
||||
view: discord.ui.View,
|
||||
cur_state: Tuple[tekore.model.CurrentlyPlayingContext, bool],
|
||||
) -> discord.Embed:
|
||||
|
||||
state = cur_state[0]
|
||||
is_liked = cur_state[1]
|
||||
self.context = state.context
|
||||
@@ -872,7 +871,12 @@ class SpotifyUserMenu(discord.ui.View):
|
||||
pass
|
||||
|
||||
async def on_error(self, error, interaction: discord.Interaction, button: discord.ui.Button):
|
||||
log.debug(f"{error=} {button=} {interaction=}")
|
||||
log.verbose(
|
||||
"SpotifyUserMenu on_error: error=%s button=%s interaction=%s",
|
||||
error,
|
||||
button,
|
||||
interaction,
|
||||
)
|
||||
|
||||
async def interaction_check(self, interaction: discord.Interaction):
|
||||
"""Just extends the default reaction_check to use owner_ids"""
|
||||
@@ -980,7 +984,7 @@ class SpotifySearchMenu(discord.ui.View):
|
||||
self.source.select_options[page_number - 12 : page_number + 13]
|
||||
)
|
||||
self.add_item(self.select_view)
|
||||
log.debug(f"changing select {len(self.select_view.options)}")
|
||||
log.trace("changing select %s", len(self.select_view.options))
|
||||
self.current_page = page_number
|
||||
kwargs = await self._get_kwargs_from_page(page)
|
||||
if not interaction.response.is_done():
|
||||
|
||||
+3
-4
@@ -1,10 +1,9 @@
|
||||
import logging
|
||||
|
||||
from dashboard.rpc.utils import rpccheck
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.commands import commands
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.spotify")
|
||||
log = getLogger("red.trusty-cogs.spotify")
|
||||
|
||||
|
||||
class DashboardRPC_Spotify:
|
||||
@@ -29,7 +28,7 @@ class DashboardRPC_Spotify:
|
||||
return {"status": 0, "message": "Unknown user."}
|
||||
if not self.cog._credentials:
|
||||
return {"status": 0, "message": "Bot owner has not set credentials."}
|
||||
log.debug(user)
|
||||
log.verbose("DashboardRPC_Spotify user: %s", user)
|
||||
try:
|
||||
auth = self.cog.temp_cache[userobj.id]
|
||||
except KeyError:
|
||||
|
||||
+4
-4
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from abc import ABC
|
||||
@@ -8,6 +7,7 @@ from typing import Literal, Mapping, Optional, Tuple
|
||||
|
||||
import discord
|
||||
import tekore
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
@@ -23,7 +23,7 @@ try:
|
||||
except ImportError:
|
||||
DASHBOARD = False
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.spotify")
|
||||
log = getLogger("red.trusty-cogs.spotify")
|
||||
_ = Translator("Spotify", __file__)
|
||||
|
||||
|
||||
@@ -351,7 +351,7 @@ class Spotify(
|
||||
if "fields" in em_dict:
|
||||
for field in em_dict["fields"]:
|
||||
content += " " + field["name"] + " " + field["value"]
|
||||
log.debug(content)
|
||||
log.verbose("Spotify content: %s", content)
|
||||
content = content.replace("🧑🎨", ":artist:")
|
||||
# because discord will replace this in URI's automatically 🙄
|
||||
song_data = SPOTIFY_RE.finditer(content)
|
||||
@@ -498,7 +498,7 @@ class Spotify(
|
||||
query = em.title if em.title else ""
|
||||
if not query or query == "-":
|
||||
return
|
||||
log.debug(query)
|
||||
log.verbose("play_from_message query: %s", query)
|
||||
search = await user_spotify.search(query, ("track",), "from_token", limit=50)
|
||||
# log.debug(search)
|
||||
tracks = search[0].items
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import logging
|
||||
from copy import copy
|
||||
from io import BytesIO
|
||||
from typing import List, Literal, Optional, Tuple, Union
|
||||
@@ -8,6 +7,7 @@ import discord
|
||||
import tekore
|
||||
import yaml
|
||||
from discord import app_commands
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
@@ -49,7 +49,7 @@ from .menus import (
|
||||
# from redbot.core.utils.views import SetApiView
|
||||
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.spotify")
|
||||
log = getLogger("red.trusty-cogs.spotify")
|
||||
_ = Translator("Spotify", __file__)
|
||||
|
||||
ActionConverter = commands.get_dict_converter(
|
||||
@@ -768,7 +768,7 @@ class SpotifyCommands(SpotifyMixin):
|
||||
|
||||
e.g. `[p]spotify recommendations genre: edm electronic valence: 100 mode: major`
|
||||
"""
|
||||
log.info(recommendations)
|
||||
log.verbose("spotify_recommendations recommendations: %s", recommendations)
|
||||
# user_spotify = await self.get_user_spotify(ctx)
|
||||
if not any([recommendations.genres, recommendations.artists, recommendations.tracks]):
|
||||
await ctx.send(
|
||||
@@ -1235,7 +1235,7 @@ class SpotifyCommands(SpotifyMixin):
|
||||
uri_type = match.group(2)
|
||||
if match.group(2) == "track":
|
||||
tracks.append(match.group(3))
|
||||
log.debug(new_uri)
|
||||
log.verbose("spotify_play new_uri: %s", new_uri)
|
||||
try:
|
||||
user_spotify = tekore.Spotify(sender=self._sender)
|
||||
with user_spotify.token_as(user_token):
|
||||
@@ -1296,7 +1296,7 @@ class SpotifyCommands(SpotifyMixin):
|
||||
user_spotify = tekore.Spotify(sender=self._sender)
|
||||
with user_spotify.token_as(user_token):
|
||||
for uri in tracks:
|
||||
log.debug(f"Queueing {uri=}")
|
||||
log.trace("Queueing uri=%s", uri)
|
||||
await user_spotify.playback_queue_add(uri)
|
||||
all_tracks = await user_spotify.tracks(tracks)
|
||||
if ctx.interaction:
|
||||
@@ -1478,7 +1478,7 @@ class SpotifyCommands(SpotifyMixin):
|
||||
now = cur.progress_ms
|
||||
total = cur.item.duration_ms
|
||||
emoji = spotify_emoji_handler.get_emoji("fastforward", True)
|
||||
log.debug(seconds)
|
||||
log.verbose("spotify_seek seconds: %s", seconds)
|
||||
if abs_position:
|
||||
to_seek = seconds * 1000
|
||||
else:
|
||||
@@ -1587,7 +1587,7 @@ class SpotifyCommands(SpotifyMixin):
|
||||
if device_name:
|
||||
for d in devices:
|
||||
if device_name.lower() in d.name.lower() or device_name == d.id:
|
||||
log.debug(f"Transferring playback to {d.name}")
|
||||
log.debug("Transferring playback to %s", d.name)
|
||||
new_device = d
|
||||
else:
|
||||
new_view = SpotifyDeviceView(ctx)
|
||||
@@ -1658,7 +1658,7 @@ class SpotifyCommands(SpotifyMixin):
|
||||
if device_name:
|
||||
for d in devices:
|
||||
if device_name.lower() in d.name.lower() or device_name == d.id:
|
||||
log.debug(f"Transferring playback to {d.name}")
|
||||
log.debug("Transferring playback to %s", d.name)
|
||||
new_device = d
|
||||
else:
|
||||
new_view = SpotifyDeviceView(ctx)
|
||||
|
||||
+16
-10
@@ -1,10 +1,10 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Dict, List, Literal, Union, cast
|
||||
|
||||
import discord
|
||||
from discord.utils import snowflake_time
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
@@ -14,7 +14,7 @@ from redbot.core.utils.chat_formatting import humanize_timedelta
|
||||
from .starboard_entry import FakePayload, StarboardEntry, StarboardMessage
|
||||
|
||||
_ = Translator("Starboard", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.Starboard")
|
||||
log = getLogger("red.trusty-cogs.Starboard")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
@@ -364,23 +364,29 @@ class StarboardEvents:
|
||||
if snowflake_time(message.original_message) < to_purge:
|
||||
to_rem.append(message_ids)
|
||||
for m in to_rem:
|
||||
log.debug(f"Removing {m}")
|
||||
log.verbose("Removing %s", m)
|
||||
del starboard.messages[m]
|
||||
total_pruned += 1
|
||||
for m in to_rem_index:
|
||||
del starboard.starboarded_messages[m]
|
||||
if len(to_rem) > 0:
|
||||
log.info(
|
||||
f"Starboard pruned {len(to_rem)} messages that are "
|
||||
f"{humanize_timedelta(timedelta=purge)} old from "
|
||||
f"{guild.name} ({guild.id})"
|
||||
"Starboard pruned %s messages that are "
|
||||
"%s old from "
|
||||
"%s (%s)",
|
||||
len(to_rem),
|
||||
humanize_timedelta(timedelta=purge),
|
||||
guild.name,
|
||||
guild.id,
|
||||
)
|
||||
except Exception:
|
||||
log.exception("Error trying to clenaup old starboard messages.")
|
||||
await self._save_starboards(guild)
|
||||
if total_pruned:
|
||||
log.info(
|
||||
f"Starboard has pruned {total_pruned} messages and ignored {guilds_ignored} guilds."
|
||||
"Starboard has pruned %s messages and ignored %s guilds.",
|
||||
total_pruned,
|
||||
guilds_ignored,
|
||||
)
|
||||
# Sleep 1 day but also run on cog reload
|
||||
await asyncio.sleep(60 * 60 * 24)
|
||||
@@ -441,18 +447,18 @@ class StarboardEvents:
|
||||
if getattr(payload, "event_type", None) == "REACTION_ADD":
|
||||
if (user_id := getattr(payload, "user_id", 0)) not in starboard_msg.reactions:
|
||||
starboard_msg.reactions.append(user_id)
|
||||
log.debug("Adding user in _loop_messages")
|
||||
log.verbose("Adding user (%s) in _loop_messages", user_id)
|
||||
starboard.stars_added += 1
|
||||
else:
|
||||
if (user_id := getattr(payload, "user_id", 0)) in starboard_msg.reactions:
|
||||
starboard_msg.reactions.remove(user_id)
|
||||
log.debug("Removing user in _loop_messages")
|
||||
log.verbose("Removing user (%s) in _loop_messages", user_id)
|
||||
starboard.stars_added -= 1
|
||||
|
||||
if not starboard_msg.new_message or not starboard_msg.new_channel:
|
||||
return starboard_msg
|
||||
count = len(starboard_msg.reactions)
|
||||
log.debug(f"Existing {count=} {starboard.threshold=}")
|
||||
log.debug("Existing count=%s starboard.threshold=%s", count, starboard.threshold)
|
||||
if count < starboard.threshold:
|
||||
try:
|
||||
index_key = f"{starboard_msg.new_channel}-{starboard_msg.new_message}"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from typing import Dict, Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, checks, commands
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils.chat_formatting import humanize_list, humanize_timedelta, pagify
|
||||
@@ -14,7 +14,7 @@ from .events import StarboardEvents
|
||||
from .starboard_entry import FakePayload, StarboardEntry
|
||||
|
||||
_ = Translator("Starboard", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.Starboard")
|
||||
log = getLogger("red.trusty-cogs.Starboard")
|
||||
|
||||
TimeConverter = commands.converter.TimedeltaConverter(
|
||||
minimum=timedelta(days=7), allowed_units=["days", "weeks"], default_unit="days"
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import Dict, List, Optional, Union
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot import VersionInfo, version_info
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.utils import AsyncIter
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.starboard")
|
||||
log = getLogger("red.trusty-cogs.starboard")
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -28,7 +28,6 @@ class FakePayload:
|
||||
@dataclass
|
||||
class StarboardEntry:
|
||||
def __init__(self, **kwargs):
|
||||
|
||||
super().__init__()
|
||||
self.name: str = kwargs.get("name", "starboard")
|
||||
self.guild: int = kwargs.get("guild", None)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import random
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
@@ -8,11 +7,12 @@ from random import choice, sample
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
|
||||
from .tarot_cards import card_list as tarot_cards
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.tarot")
|
||||
log = getLogger("red.trusty-cogs.tarot")
|
||||
|
||||
|
||||
TAROT_RE = re.compile(r"|".join(t["card_name"] for _id, t in tarot_cards.items()), flags=re.I)
|
||||
|
||||
+4
-5
@@ -1,6 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from copy import deepcopy
|
||||
@@ -11,6 +10,7 @@ import aiohttp
|
||||
import discord
|
||||
from discord.ext import tasks
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -20,7 +20,7 @@ from .flags import FLAGS
|
||||
|
||||
BASE_URL = "https://translation.googleapis.com"
|
||||
_ = Translator("Translate", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.Translate")
|
||||
log = getLogger("red.trusty-cogs.Translate")
|
||||
|
||||
FLAG_REGEX = re.compile(r"|".join(rf"{re.escape(f)}" for f in FLAGS.keys()))
|
||||
|
||||
@@ -275,7 +275,7 @@ class StatsCounter:
|
||||
|
||||
async def add_detect(self, guild: Optional[discord.Guild]):
|
||||
if guild:
|
||||
log.debug(f"adding detect to {guild.name}")
|
||||
log.debug("adding detect to %s", guild.name)
|
||||
if guild.id not in self._guild_counter:
|
||||
self._guild_counter[guild.id] = await self.config.guild(guild).count()
|
||||
self._guild_counter[guild.id]["detect"] += 1
|
||||
@@ -285,7 +285,7 @@ class StatsCounter:
|
||||
|
||||
async def add_requests(self, guild: Optional[discord.Guild], message: str):
|
||||
if guild:
|
||||
log.debug(f"Adding requests to {guild.name}")
|
||||
log.debug("Adding requests to %s", guild.name)
|
||||
if guild.id not in self._guild_counter:
|
||||
self._guild_counter[guild.id] = await self.config.guild(guild).count()
|
||||
self._guild_counter[guild.id]["requests"] += 1
|
||||
@@ -549,7 +549,6 @@ class GoogleTranslateAPI:
|
||||
flag: Optional[str] = None,
|
||||
reacted_user: Optional[discord.Member] = None,
|
||||
) -> Optional[discord.Embed]:
|
||||
|
||||
to_translate = None
|
||||
if message.embeds != []:
|
||||
if message.embeds[0].description:
|
||||
|
||||
@@ -11,11 +11,11 @@ Support the developer https://goo.gl/Brchj4
|
||||
Invite the bot to your guild https://goo.gl/aQm2G7
|
||||
Join the official development guild https://discord.gg/uekTNPj
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
from discord.ext.commands.errors import BadArgument
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, VersionInfo, checks, commands, version_info
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
@@ -27,7 +27,7 @@ from .errors import GoogleTranslateAPIError
|
||||
|
||||
BASE_URL = "https://translation.googleapis.com"
|
||||
_ = Translator("Translate", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.Translate")
|
||||
log = getLogger("red.trusty-cogs.Translate")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
|
||||
+5
-7
@@ -1,11 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import discord
|
||||
import tweepy
|
||||
from red_commons.logging import getLogger
|
||||
|
||||
# from discord.ext.commands.errors import BadArgument
|
||||
from redbot.core.commands import commands
|
||||
@@ -14,7 +14,7 @@ from redbot.vendored.discord.ext import menus
|
||||
|
||||
from .tweets_api import EXPANSIONS, MEDIA_FIELDS, TWEET_FIELDS, USER_FIELDS
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.tweets")
|
||||
log = getLogger("red.Trusty-cogs.tweets")
|
||||
_ = Translator("Tweets", __file__)
|
||||
|
||||
|
||||
@@ -92,7 +92,6 @@ class TweetPages(menus.PageSource):
|
||||
"""
|
||||
self._index += 1
|
||||
if self._index > (len(self._cache) - 1) or skip:
|
||||
|
||||
try:
|
||||
await self._next_batch(_next=True)
|
||||
except Exception:
|
||||
@@ -137,15 +136,14 @@ class TweetPages(menus.PageSource):
|
||||
self,
|
||||
pagination_token: Optional[str] = None,
|
||||
) -> List[tweepy.Status]:
|
||||
|
||||
msg_list = []
|
||||
if self._user is None:
|
||||
log.info(f"Getting user ID for {self._username}")
|
||||
log.info("Getting user ID for %s", self._username)
|
||||
resp = await self._api.get_user(username=self._username)
|
||||
self._user = resp.data
|
||||
log.info(f"{self._user}")
|
||||
log.info("_get_twitter_statuses user: %s", self._user)
|
||||
try:
|
||||
log.info(f"Getting tweets for {self._user.id}")
|
||||
log.info("Getting tweets for %s", self._user.id)
|
||||
kwargs = {
|
||||
"id": self._user.id,
|
||||
"tweet_fields": TWEET_FIELDS,
|
||||
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Literal, Optional
|
||||
|
||||
import discord
|
||||
import tweepy
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, checks, commands
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils.chat_formatting import humanize_number
|
||||
@@ -14,7 +14,7 @@ from .tweets_api import USER_FIELDS, TweetsAPI
|
||||
|
||||
_ = Translator("Tweets", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Tweets")
|
||||
log = getLogger("red.trusty-cogs.Tweets")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
|
||||
+10
-10
@@ -1,6 +1,5 @@
|
||||
import asyncio
|
||||
import functools
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Dict, List, Optional, Union
|
||||
@@ -8,6 +7,7 @@ from typing import Dict, List, Optional, Union
|
||||
import aiohttp
|
||||
import discord
|
||||
import tweepy
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.i18n import Translator
|
||||
@@ -18,7 +18,7 @@ from .tweet_entry import TweetEntry
|
||||
|
||||
_ = Translator("Tweets", __file__)
|
||||
|
||||
log = logging.getLogger("red.trusty-cogs.Tweets")
|
||||
log = getLogger("red.trusty-cogs.Tweets")
|
||||
|
||||
USER_FIELDS = [
|
||||
"created_at",
|
||||
@@ -130,7 +130,7 @@ class TweetListener(AsyncStreamingClient):
|
||||
|
||||
async def on_connection_error(self, error: Exception = None):
|
||||
if error is not None:
|
||||
log.error(f"Error on Tweet stream connection attempt - {error}")
|
||||
log.error("Error on Tweet stream connection attempt - %s", error)
|
||||
|
||||
async def on_keep_alive(self):
|
||||
if "Keep-Alive" not in self.error_counts:
|
||||
@@ -183,9 +183,9 @@ class TweetListener(AsyncStreamingClient):
|
||||
error_title=error_title, error_details=error_details, link_info=error_type
|
||||
)
|
||||
if error_title == "operational-disconnect":
|
||||
log.info(error_msg)
|
||||
log.warning(error_msg)
|
||||
else:
|
||||
log.error(error_msg)
|
||||
log.warning(error_msg)
|
||||
full_msg += error_msg
|
||||
if full_msg:
|
||||
self.bot.dispatch("tweet_error", full_msg)
|
||||
@@ -198,9 +198,9 @@ class TweetListener(AsyncStreamingClient):
|
||||
error_title=error_title, error_details=error_details, link_info=error_type
|
||||
)
|
||||
if error_title == "operational-disconnect":
|
||||
log.info(error_msg)
|
||||
log.warning(error_msg)
|
||||
else:
|
||||
log.error(error_msg)
|
||||
log.warning(error_msg)
|
||||
self.bot.dispatch("tweet_error", error_msg)
|
||||
|
||||
async def on_closed(self, resp: aiohttp.ClientResponse):
|
||||
@@ -219,7 +219,7 @@ class TweetListener(AsyncStreamingClient):
|
||||
|
||||
async def on_disconnect(self) -> None:
|
||||
# self.last_disconnect = datetime.now().timestamp()
|
||||
log.info(_("The Tweet stream has disconnected."))
|
||||
log.info("The Tweet stream has disconnected.")
|
||||
|
||||
|
||||
class TweetsAPI:
|
||||
@@ -260,7 +260,7 @@ class TweetsAPI:
|
||||
log.info("Tweets stream done or cancelled, restarting")
|
||||
self.mystream.disconnect()
|
||||
self.mystream.start()
|
||||
log.debug(f"tweets waiting {base_sleep * count} seconds.")
|
||||
log.debug("tweets waiting %s seconds.", base_sleep * count)
|
||||
await asyncio.sleep(base_sleep * count)
|
||||
|
||||
async def refresh_token(self, user: discord.abc.User) -> dict:
|
||||
@@ -553,7 +553,7 @@ class TweetsAPI:
|
||||
if channel is None:
|
||||
continue
|
||||
if nsfw and not channel.is_nsfw():
|
||||
log.info(f"Ignoring tweet from {user} because it is labeled as NSFW.")
|
||||
log.info("Ignoring tweet from %s because it is labeled as NSFW.", user)
|
||||
continue
|
||||
if str(user.id) in data.get("followed_accounts", {}):
|
||||
tasks.append(
|
||||
|
||||
+2
-2
@@ -1,17 +1,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any, List
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import commands
|
||||
from redbot.core.i18n import Translator
|
||||
from redbot.vendored.discord.ext import menus
|
||||
|
||||
from .twitch_models import TwitchFollower
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.twitch")
|
||||
log = getLogger("red.Trusty-cogs.twitch")
|
||||
|
||||
_ = Translator("Twitch", __file__)
|
||||
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Literal, Optional
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, checks, commands
|
||||
from redbot.core.commands.converter import TimedeltaConverter
|
||||
|
||||
@@ -11,7 +11,7 @@ from .menus import BaseMenu, TwitchClipsPages, TwitchFollowersPages
|
||||
from .twitch_api import TwitchAPI
|
||||
from .twitch_models import TwitchFollower
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.Twitch")
|
||||
log = getLogger("red.Trusty-cogs.Twitch")
|
||||
|
||||
BASE_URL = "https://api.twitch.tv/helix"
|
||||
|
||||
|
||||
+12
-10
@@ -1,11 +1,11 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, VersionInfo, commands, version_info
|
||||
from redbot.core.bot import Red
|
||||
from redbot.core.utils import bounded_gather
|
||||
@@ -13,7 +13,7 @@ from redbot.core.utils import bounded_gather
|
||||
from .errors import TwitchError
|
||||
from .twitch_models import TwitchFollower, TwitchProfile
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.Twitch")
|
||||
log = getLogger("red.Trusty-cogs.Twitch")
|
||||
|
||||
BASE_URL = "https://api.twitch.tv/helix"
|
||||
|
||||
@@ -68,7 +68,7 @@ class TwitchAPI:
|
||||
# Calculate wait time and add 0.1s to the wait time to allow Twitch to reset
|
||||
# their counter
|
||||
wait_time = reset_time - current_time + 0.1
|
||||
log.debug(wait_time)
|
||||
log.trace("wait_for_rate_limit_reset, timer: %s", wait_time)
|
||||
await asyncio.sleep(wait_time)
|
||||
|
||||
async def oauth_check(self) -> None:
|
||||
@@ -162,11 +162,11 @@ class TwitchAPI:
|
||||
|
||||
async def get_all_followers(self, user_id: str) -> Tuple[list, dict]:
|
||||
# Get's first 100 users following user_id
|
||||
url = "{}/users/follows?to_id={}&first=100".format(BASE_URL, user_id)
|
||||
url = f"{BASE_URL}/users/follows?to_id={user_id}&first=100"
|
||||
data = await self.get_response(url)
|
||||
follows = [x["from_id"] for x in data["data"]]
|
||||
total = data["total"]
|
||||
log.debug(f"{len(follows)} of {total}")
|
||||
log.debug("%s of %s", len(follows), total)
|
||||
return follows, total
|
||||
|
||||
async def get_all_streams(self):
|
||||
@@ -242,8 +242,10 @@ class TwitchAPI:
|
||||
except Exception:
|
||||
log.exception(f"Error getting twitch profile {follow.from_id}", exc_info=True)
|
||||
log.info(
|
||||
f"{profile.login} Followed! {followed.display_name} "
|
||||
f"has {total} followers now."
|
||||
"%s Followed! %s " "has %s followers now.",
|
||||
profile.login,
|
||||
followed.display_name,
|
||||
total,
|
||||
)
|
||||
em = await self.make_follow_embed(followed, profile, total)
|
||||
for channel_id in account["channels"]:
|
||||
@@ -276,7 +278,7 @@ class TwitchAPI:
|
||||
if info["view_count"] and clip["view_count"] < info["view_count"]:
|
||||
continue
|
||||
if clip["id"] in info["clips"]:
|
||||
log.debug("skipping clip")
|
||||
log.verbose("send_clips_update - skipping clip")
|
||||
continue
|
||||
if channel and channel.permissions_for(channel.guild.me).send_messages:
|
||||
tasks.append(channel.send(msg))
|
||||
@@ -290,12 +292,12 @@ class TwitchAPI:
|
||||
async def check_clips(self):
|
||||
followed = await self.config.twitch_clips()
|
||||
for user_id, clip_data in followed.items():
|
||||
log.debug(f"Checking for new clips from {clip_data['display_name']}")
|
||||
log.verbose("Checking for new clips from %s", clip_data["display_name"])
|
||||
try:
|
||||
now = datetime.utcnow() + timedelta(days=-8)
|
||||
clips = await self.get_new_clips(user_id, now)
|
||||
except Exception:
|
||||
log.exception(f"Error getting twitch clips {user_id}", exc_info=True)
|
||||
log.exception("Error getting twitch clips %s", user_id, exc_info=True)
|
||||
continue
|
||||
for clip in clips:
|
||||
await self.send_clips_update(clip, clip_data)
|
||||
|
||||
+4
-4
@@ -1,6 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
@@ -8,12 +7,13 @@ from typing import Dict, List, NamedTuple, Optional
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import i18n
|
||||
from redbot.core.utils.chat_formatting import humanize_list
|
||||
|
||||
_ = i18n.Translator("Weather", __file__)
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.weather")
|
||||
log = getLogger("red.Trusty-cogs.weather")
|
||||
|
||||
|
||||
HEADERS = {"User-Agent": "Trusty-cogs Weather cog for Red-DiscordBot"}
|
||||
@@ -306,7 +306,7 @@ class Zipcode:
|
||||
else:
|
||||
async with session.get(url, params=params) as resp:
|
||||
data = await resp.json()
|
||||
log.debug(data)
|
||||
log.debug("Zipcode get data: %s", data)
|
||||
if "cod" in data and data["cod"] != "200":
|
||||
raise APIError(data["message"])
|
||||
|
||||
@@ -742,7 +742,7 @@ class OneCall:
|
||||
else:
|
||||
async with session.get(url, params=params) as resp:
|
||||
data = await resp.json()
|
||||
log.debug(data)
|
||||
log.verbose("OneCall get data: %s", data)
|
||||
if "cod" in data and data["cod"] != "200":
|
||||
raise APIError(data["message"])
|
||||
return cls.from_json(data, units, name, state, country)
|
||||
|
||||
+3
-3
@@ -1,10 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, List, Optional, Union
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
|
||||
# from discord.ext.commands.errors import BadArgument
|
||||
from redbot.core.commands import commands
|
||||
@@ -13,7 +13,7 @@ from redbot.vendored.discord.ext import menus
|
||||
|
||||
from .api import APIError, Geocoding, OneCall, Units, Zipcode
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.weather")
|
||||
log = getLogger("red.Trusty-cogs.weather")
|
||||
_ = Translator("Weather", __file__)
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ class WeatherPages(menus.ListPageSource):
|
||||
self._last_coords = None
|
||||
|
||||
async def format_page(self, view: BaseMenu, page: Union[Geocoding, Zipcode]):
|
||||
log.debug(page)
|
||||
log.verbose("WeatherPages page: %s", page)
|
||||
if self._last_coords != page:
|
||||
try:
|
||||
we = await OneCall.get(
|
||||
|
||||
+2
-2
@@ -1,10 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Literal, Optional
|
||||
|
||||
import aiohttp
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, checks, commands, i18n
|
||||
from redbot.core.utils.views import SetApiView
|
||||
|
||||
@@ -13,7 +13,7 @@ from .menus import BaseMenu, WeatherPages
|
||||
|
||||
_ = i18n.Translator("Weather", __file__)
|
||||
|
||||
log = logging.getLogger("red.Trusty-cogs.weather")
|
||||
log = getLogger("red.Trusty-cogs.weather")
|
||||
|
||||
|
||||
@i18n.cog_i18n(_)
|
||||
|
||||
+18
-24
@@ -1,10 +1,10 @@
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from random import choice as rand_choice
|
||||
from typing import List, Optional, Pattern, Union, cast
|
||||
|
||||
import discord
|
||||
from red_commons.logging import getLogger
|
||||
from redbot import VersionInfo, version_info
|
||||
from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
@@ -15,7 +15,7 @@ from redbot.core.utils.common_filters import filter_mass_mentions
|
||||
RE_CTX: Pattern = re.compile(r"{([^}]+)\}")
|
||||
RE_POS: Pattern = re.compile(r"{((\d+)[^.}]*(\.[^:}]+)?[^}]*)\}")
|
||||
_ = Translator("Welcome", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.Welcome")
|
||||
log = getLogger("red.trusty-cogs.Welcome")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
@@ -166,13 +166,13 @@ class Events:
|
||||
return await self.bot_welcome(member, guild)
|
||||
td = timedelta(days=await self.config.guild(guild).MINIMUM_DAYS())
|
||||
if (datetime.now(timezone.utc) - member.created_at) <= td:
|
||||
log.info(_("Member joined with an account newer than required days."))
|
||||
log.info("Member joined with an account newer than required days.")
|
||||
return
|
||||
has_filter = self.bot.get_cog("Filter")
|
||||
filter_setting = await self.config.guild(guild).FILTER_SETTING()
|
||||
if has_filter and filter_setting is None:
|
||||
if await has_filter.filter_hits(member.name, guild):
|
||||
log.info(_("Member joined with a bad username."))
|
||||
log.info("Member joined with a bad username.")
|
||||
return
|
||||
|
||||
if datetime.now(timezone.utc).date() > self.today_count["now"].date():
|
||||
@@ -210,13 +210,13 @@ class Events:
|
||||
await member.add_roles(role, reason=_("Automatic Bot Role"))
|
||||
except Exception:
|
||||
log.error(
|
||||
_("welcome.py: unable to add a role. ") + f"{bot_role} {member}",
|
||||
"welcome.py: unable to add a role. %s %s",
|
||||
bot_role,
|
||||
member,
|
||||
exc_info=True,
|
||||
)
|
||||
else:
|
||||
log.debug(
|
||||
_("welcome.py: added ") + str(role) + _(" role to ") + _("bot, ") + str(member)
|
||||
)
|
||||
log.debug("welcome.py: added %s role to bot, %s", role, member)
|
||||
if bot_welcome:
|
||||
# finally, welcome them
|
||||
if not channel:
|
||||
@@ -243,8 +243,8 @@ class Events:
|
||||
if channel is None: # complain even if only whisper
|
||||
if not only_whisper:
|
||||
log.info(
|
||||
_("welcome.py: Channel not found. It was most likely deleted. User joined: ")
|
||||
+ str(member)
|
||||
"welcome.py: Channel not found. It was most likely deleted. User joined: %s",
|
||||
member,
|
||||
)
|
||||
return None
|
||||
else:
|
||||
@@ -253,10 +253,11 @@ class Events:
|
||||
# we can stop here
|
||||
|
||||
if not channel.permissions_for(guild.me).send_messages:
|
||||
log.info(_("Permissions Error. User that joined: ") + "{0}".format(member))
|
||||
log.info("Permissions Error. User that joined: %s", member)
|
||||
log.info(
|
||||
_("Bot doesn't have permissions to send messages to ")
|
||||
+ "{0.name}'s #{1.name} channel".format(guild, channel)
|
||||
"Bot doesn't have permissions to send messages to %s's $%s",
|
||||
guild.name,
|
||||
channel.name,
|
||||
)
|
||||
return None
|
||||
return channel
|
||||
@@ -302,11 +303,8 @@ class Events:
|
||||
await member.send(await self.convert_parms(member, guild, msg, False)) # type: ignore
|
||||
except discord.errors.Forbidden:
|
||||
log.info(
|
||||
_(
|
||||
"welcome.py: unable to whisper a user. Probably "
|
||||
"doesn't want to be PM'd"
|
||||
)
|
||||
+ str(member)
|
||||
"welcome.py: unable to whisper %s. Probably " "doesn't want to be PM'd",
|
||||
member,
|
||||
)
|
||||
except Exception:
|
||||
log.error("error sending member join message", exc_info=True)
|
||||
@@ -381,11 +379,7 @@ class Events:
|
||||
# guild_settings = await self.config.guild(guild).guild_settings()
|
||||
channel = self.bot.get_channel(await self.config.guild(guild).LEAVE_CHANNEL())
|
||||
if channel is None: # complain even if only whisper
|
||||
log.info(
|
||||
_("welcome.py: Channel not found in {guild}. It was most likely deleted.").format(
|
||||
guild=guild
|
||||
)
|
||||
)
|
||||
log.info("welcome.py: Channel not found in %s. It was most likely deleted.", guild)
|
||||
return
|
||||
# we can stop here
|
||||
if await self.config.guild(guild).DELETE_PREVIOUS_GOODBYE():
|
||||
@@ -403,7 +397,7 @@ class Events:
|
||||
await old_msg.delete()
|
||||
|
||||
if not channel.permissions_for(guild.me).send_messages:
|
||||
log.info(_("Permissions Error in {guild}"))
|
||||
log.info("Permissions Error in {guild}")
|
||||
return
|
||||
elif not member.bot:
|
||||
if is_embed and channel.permissions_for(guild.me).embed_links:
|
||||
|
||||
+36
-104
@@ -1,11 +1,11 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
from discord.ext import tasks
|
||||
from red_commons.logging import getLogger
|
||||
from redbot.core import Config, VersionInfo, checks, commands, version_info
|
||||
from redbot.core.i18n import Translator, cog_i18n
|
||||
from redbot.core.utils.chat_formatting import humanize_list, pagify
|
||||
@@ -56,7 +56,7 @@ default_settings = {
|
||||
IMAGE_LINKS = re.compile(r"(http[s]?:\/\/[^\"\']*\.(?:png|jpg|jpeg|gif|png))")
|
||||
|
||||
_ = Translator("Welcome", __file__)
|
||||
log = logging.getLogger("red.trusty-cogs.Welcome")
|
||||
log = getLogger("red.trusty-cogs.Welcome")
|
||||
|
||||
|
||||
@cog_i18n(_)
|
||||
@@ -189,9 +189,7 @@ class Welcome(Events, commands.Cog):
|
||||
@welcomeset_greeting.command()
|
||||
@checks.mod_or_permissions(mention_everyone=True)
|
||||
@checks.bot_has_permissions(mention_everyone=True)
|
||||
async def allowedmentions(
|
||||
self, ctx: commands.Context, set_to: bool, *allowed
|
||||
) -> None:
|
||||
async def allowedmentions(self, ctx: commands.Context, set_to: bool, *allowed) -> None:
|
||||
"""
|
||||
Determine the bots allowed mentions for welcomes
|
||||
|
||||
@@ -201,14 +199,10 @@ class Welcome(Events, commands.Cog):
|
||||
Note: This will only function on Red 3.4.0 or higher.
|
||||
"""
|
||||
if not allowed:
|
||||
return await ctx.send(
|
||||
_("You must provide either `users`, `roles` or `everyone`.")
|
||||
)
|
||||
return await ctx.send(_("You must provide either `users`, `roles` or `everyone`."))
|
||||
for i in set(allowed):
|
||||
if i not in ["everyone", "users", "roles"]:
|
||||
return await ctx.send(
|
||||
_("You must provide either `users`, `roles` or `everyone`.")
|
||||
)
|
||||
return await ctx.send(_("You must provide either `users`, `roles` or `everyone`."))
|
||||
if (
|
||||
"everyone" in set(allowed)
|
||||
or "roles" in set(allowed)
|
||||
@@ -229,9 +223,7 @@ class Welcome(Events, commands.Cog):
|
||||
)
|
||||
|
||||
@welcomeset_greeting.command(name="grouped")
|
||||
async def welcomeset_greeting_grouped(
|
||||
self, ctx: commands.Context, grouped: bool
|
||||
) -> None:
|
||||
async def welcomeset_greeting_grouped(self, ctx: commands.Context, grouped: bool) -> None:
|
||||
"""Set whether to group welcome messages"""
|
||||
await self.config.guild(ctx.guild).GROUPED.set(grouped)
|
||||
if grouped:
|
||||
@@ -240,9 +232,7 @@ class Welcome(Events, commands.Cog):
|
||||
await ctx.send(_("I will no longer group welcomes."))
|
||||
|
||||
@welcomeset_greeting.command(name="add")
|
||||
async def welcomeset_greeting_add(
|
||||
self, ctx: commands.Context, *, format_msg: str
|
||||
) -> None:
|
||||
async def welcomeset_greeting_add(self, ctx: commands.Context, *, format_msg: str) -> None:
|
||||
"""
|
||||
Adds a welcome message format for the guild to be chosen at random
|
||||
|
||||
@@ -325,15 +315,11 @@ class Welcome(Events, commands.Cog):
|
||||
guild_settings = not guild_settings
|
||||
if guild_settings:
|
||||
await ctx.send(
|
||||
_(
|
||||
"I will now delete the previous welcome message when a new user joins."
|
||||
)
|
||||
_("I will now delete the previous welcome message when a new user joins.")
|
||||
)
|
||||
else:
|
||||
await ctx.send(
|
||||
_(
|
||||
"I will stop deleting the previous welcome message when a new user joins."
|
||||
)
|
||||
_("I will stop deleting the previous welcome message when a new user joins.")
|
||||
)
|
||||
await self.config.guild(guild).DELETE_PREVIOUS_GREETING.set(guild_settings)
|
||||
|
||||
@@ -348,19 +334,13 @@ class Welcome(Events, commands.Cog):
|
||||
guild_settings = await self.config.guild(guild).JOINED_TODAY()
|
||||
guild_settings = not guild_settings
|
||||
if guild_settings:
|
||||
await ctx.send(
|
||||
_("I will now show how many people join the server each day.")
|
||||
)
|
||||
await ctx.send(_("I will now show how many people join the server each day."))
|
||||
else:
|
||||
await ctx.send(
|
||||
_("I will stop showing how many people join the server each day.")
|
||||
)
|
||||
await ctx.send(_("I will stop showing how many people join the server each day."))
|
||||
await self.config.guild(guild).JOINED_TODAY.set(guild_settings)
|
||||
|
||||
@welcomeset_greeting.command(name="minimumage", aliases=["age"])
|
||||
async def welcomeset_greeting_minimum_days(
|
||||
self, ctx: commands.Context, days: int
|
||||
) -> None:
|
||||
async def welcomeset_greeting_minimum_days(self, ctx: commands.Context, days: int) -> None:
|
||||
"""
|
||||
Set the minimum number of days a user account must be to show up in the welcome message
|
||||
|
||||
@@ -371,9 +351,7 @@ class Welcome(Events, commands.Cog):
|
||||
days = 0
|
||||
await self.config.guild(guild).MINIMUM_DAYS.set(days)
|
||||
await ctx.send(
|
||||
_("I will now show users joining who are {days} days old.").format(
|
||||
days=days
|
||||
)
|
||||
_("I will now show users joining who are {days} days old.").format(days=days)
|
||||
)
|
||||
|
||||
@welcomeset_greeting.command(name="filter")
|
||||
@@ -406,9 +384,7 @@ class Welcome(Events, commands.Cog):
|
||||
)
|
||||
else:
|
||||
await ctx.send(
|
||||
_(
|
||||
"I will not post welcome messages for usernames that match cores filter."
|
||||
)
|
||||
_("I will not post welcome messages for usernames that match cores filter.")
|
||||
)
|
||||
if not has_filter:
|
||||
await ctx.send(
|
||||
@@ -458,9 +434,7 @@ class Welcome(Events, commands.Cog):
|
||||
return
|
||||
guild_settings = channel.id
|
||||
await self.config.guild(guild).CHANNEL.set(guild_settings)
|
||||
msg = _("I will now send welcome messages to {channel}").format(
|
||||
channel=channel.mention
|
||||
)
|
||||
msg = _("I will now send welcome messages to {channel}").format(channel=channel.mention)
|
||||
await ctx.send(msg)
|
||||
|
||||
@welcomeset_greeting.command()
|
||||
@@ -477,9 +451,7 @@ class Welcome(Events, commands.Cog):
|
||||
|
||||
@welcomeset_goodbye.command(name="allowedmentions")
|
||||
@checks.mod_or_permissions(mention_everyone=True)
|
||||
async def goodbye_allowedmentions(
|
||||
self, ctx: commands.Context, set_to: bool, *allowed
|
||||
) -> None:
|
||||
async def goodbye_allowedmentions(self, ctx: commands.Context, set_to: bool, *allowed) -> None:
|
||||
"""
|
||||
Determine the bots allowed mentions for welcomes
|
||||
|
||||
@@ -489,14 +461,10 @@ class Welcome(Events, commands.Cog):
|
||||
Note: This will only function on Red 3.4.0 or higher.
|
||||
"""
|
||||
if not allowed:
|
||||
return await ctx.send(
|
||||
_("You must provide either `users`, `roles` or `everyone`.")
|
||||
)
|
||||
return await ctx.send(_("You must provide either `users`, `roles` or `everyone`."))
|
||||
for i in set(allowed):
|
||||
if i not in ["everyone", "users", "roles"]:
|
||||
return await ctx.send(
|
||||
_("You must provide either `users`, `roles` or `everyone`.")
|
||||
)
|
||||
return await ctx.send(_("You must provide either `users`, `roles` or `everyone`."))
|
||||
if (
|
||||
"everyone" in set(allowed)
|
||||
or "roles" in set(allowed)
|
||||
@@ -517,9 +485,7 @@ class Welcome(Events, commands.Cog):
|
||||
)
|
||||
|
||||
@welcomeset_goodbye.command(name="add")
|
||||
async def welcomeset_goodbye_add(
|
||||
self, ctx: commands.Context, *, format_msg: str
|
||||
) -> None:
|
||||
async def welcomeset_goodbye_add(self, ctx: commands.Context, *, format_msg: str) -> None:
|
||||
"""
|
||||
Adds a goodbye message format for the guild to be chosen at random
|
||||
|
||||
@@ -590,9 +556,7 @@ class Welcome(Events, commands.Cog):
|
||||
if guild_settings:
|
||||
await ctx.send(_("I will now say goodbye when a member leaves the server."))
|
||||
else:
|
||||
await ctx.send(
|
||||
_("I will no longer say goodbye to members leaving the server.")
|
||||
)
|
||||
await ctx.send(_("I will no longer say goodbye to members leaving the server."))
|
||||
await self.config.guild(guild).LEAVE_ON.set(guild_settings)
|
||||
|
||||
@welcomeset_goodbye.command(name="channel")
|
||||
@@ -610,9 +574,7 @@ class Welcome(Events, commands.Cog):
|
||||
await ctx.send(msg)
|
||||
return
|
||||
await self.config.guild(guild).LEAVE_CHANNEL.set(channel.id)
|
||||
msg = _("I will now send goodbye messages to {channel}").format(
|
||||
channel=channel.mention
|
||||
)
|
||||
msg = _("I will now send goodbye messages to {channel}").format(channel=channel.mention)
|
||||
await ctx.send(msg)
|
||||
|
||||
@welcomeset_goodbye.command(name="deleteprevious")
|
||||
@@ -624,14 +586,10 @@ class Welcome(Events, commands.Cog):
|
||||
guild_settings = await self.config.guild(guild).DELETE_PREVIOUS_GOODBYE()
|
||||
guild_settings = not guild_settings
|
||||
if guild_settings:
|
||||
await ctx.send(
|
||||
_("I will now delete the previous goodbye message when user leaves.")
|
||||
)
|
||||
await ctx.send(_("I will now delete the previous goodbye message when user leaves."))
|
||||
else:
|
||||
await ctx.send(
|
||||
_(
|
||||
"I will stop deleting the previous goodbye message when a user leaves."
|
||||
)
|
||||
_("I will stop deleting the previous goodbye message when a user leaves.")
|
||||
)
|
||||
await self.config.guild(guild).DELETE_PREVIOUS_GOODBYE.set(guild_settings)
|
||||
|
||||
@@ -711,9 +669,7 @@ class Welcome(Events, commands.Cog):
|
||||
await ctx.send(msg)
|
||||
|
||||
@welcomeset.command()
|
||||
async def whisper(
|
||||
self, ctx: commands.Context, choice: Optional[str] = None
|
||||
) -> None:
|
||||
async def whisper(self, ctx: commands.Context, choice: Optional[str] = None) -> None:
|
||||
"""Sets whether or not a DM is sent to the new user
|
||||
|
||||
Options:
|
||||
@@ -803,9 +759,7 @@ class Welcome(Events, commands.Cog):
|
||||
await ctx.tick()
|
||||
|
||||
@_embed.command()
|
||||
async def thumbnail(
|
||||
self, ctx: commands.Context, link: Optional[str] = None
|
||||
) -> None:
|
||||
async def thumbnail(self, ctx: commands.Context, link: Optional[str] = None) -> None:
|
||||
"""
|
||||
Set the embed thumbnail image
|
||||
|
||||
@@ -819,9 +773,7 @@ class Welcome(Events, commands.Cog):
|
||||
if link is not None:
|
||||
link_search = IMAGE_LINKS.search(link)
|
||||
if link_search:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.thumbnail.set(
|
||||
link_search.group(0)
|
||||
)
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.thumbnail.set(link_search.group(0))
|
||||
await ctx.tick()
|
||||
elif link in ["member", "user", "avatar"]:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.thumbnail.set("avatar")
|
||||
@@ -834,9 +786,7 @@ class Welcome(Events, commands.Cog):
|
||||
await ctx.tick()
|
||||
else:
|
||||
await ctx.send(
|
||||
_(
|
||||
"That's not a valid option. You must provide a link, `avatar` or `server`."
|
||||
)
|
||||
_("That's not a valid option. You must provide a link, `avatar` or `server`.")
|
||||
)
|
||||
else:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.thumbnail.set(None)
|
||||
@@ -857,9 +807,7 @@ class Welcome(Events, commands.Cog):
|
||||
if link is not None:
|
||||
link_search = IMAGE_LINKS.search(link)
|
||||
if link_search:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.icon_url.set(
|
||||
link_search.group(0)
|
||||
)
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.icon_url.set(link_search.group(0))
|
||||
await ctx.tick()
|
||||
elif link in ["author", "avatar"]:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.icon_url.set("avatar")
|
||||
@@ -872,9 +820,7 @@ class Welcome(Events, commands.Cog):
|
||||
await ctx.tick()
|
||||
else:
|
||||
await ctx.send(
|
||||
_(
|
||||
"That's not a valid option. You must provide a link, `avatar` or `server`."
|
||||
)
|
||||
_("That's not a valid option. You must provide a link, `avatar` or `server`.")
|
||||
)
|
||||
else:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.icon_url.set(None)
|
||||
@@ -888,9 +834,7 @@ class Welcome(Events, commands.Cog):
|
||||
pass
|
||||
|
||||
@_image.command(name="greeting")
|
||||
async def image_greeting(
|
||||
self, ctx: commands.Context, link: Optional[str] = None
|
||||
) -> None:
|
||||
async def image_greeting(self, ctx: commands.Context, link: Optional[str] = None) -> None:
|
||||
"""
|
||||
Set the embed image link for greetings
|
||||
|
||||
@@ -904,9 +848,7 @@ class Welcome(Events, commands.Cog):
|
||||
if link is not None:
|
||||
link_search = IMAGE_LINKS.search(link)
|
||||
if link_search:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.image.set(
|
||||
link_search.group(0)
|
||||
)
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.image.set(link_search.group(0))
|
||||
await ctx.tick()
|
||||
elif link in ["author", "avatar"]:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.image.set("avatar")
|
||||
@@ -919,18 +861,14 @@ class Welcome(Events, commands.Cog):
|
||||
await ctx.tick()
|
||||
else:
|
||||
await ctx.send(
|
||||
_(
|
||||
"That's not a valid option. You must provide a link, `avatar` or `server`."
|
||||
)
|
||||
_("That's not a valid option. You must provide a link, `avatar` or `server`.")
|
||||
)
|
||||
else:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.image.set(None)
|
||||
await ctx.send(_("Greeting image cleared."))
|
||||
|
||||
@_image.command(name="goodbye")
|
||||
async def image_goodbye(
|
||||
self, ctx: commands.Context, link: Optional[str] = None
|
||||
) -> None:
|
||||
async def image_goodbye(self, ctx: commands.Context, link: Optional[str] = None) -> None:
|
||||
"""
|
||||
Set the embed image link for goodbyes
|
||||
|
||||
@@ -949,23 +887,17 @@ class Welcome(Events, commands.Cog):
|
||||
)
|
||||
await ctx.tick()
|
||||
elif link in ["author", "avatar"]:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.image_goodbye.set(
|
||||
"avatar"
|
||||
)
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.image_goodbye.set("avatar")
|
||||
await ctx.tick()
|
||||
elif link in ["server", "guild"]:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.image_goodbye.set("guild")
|
||||
await ctx.tick()
|
||||
elif link == "splash":
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.image_goodbye.set(
|
||||
"splash"
|
||||
)
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.image_goodbye.set("splash")
|
||||
await ctx.tick()
|
||||
else:
|
||||
await ctx.send(
|
||||
_(
|
||||
"That's not a valid option. You must provide a link, `avatar` or `server`."
|
||||
)
|
||||
_("That's not a valid option. You must provide a link, `avatar` or `server`.")
|
||||
)
|
||||
else:
|
||||
await self.config.guild(ctx.guild).EMBED_DATA.image_goodbye.set(None)
|
||||
|
||||
Reference in new issue
Block a user