Skip to content

Commit

Permalink
format code
Browse files Browse the repository at this point in the history
  • Loading branch information
lovvskillz committed Jun 13, 2023
1 parent 384a4c6 commit 6cc9ed3
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 61 deletions.
18 changes: 9 additions & 9 deletions discord_webhook/async_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ async def api_post_request(self):
response = await client.post(
self.url,
json=self.json,
params={'wait': True},
params={"wait": True},
timeout=self.timeout,
)
else:
self.files["payload_json"] = (
None,
json.dumps(self.json).encode('utf-8'),
json.dumps(self.json).encode("utf-8"),
)
response = await client.post(
self.url, files=self.files, timeout=self.timeout
Expand All @@ -75,9 +75,9 @@ async def handle_rate_limit(self, response, request):
"""
while response.status_code == 429:
errors = response.json()
if not response.headers.get('Via'):
if not response.headers.get("Via"):
raise HTTPException(errors)
wh_sleep = (int(errors['retry_after']) / 1000) + 0.15
wh_sleep = (int(errors["retry_after"]) / 1000) + 0.15
logger.error(
"Webhook rate limited: sleeping for {wh_sleep} seconds...".format(
wh_sleep=wh_sleep
Expand Down Expand Up @@ -109,7 +109,7 @@ async def execute(self, remove_embeds=False):
if remove_embeds:
self.remove_embeds()
self.remove_files(clear_attachments=False)
if webhook_id := json.loads(response.content.decode("utf-8")).get('id'):
if webhook_id := json.loads(response.content.decode("utf-8")).get("id"):
self.id = webhook_id
return response

Expand All @@ -128,13 +128,13 @@ async def edit(self):
url = f"{self.url}/messages/{self.id}"
if bool(self.files) is False:
patch_kwargs = {
'json': self.json,
'params': {'wait': True},
'timeout': self.timeout,
"json": self.json,
"params": {"wait": True},
"timeout": self.timeout,
}
else:
self.files["payload_json"] = (None, json.dumps(self.json))
patch_kwargs = {'files': self.files, 'timeout': self.timeout}
patch_kwargs = {"files": self.files, "timeout": self.timeout}
request = partial(client.patch, url, **patch_kwargs)
response = await request()
if response.status_code in [200, 204]:
Expand Down
64 changes: 32 additions & 32 deletions discord_webhook/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,54 +307,61 @@ def __init__(
self.url = url
self.username = username

def add_file(self, file: bytes, filename: str) -> None:
"""
Add a file to the webhook.
:param file: file content
:param filename: filename
:return:
"""
self.files[f"_{filename}"] = (filename, file)

def add_embed(self, embed: Union[DiscordEmbed, Dict[str, Any]]) -> None:
"""
Add an embedded rich content.
:param embed: embed object or dict
"""
self.embeds.append(embed.__dict__ if isinstance(embed, DiscordEmbed) else embed)

def get_embeds(self) -> List[Dict[str, Any]]:
"""
Get all embeds as a list.
:return: self.embeds
"""
return self.embeds

def remove_embed(self, index: int) -> None:
"""
Remove embedded rich content from `self.embeds`.
:param index: index of embed in `self.embeds`
"""
self.embeds.pop(index)

def remove_embeds(self) -> None:
"""
Remove all embeds.
:return: None
"""
self.embeds = []

def add_file(self, file: bytes, filename: str) -> None:
"""
Add a file to the webhook.
:param file: file content
:param filename: filename
:return:
"""
self.files[f"_{filename}"] = (filename, file)

def remove_file(self, filename: str) -> None:
"""
Remove file by given `filename` if it exists.
:param filename: filename
"""
self.files.pop(f'_{filename}', None)
self.files.pop(f"_{filename}", None)
if self.attachments:
index = next(
(
i
for i, item in enumerate(self.attachments)
if item.get('filename') == filename
if item.get("filename") == filename
),
None,
)
if index is not None:
self.attachments.pop(index)

def remove_embeds(self) -> None:
"""
Remove all embeds.
:return: None
"""
self.embeds = []

def remove_files(self, clear_attachments: bool = True) -> None:
"""
Remove all files and optionally clear the attachments.
Expand All @@ -373,13 +380,6 @@ def clear_attachments(self) -> None:
"""
self.attachments = []

def get_embeds(self) -> List[Dict[str, Any]]:
"""
Get all embeds as a list.
:return: self.embeds
"""
return self.embeds

def set_proxies(self, proxies: Dict[str, str]) -> None:
"""
Set proxies.
Expand Down Expand Up @@ -410,7 +410,7 @@ def json(self) -> Dict[str, Any]:
data = {
key: value
for key, value in self.__dict__.items()
if value and key not in ['url', 'files'] or key in ['embeds', 'attachments']
if value and key not in ["url", "files"] or key in ["embeds", "attachments"]
}
embeds_empty = not any(data["embeds"]) if "embeds" in data else True
if embeds_empty and "content" not in data and bool(self.files) is False:
Expand Down Expand Up @@ -444,7 +444,7 @@ def handle_rate_limit(self, response, request):
"""
while response.status_code == 429:
errors = json.loads(response.content.decode("utf-8"))
if not response.headers.get('Via'):
if not response.headers.get("Via"):
raise HTTPException(errors)
wh_sleep = (int(errors["retry_after"]) / 1000) + 0.15
logger.error(f"Webhook rate limited: sleeping for {wh_sleep} seconds...")
Expand Down Expand Up @@ -473,16 +473,16 @@ def execute(
logger.error(
"Webhook status code {status_code}: {content}".format(
status_code=response.status_code,
content=response.content.decode('utf-8'),
content=response.content.decode("utf-8"),
)
)
if remove_embeds:
self.remove_embeds()
self.remove_files(clear_attachments=False)
response_content = json.loads(response.content.decode("utf-8"))
if webhook_id := response_content.get('id'):
if webhook_id := response_content.get("id"):
self.id = webhook_id
if attachments := response_content.get('attachments'):
if attachments := response_content.get("attachments"):
self.attachments = attachments
return response

Expand Down Expand Up @@ -555,12 +555,12 @@ def delete(self) -> requests.Response:
return response

@classmethod
def create_batch(cls, urls: List[str], **kwargs) -> Tuple['DiscordWebhook', ...]:
def create_batch(cls, urls: List[str], **kwargs) -> Tuple["DiscordWebhook", ...]:
"""
Create multiple instances of webhook.
:param urls: list of webhook URLs.
:return: tuple of webhook instances
"""
if 'url' in kwargs:
if "url" in kwargs:
raise TypeError("'url' can't be used as a keyword argument.")
return tuple([cls(url, **kwargs) for url in urls])
20 changes: 8 additions & 12 deletions discord_webhook/webhook_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,11 @@ class ColorNotInRangeException(Exception):
A valid color must take an integer value between 0 and 16777216 inclusive
"""

color: Union[str, int]

def __init__(self, color: Union[str, int]) -> None:
self.color = color
super().__init__()

def __str__(self) -> str:
return repr(
f"{self.color!r} is not in valid range of colors. The valid ranges "
"of colors are 0 to 16777215 inclusive (INTEGERS) and 0 "
"to FFFFFF inclusive (HEXADECIMAL)"
)
def __init__(self, color: Union[str, int], message=None) -> None:
if not message:
message = (
f"{color!r} is not in valid range of colors. The valid ranges of colors"
" are 0 to 16777215 inclusive (INTEGERS) and 0 to FFFFFF inclusive"
" (HEXADECIMAL)."
)
super().__init__(message)
6 changes: 3 additions & 3 deletions examples/use_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@


async def send_webhook(message):
webhook = AsyncDiscordWebhook(url='your webhook url', content=message)
webhook = AsyncDiscordWebhook(url="your webhook url", content=message)
await webhook.execute()


async def main():
await asyncio.gather(
send_webhook('Async webhook message 1'),
send_webhook('Async webhook message 2'),
send_webhook("Async webhook message 1"),
send_webhook("Async webhook message 2"),
) # sends both messages asynchronously


Expand Down
10 changes: 5 additions & 5 deletions tests/test_embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,17 @@ def test__set_embed__url(embed):


@pytest.mark.parametrize(
'timestamp',
"timestamp",
[
1679610926,
1679610926.0,
datetime.fromisoformat('2023-03-23T22:35:26'),
datetime.fromisoformat('2023-03-23T23:35:26+01:00'),
datetime.fromisoformat("2023-03-23T22:35:26"),
datetime.fromisoformat("2023-03-23T23:35:26+01:00"),
],
)
def test__set_embed__timestamp(embed, timestamp):
compare_datetime = datetime.fromisoformat(
'2023-03-23T22:35:26'
"2023-03-23T22:35:26"
) # timestamp 1679610926
if isinstance(timestamp, datetime):
compare_datetime = timestamp
Expand All @@ -57,7 +57,7 @@ def test__set_embed__timestamp(embed, timestamp):


@pytest.mark.parametrize(
'color, output',
"color, output",
[
("03b2f8", 242424),
(333333, 333333),
Expand Down

0 comments on commit 6cc9ed3

Please sign in to comment.