Skip to content

Commit b8f8037

Browse files
authored
Merge pull request #218 from nextsnake/tag-epic/docs/more-examples
Improve examples
2 parents 0715d86 + 2a9b6d9 commit b8f8037

File tree

17 files changed

+274
-6
lines changed

17 files changed

+274
-6
lines changed

docs/gateway.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Gateway quickstart
99
.. hint::
1010
We recommend that you read the :ref:`Making requests` tutorial before this, as we will not explain HTTP concepts here.
1111
.. hint::
12-
The finished example can be found `here <https://github.com/nextsnake/nextcore/blob/master/examples/gateway/ping_pong.py>`__
12+
The finished example can be found `here <https://github.com/nextsnake/nextcore/tree/master/examples/gateway/ping_pong>`__
1313
.. note::
1414
We will use await at the top level here as it's easier to explain. For your own code, please use an async function.
1515

docs/http.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Making requests
77
---------------
88

99
.. hint::
10-
The finished example can be found `here <https://github.com/nextsnake/nextcore/blob/master/examples/http/get_channel.py>`__
10+
The finished example can be found `here <https://github.com/nextsnake/nextcore/tree/master/examples/http/get_channel>`__
1111
.. note::
1212
We will use await at the top level here as its easier to explain. For your own code, please use a async function.
1313

