Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use anyio to support both trio and asyncio #142

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,25 +363,41 @@ In order to use the async version, you need to install the package using:
```
pip install discord-webhook[async]
```
python-discord-webhook supports both asyncio and [trio](https://trio.readthedocs.io/en/stable/) through the use of [anyio](https://anyio.readthedocs.io/en/3.x/)

Example usage:
```python
import asyncio
from discord_webhook import AsyncDiscordWebhook
import os

import trio

import discord_webhook

async def send_webhook(message):
webhook = AsyncDiscordWebhook(url="your webhook url", content=message)

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


async def main():
async def trio_main():
async with trio.open_nursery() as nursery:
nursery.start_soon(send_webhook, "Async webhook message 1")
nursery.start_soon(send_webhook, "Async webhook message 2")


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


asyncio.run(main())
if __name__ == "__main__":
trio.run(trio_main)
asyncio.run(asyncio_main())


```

### Use CLI
Expand Down
4 changes: 2 additions & 2 deletions discord_webhook/async_webhook.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import asyncio
import anyio
import json
import logging
from contextlib import asynccontextmanager
Expand Down Expand Up @@ -90,7 +90,7 @@ async def handle_rate_limit(self, response, request) -> "httpx.Response":
wh_sleep=round(wh_sleep, 2)
)
)
await asyncio.sleep(wh_sleep)
await anyio.sleep(wh_sleep)
response = await request()
if response.status_code in [200, 204]:
return response
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ keywords = ["discord", "webhook"]
python = "^3.8"
requests = "^2.28.1"
httpx = { version = "^0.23.0", optional = true }
anyio = "^3.7.1"

[tool.poetry.extras]
async = ["httpx"]
Expand Down