11 Commits

10 changed files with 298 additions and 65 deletions

View File

@@ -20,14 +20,17 @@ jobs:
strategy:
fail-fast: false
matrix:
check: [format, lint]
check: [format, lint, basedpyright]
include:
- check: format
name: "Format Check"
command: "uv run ruff format --check ."
command: "uv run ruff format --check src"
- check: lint
name: "Lint Check"
command: "uv run ruff check ."
command: "uv run ruff check src"
- check: basedpyright
name: "Type Check"
command: "uv run basedpyright src"
name: ${{ matrix.name }}

1
.gitignore vendored
View File

@@ -172,3 +172,4 @@ cython_debug/
.python-version
.idea
_version.py

View File

@@ -40,6 +40,25 @@ if __name__ == "__main__":
)
```
For more examples, check out the [examples directory](/examples) which includes:
- Basic slash command setup
- Button interactions
- Modal forms
- Production deployment configurations
## How It Works
Under the hood, Pycord REST creates an HTTP server using FastAPI and Uvicorn that:
1. Listens for incoming Discord interaction requests on your specified endpoint
2. Verifies the request signature using your application's public key
3. Routes the interaction to the appropriate command handler
4. Returns the response back to Discord
Unlike traditional Discord bots that maintain a persistent WebSocket connection to Discord's gateway, HTTP-based bots:
- Only wake up when an interaction is received
- Don't receive real-time events from Discord
## Usage
### Setting up your bot on Discord
@@ -78,8 +97,8 @@ async def button(ctx):
This library works differently than traditional bots because it does not use Discord's WebSocket gateway:
- **No Cache**: Since there's no gateway connection, there's no cache of guilds, channels, users, etc.
- **Limited API Methods**: Many standard Discord.py/py-cord methods that rely on cache won't work properly:
- `app.get_channel()`, `app.get_guild()`, `app.get_user()`
- **Limited API Methods**: Many standard py-cord methods that rely on cache won't work properly:
- `app.get_channel()`, `app.get_guild()`, `app.get_user()`, etc.
- Presence updates
- Voice support
- Member tracking
@@ -94,15 +113,25 @@ app.run(
token="YOUR_BOT_TOKEN",
public_key="YOUR_PUBLIC_KEY",
uvicorn_options={
"host": "0.0.0.0",
"port": 8000,
"log_level": "info",
"host": "0.0.0.0", # Listen on all network interfaces
"port": 8000, # Port to listen on
"log_level": "info", # Uvicorn logging level
# Any valid uvicorn server options
},
health=True # Enable /health endpoint
)
```
### Server Configuration
For Discord to reach your bot, you need a publicly accessible HTTPS URL. Options include:
- Using a VPS with a domain and SSL certificate
- Deploying to a cloud service like Heroku, Railway, or Fly.io
### Health Check
By default, Pycord REST includes a `/health` endpoint that returns a 200 status code. This endpoint is useful for monitoring services like UptimeRobot or health checks.
## Advanced Usage
### Adding Custom FastAPI Routes
@@ -115,6 +144,24 @@ async def custom_endpoint(request: Request):
return {"message": "This is a custom endpoint"}
```
## Development Workflow
For faster development and testing, you can use tunneling tools to expose your local development server:
- **ngrok** - Creates a secure tunnel to your localhost
```bash
# Install ngrok
npm install -g ngrok
# Expose your local server
ngrok http 8000
```
- **Cloudflare Tunnel** - Provides a secure connection to your local server
- **localtunnel** - Simple tunnel service for exposing local endpoints
These tools provide temporary URLs that you can use in the Discord Developer Portal during development, allowing you to test changes quickly without deploying to production.
## Contributing
Contributions are welcome! This project is in early development, so there might be bugs or unexpected behaviors.

49
examples/basic_bot.py Normal file
View File

@@ -0,0 +1,49 @@
# Copyright (c) Paillat-dev
# SPDX-License-Identifier: MIT
"""Basic Discord bot example using Pycord REST.
This is a minimal example showing how to create slash commands.
"""
import os
from pydoc import describe
import discord
from dotenv import load_dotenv
from pycord_rest import App
# Load environment variables from .env file
load_dotenv()
app = App()
# Simple ping command
@app.slash_command(name="ping", description="Responds with pong!")
async def ping(ctx: discord.ApplicationContext) -> None:
await ctx.respond("Pong!")
# Command with parameters
@app.slash_command(name="greet", description="Greets a user")
@discord.option("name", input_type=str, description="The name of the user to greet", required=False)
async def greet(ctx: discord.ApplicationContext, name: str | None = None) -> None:
if name:
await ctx.respond(f"Hello, {name}!")
else:
await ctx.respond(f"Hello, {ctx.author.display_name}!")
# Run the app
if __name__ == "__main__":
app.run(
token=os.environ["DISCORD_TOKEN"],
public_key=os.environ["DISCORD_PUBLIC_KEY"],
uvicorn_options={
"host": "0.0.0.0", # noqa: S104
"port": 8000,
"log_level": "info",
},
)

View File

@@ -0,0 +1,55 @@
# Copyright (c) Paillat-dev
# SPDX-License-Identifier: MIT
"""Example demonstrating how to use buttons with Pycord REST."""
import os
from typing import Any
import discord
from dotenv import load_dotenv
from pycord_rest import App
# Load environment variables from .env file
load_dotenv()
app = App()
class MyView(discord.ui.View):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.add_item(
discord.ui.Button(
style=discord.ButtonStyle.link, label="GitHub", url="https://github.com/Paillat-dev/pycord-rest"
)
)
@discord.ui.button(label="Green", style=discord.ButtonStyle.success)
async def green_button(self, button: "discord.ui.Button[MyView]", interaction: discord.Interaction) -> None:
await interaction.respond("You clicked the green button!", ephemeral=True)
@discord.ui.button(label="Red", style=discord.ButtonStyle.danger)
async def red_button(self, button: "discord.ui.Button[MyView]", interaction: discord.Interaction) -> None:
await interaction.respond("You clicked the red button!", ephemeral=True)
# Create a slash command that shows buttons
@app.slash_command(name="buttons", description="Shows interactive buttons")
async def buttons(ctx: discord.ApplicationContext) -> None:
# Create a view with buttons
view = MyView()
await ctx.respond("Choose a button:", view=view)
if __name__ == "__main__":
app.run(
token=os.environ["DISCORD_TOKEN"],
public_key=os.environ["DISCORD_PUBLIC_KEY"],
uvicorn_options={
"host": "0.0.0.0", # noqa: S104
"port": 8000,
"log_level": "info",
},
)

63
examples/modal_example.py Normal file
View File

@@ -0,0 +1,63 @@
# Copyright (c) Paillat-dev
# SPDX-License-Identifier: MIT
"""Example showing how to work with modals in Pycord REST."""
import asyncio
import os
from typing import Any
import discord
from dotenv import load_dotenv
from pycord_rest import App
# Load environment variables from .env file
load_dotenv()
app = App()
class MyModal(discord.ui.Modal):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(
discord.ui.InputText(
label="Name", placeholder="Enter your name", style=discord.InputTextStyle.short, custom_id="name_input"
),
discord.ui.InputText(
label="Feedback",
placeholder="Please provide your feedback here...",
style=discord.InputTextStyle.paragraph,
custom_id="feedback_input",
),
*args,
**kwargs,
)
async def callback(self, interaction: discord.Interaction) -> None:
name = self.children[0].value
await interaction.respond(
f"Thank you for your feedback, {name}! Your submission has been received.", ephemeral=True
)
# Command that shows a form modal
@app.slash_command(name="feedback", description="Submit feedback through a form")
async def feedback(ctx: discord.ApplicationContext) -> None:
# Create a modal
modal = MyModal(title="Feedback Form")
await ctx.send_modal(modal)
await ctx.respond("Opening feedback form...", ephemeral=True)
if __name__ == "__main__":
app.run(
token=os.environ["DISCORD_TOKEN"],
public_key=os.environ["DISCORD_PUBLIC_KEY"],
uvicorn_options={
"host": "0.0.0.0", # noqa: S104
"port": 8000,
"log_level": "info",
},
)

View File

@@ -1,12 +1,21 @@
[project]
name = "pycord-rest-bot"
version = "0.1.0"
dynamic = ["version", "urls"]
description = "A discord rest-bot wrapper for pycord"
readme = "README.md"
authors = [
{ name = "Paillat-dev", email = "me@paillat.dev" }
]
license = "MIT"
requires-python = "==3.12.*"
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.12"
]
keywords = ["discord", "bot", "rest", "pycord"]
dependencies = [
"fastapi>=0.115.11",
"orjson>=3.10.15",
@@ -15,7 +24,6 @@ dependencies = [
"uvicorn>=0.34.0",
]
[dependency-groups]
dev = [
"basedpyright>=1.28.1",
@@ -24,18 +32,45 @@ dev = [
]
[build-system]
requires = ["hatchling"]
requires = ["hatchling", "hatch-vcs"]
build-backend = "hatchling.build"
[tool.hatch.version]
source = "vcs"
[tool.hatch.build.hooks.vcs]
version-file = "src/pycord_rest/_version.py"
[tool.hatch.metadata.hooks.vcs.urls]
Homepage = "https://github.com/Paillat-dev/pycord-rest"
source_archive = "https://github.com/Paillat-dev/pycord-rest/archive/{commit_hash}.zip"
[tool.hatchling]
name = "pycord-rest-bot"
[tool.hatch.build]
include = [
"src/pycord_rest/",
]
exclude = [
".copywrite.hcl",
".github",
".python-version",
"uv.lock",
]
[tool.hatch.build.targets.wheel]
packages = ["src/pycord_rest"]
[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "all"
reportUnusedCallResult = false
reportAny = false
executionEnvironments = [
{ root = "src/pycord_rest/_version.py", reportDeprecated = false },
{ root = "examples", reportExplicitAny = false, reportUnknownMemberType = false, reportUnusedParameter = false, reportImplicitOverride = false }
]
[tool.ruff]
target-version = "py312"
@@ -44,20 +79,18 @@ indent-width = 4
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false
line-ending = "auto"
docstring-code-format = false
docstring-code-line-length = "dynamic"
exclude = [
"src/pycord_rest/_version.py"
]
[tool.ruff.lint]
select = ["ALL"]
per-file-ignores = {}
per-file-ignores = { "examples/**/*" = ["INP001", "ARG002"] }
extend-ignore = [
"N999",
"D104",
@@ -85,6 +118,3 @@ extend-ignore = [
"PLR0913",
"C901"
]
[tool.uv.workspace]
members = ["test"]

View File

@@ -1,6 +1,8 @@
# Copyright (c) Paillat-dev
# SPDX-License-Identifier: MIT
from discord import * # noqa: F403, I001 # pyright: ignore [reportWildcardImportFromLibrary]
from .app import App
__all__ = ["App"]
Bot = App
__all__ = ["App", "Bot"]

View File

@@ -10,7 +10,6 @@ import aiohttp
import discord
import uvicorn
from discord import Interaction, InteractionType
from discord.ui.view import ViewStore
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request
from fastapi.exceptions import FastAPIError
from nacl.exceptions import BadSignatureError
@@ -19,34 +18,10 @@ from nacl.signing import VerifyKey
logger = logging.getLogger("pycord.rest")
async def _dispatch_view(view_store: ViewStore, component_type: int, custom_id: str, interaction: Interaction) -> None:
# Code taken from ViewStore.dispatch
view_store._ViewStore__verify_integrity() # noqa: SLF001 # pyright: ignore [reportUnknownMemberType, reportAttributeAccessIssue]
message_id: int | None = interaction.message and interaction.message.id
key = (component_type, message_id, custom_id)
value = view_store._views.get(key) or view_store._views.get( # pyright: ignore [reportUnknownVariableType, reportUnknownMemberType, reportPrivateUsage] # noqa: SLF001
(component_type, None, custom_id)
)
if value is None:
return
view, item = value # pyright: ignore [reportUnknownVariableType]
item.refresh_state(interaction)
# Code taken from View._dispatch_item
if view._View__stopped.done(): # noqa: SLF001 # pyright: ignore [reportAttributeAccessIssue, reportUnknownMemberType]
return
if interaction.message:
view.message = interaction.message
await view._scheduled_task(item, interaction) # noqa: SLF001 # pyright: ignore [reportPrivateUsage, reportUnknownMemberType]
class App(discord.Bot):
def __init__(self, *args: Any, **options: Any) -> None: # pyright: ignore [reportExplicitAny]
super().__init__(*args, **options) # pyright: ignore [reportUnknownMemberType]
self.app: FastAPI = FastAPI()
self.app: FastAPI = FastAPI(openapi_url=None, docs_url=None, redoc_url=None)
self.router: APIRouter = APIRouter()
self.public_key: str | None = None
@@ -89,22 +64,31 @@ class App(discord.Bot):
raise HTTPException(status_code=401, detail="Invalid request signature") from e
async def _process_interaction(self, request: Request) -> dict[str, Any]: # pyright: ignore [reportExplicitAny]
# Code taken from ConnectionState.parse_interaction_create
data = await request.json()
interaction = Interaction(data=data, state=self._connection)
if data["type"] == 3: # interaction component
custom_id: str = interaction.data["custom_id"] # pyright: ignore [reportGeneralTypeIssues, reportOptionalSubscript, reportUnknownVariableType]
component_type = interaction.data["component_type"] # pyright: ignore [reportGeneralTypeIssues, reportOptionalSubscript, reportUnknownVariableType]
await self._dispatch_view(component_type, custom_id, interaction) # pyright: ignore [reportUnknownArgumentType]
if interaction.type == InteractionType.modal_submit:
user_id, custom_id = ( # pyright: ignore [reportUnknownVariableType]
interaction.user.id, # pyright: ignore [reportOptionalMemberAccess]
interaction.data["custom_id"], # pyright: ignore [reportGeneralTypeIssues, reportOptionalSubscript]
)
await self._connection._modal_store.dispatch(user_id, custom_id, interaction) # pyright: ignore [reportUnknownArgumentType, reportPrivateUsage] # noqa: SLF001
await self.process_application_commands(interaction)
match interaction.type:
case InteractionType.component:
custom_id: str = interaction.data["custom_id"] # pyright: ignore [reportGeneralTypeIssues, reportOptionalSubscript, reportUnknownVariableType]
component_type = interaction.data["component_type"] # pyright: ignore [reportGeneralTypeIssues, reportOptionalSubscript, reportUnknownVariableType]
await self._dispatch_view(component_type, custom_id, interaction) # pyright: ignore [reportUnknownArgumentType]
case InteractionType.modal_submit:
user_id, custom_id = ( # pyright: ignore [reportUnknownVariableType]
interaction.user.id, # pyright: ignore [reportOptionalMemberAccess]
interaction.data["custom_id"], # pyright: ignore [reportGeneralTypeIssues, reportOptionalSubscript]
)
await self._connection._modal_store.dispatch(user_id, custom_id, interaction) # pyright: ignore [reportUnknownArgumentType, reportPrivateUsage] # noqa: SLF001
case InteractionType.ping:
return {"type": 1}
case InteractionType.application_command | InteractionType.auto_complete:
await self.process_application_commands(interaction)
self.dispatch("interaction", interaction)
return {"ok": True}
@override
async def on_interaction(self, *args: Never, **kwargs: Never) -> None:
pass
@override
async def process_application_commands( # noqa: PLR0912
self, interaction: Interaction, auto_sync: bool | None = None
@@ -143,8 +127,8 @@ class App(discord.Bot):
return self._bot.dispatch("unknown_application_command", interaction)
if interaction.type is InteractionType.auto_complete:
self._bot.dispatch("application_command_auto_complete", interaction, command)
await super().on_application_command_auto_complete(interaction, command) # pyright: ignore [reportArgumentType, reportUnknownMemberType]
return self._bot.dispatch("application_command_auto_complete", interaction, command)
return None
ctx = await self.get_application_context(interaction)
@@ -212,7 +196,7 @@ class App(discord.Bot):
self,
token: str,
public_key: str,
uvicorn_options: dict[str, Any] | None = None,
uvicorn_options: dict[str, Any] | None = None, # pyright: ignore [reportExplicitAny]
health: bool = True,
) -> None:
await self.login(token)

3
uv.lock generated
View File

@@ -298,8 +298,7 @@ wheels = [
]
[[package]]
name = "pycord-rest"
version = "0.1.0"
name = "pycord-rest-bot"
source = { editable = "." }
dependencies = [
{ name = "fastapi" },