examples/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Nextcore examples
2+
## Structure
3+
Nextcore examples is split into the same modules nextcore is split into
4+
5+
So examples in the `http` directory would be for stuff in the `nextcore.http` module.
6+
7+
## Docs
8+
Some of the examples have full tutorials in the docs.
9+
For example the [get channel example](http/get_channel) also has a [tutorial in the docs](https://nextcore.readthedocs.io/en/latest/http.html#making-requests)
10+
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Ping pong - slash command edition
2+
## Environment variables
3+
The following environment variables is required
4+
5+
1. TOKEN
6+
This can be found in your developer dashboard.
7+
2. APPLICATION_ID
8+
This is usually the ID of your bot.
9+
10+
## Creating the commands
11+
Please run the [register_commands script](register_commands.py)
12+
13+
After that just run the example
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# The MIT License (MIT)
2+
#
3+
# Copyright (c) 2022-present nextcore developers
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a
6+
# copy of this software and associated documentation files (the "Software"),
7+
# to deal in the Software without restriction, including without limitation
8+
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
9+
# and/or sell copies of the Software, and to permit persons to whom the
10+
# Software is furnished to do so, subject to the following conditions:
11+
# The above copyright notice and this permission notice shall be included in
12+
# all copies or substantial portions of the Software.
13+
#
14+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15+
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20+
# DEALINGS IN THE SOFTWARE.
21+
22+
"""
23+
A simple "ping pong" example of using nextcore, but in slash commands.
24+
25+
This will respond with "pong" every time someone sends "ping" in the chat.
26+
"""
27+
28+
import asyncio
29+
from os import environ
30+
from typing import cast
31+
32+
from discord_typings import InteractionCreateData
33+
34+
from nextcore.gateway import ShardManager
35+
from nextcore.http import BotAuthentication, HTTPClient, Route
36+
37+
# Constants
38+
AUTHENTICATION = BotAuthentication(environ["TOKEN"])
39+
40+
# Intents are a way to select what intents Discord should send to you.
41+
# For a list of intents see https://discord.dev/topics/gateway#gateway-intents
42+
INTENTS = 0 # Guild messages and message content intents.
43+
44+
45+
# Create a HTTPClient and a ShardManager.
46+
# A ShardManager is just a neat wrapper around Shard objects.
47+
http_client = HTTPClient()
48+
shard_manager = ShardManager(AUTHENTICATION, INTENTS, http_client)
49+
50+
51+
@shard_manager.event_dispatcher.listen("INTERACTION_CREATE")
52+
async def on_interaction_create(interaction: InteractionCreateData):
53+
# Only accept application comamnds. See https://discord.dev/interactions/receiving-and-responding#interaction-object-interaction-type for a list of types
54+
if interaction["type"] != 2:
55+
return
56+
# Only respond to the ping command
57+
if interaction["data"]["name"] != "ping":
58+
return
59+
60+
response = {
61+
"type": 4,
62+
"data": {
63+
"content": "Pong!"
64+
}
65+
}
66+
67+
route = Route("POST", "/interactions/{interaction_id}/{interaction_token}/callback", interaction_id=interaction["id"], interaction_token = interaction["token"])
68+
# Authentication is interaction id and interaction token, not bot authenication
69+
await http_client.request(route, rate_limit_key=None, json=response)
70+
71+
72+
async def main():
73+
await http_client.setup()
74+
75+
# This should return once all shards have started to connect.
76+
# This does not mean they are connected.
77+
await shard_manager.connect()
78+
79+
# Raise a error and exit whenever a critical error occurs
80+
(error,) = await shard_manager.dispatcher.wait_for(lambda: True, "critical")
81+
82+
raise cast(Exception, error)
83+
84+
85+
asyncio.run(main())
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# The MIT License (MIT)
2+
#
3+
# Copyright (c) 2022-present nextcore developers
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a
6+
# copy of this software and associated documentation files (the "Software"),
7+
# to deal in the Software without restriction, including without limitation
8+
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
9+
# and/or sell copies of the Software, and to permit persons to whom the
10+
# Software is furnished to do so, subject to the following conditions:
11+
# The above copyright notice and this permission notice shall be included in
12+
# all copies or substantial portions of the Software.
13+
#
14+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15+
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20+
# DEALINGS IN THE SOFTWARE.
21+
22+
"""
23+
The register script for this example.
24+
25+
This will register the "ping" slash command we need for this example.
26+
27+
NOTE: This only needs to be run once per bot, and should be ran before the example.
28+
WARNING: This will remove all other commands
29+
"""
30+
31+
from __future__ import annotations # We want to use newer type hinting. If you are using python 3.9+ feel free to remove this.
32+
33+
import asyncio
34+
from os import environ
35+
from discord_typings import ApplicationCommandPayload
36+
from nextcore.http import BotAuthentication, Route, HTTPClient
37+
38+
# Constants
39+
AUTHENTICATION = BotAuthentication(environ["TOKEN"])
40+
APPLICATION_ID = environ["APPLICATION_ID"] # This should also usually be the same as your bots id.
41+
COMMANDS: list[ApplicationCommandPayload] = [ # TODO: Currently we have no TypedDict for this.
42+
{
43+
"name": "ping",
44+
"description": "Responds with pong!"
45+
}
46+
]
47+
48+
http_client = HTTPClient()
49+
50+
async def main() -> None:
51+
await http_client.setup()
52+
53+
route = Route("PUT", "/applications/{application_id}/commands", application_id=APPLICATION_ID)
54+
await http_client.request(route, rate_limit_key=AUTHENTICATION.rate_limit_key, headers=AUTHENTICATION.headers, json=COMMANDS)
55+
56+
print("Commands registered")
57+
58+
await http_client.close()
59+
60+
asyncio.run(main())

nextcore/http/authentication/base.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,13 @@ class BaseAuthentication(ABC):
3636
.. warning::
3737
This is a base class. You should probably use :class:`BotAuthentication` or :class:`BearerAuthentication` instead.
3838
39+
**Example implementation**
40+
41+
.. this is relative to the docs directory
42+
.. literalinclude:: ../nextcore/http/authentication/bot.py
43+
:language: python3
44+
:lines: 34-
45+
3946
Attributes
4047
----------
4148
prefix:
@@ -52,6 +59,12 @@ def rate_limit_key(self) -> str | None:
5259
"""The key used for rate limiting
5360
5461
This is usually the prefix + token for for example ``Bot AABBCC.DDEEFF.GGHHII``
62+
63+
**Example usage**
64+
65+
.. code-block:: python3
66+
67+
await http_client.request(route, rate_limit_key=authentication.rate_limit_key, ...)
5568
"""
5669
...
5770

@@ -61,5 +74,12 @@ def headers(self) -> dict[str, str]:
6174
"""Headers used for making a authenticated request.
6275
6376
This may return a empty dict if headers is not used for authenticating this type of authentication.
77+
78+
**Example usage**
79+
80+
.. code-block:: python3
81+
82+
await http_client.request(route, rate_limit_key=authentication.rate_limit_key, headers=authentication.headers, ...)
83+
6484
"""
6585
...

0 commit comments

Comments
 (0)