Skip to main content

A minimalist python client for the Discord API

Project description

SmallD.py

PyPI version Build Maintainability Discord

SmallD aims to be a minmalist client for the Discord API. It aims to let you use the Discord API, without hiding or abstracting it.

Table of Contents

Installing

SmallD can be install from pip.

$ pip install smalld

Getting Started

After installing SmallD, and we have a bot token for discord, we can get started on making a bot. This section will guide you through the creation of a Ping bot. When someone types "++ping", it will respond with "pong".

To begin with, we import the SmallD class and create an instance of it.

from smalld import SmallD

smalld = SmallD()

This is also where we could set the bot token or other configuration options. By default the bot token will be read from the environment variable SMALLD_TOKEN. We will set that when running our bot later.

Next, we want to add the ability to respond to messages. To do this we want to listen for message create events from discord, and then send a response if we received "++ping". We do receive events by using a decorator on a function. We can use different decorators based upon what events we want to list.

@smalld.on_message_create
def on_message(msg):
    pass

Our on_message function will now be called whenever a message create event is sent by discord.

Upon receiving this message we can check for "++ping" as the content by looking at the msg.content property. If it matches, we now send a message back via the appropriate Discord endpoint. For sending messages, this is a POST request to "/channels/{channel.id}/messages". Since we are replaying to the message that was sent, we can get the channel id by using msg.channel_id.

@smalld.on_message_create
def on_message(msg):
    if msg.content == "++ping":
        smalld.post(f"/channels/{msg.channel_id}/messages", {"content": "pong"})

The last step left in our ping bot is to actually run smalld.

smalld.run()

When we actually run our script we will need to make sure we pass the token. We can do this via the command line.

$ SMALLD_TOKEN=<your token here> python ping_bot.py

The full code for the example can be found in (examples/ping_bot.py).

Guide

This section outlines the API provided by SmallD. It does not aim to outline what are valid payloads, events, etc. For that, the Discord developer documentation is always helpful.

Creating and Configuring

smalld.SmallD(
    token=os.environ.get("SMALLD_TOKEN"),
    base_url="https://discord.com/api/v6",
    intents=Intent.all(),
    shard=(0, 1),
)

Creates a SmallD instance using the provided configuration. Intents are passed in using the | operator, for example Intent.GUILD_MESSAGES | Intent.DIRECT_MESSAGES. The shard configuration should be a tuple of (current shard, number of shards).

Running

SmallD.run()

Runs SmallD. Connects to the Gateway, authenticates, and will maintain the connection. It will handle heartbeats and reconnections as necessary.

Gateway Events

@SmallD.on_*
SmallD.on_*(func=None)
@SmallD.on_gateway_payload(op=None, t=None)
SmallD.on_gateway_payload(func=None, *, op=None, t=None)

To listen to events from the Discord gateway use decorators that start with on_. on_gateway_payload can be used to listen for raw payloads, optionally filtering by the op and/or t fields of the payload.

To listen for specific dispatch events, simply use on_ followed by the event you wish to listen for. For example on_message_create for MESSAGE_CREATE events, on_message_reaction_add for MESSAGE_REACTION_ADD events, etc.

SmallD.send_gateway_payload(data)

To send data to the Discord gateway use the send_gateway_payload method.

Resources

SmallD.<http method>(path, payload="", attachments=None, params=None)

SmallD.get(...)
SmallD.post(...)
SmallD.put(...)
SmallD.patch(...)
SmallD.delete(...)

These methods send a request to a discord resource and return the response. All methods support the same parameters. SmallD manages Discord's rate limits, throwing an exception if the rate limit would be broken. An exception is raised on any non-2xx response.

The payload is serialized to JSON before being sent. Typically payload will be passed in as a dict that matches the data expected by the Discord API.

Attachments can be provided as a list of tuples. Each tuple should be (file name, content, mime-type). The file name and mime-type should be strings, with content being a file-like object. An example of sending an attachment can be found in (examples/cat_bot.py).

Query parameters to be set on the request can be passed in params.

Errors

class SmallDError(Exception)
class HttpError(SmallDError)
class NetworkError(SmallDError)
class RateLimitError(SmallDError)

SmallDError is used as a base class for all errors raised by SmallD.

HttpError is raised when a non-2xx response is returned from a resources. The response that caused the error can be accessed via the response attribute.

NetworkError is raised when there is a connectivity or other network related error.

RateLimitError is raised when hitting a Discord imposed rate limit. The reset time of this rate limit (i.e., when the rate limit will no longer apply) is available in the reset attribute.

Contact

Reach out to the Discord Projects Hub on Discord and look for the smalld-py channels.

Contributing

Checkout the issues, and jump right in! If you have any questions, reach out via the details mentioned in Contact.

  • Tox is used for running tests.
    • Run tox -e to run tests with your installed python version
    • Run tox -e fmt to format the code
  • Emoji Log is used for commit messages and pull requests

Developing

Tox is used to setup and manage virtual envs when working on SmallD.py

To run tests:

$ tox

To run examples, ping_bot in this case:

$ tox -e run -- examples/ping_bot.py

Usages

  • Tsktsk: A task list aimed at helping prioritize and categorize your tasks.
  • Tweenie: Add reacts to messages using the power of NLP.
  • SmallD-Click: A command dispatcher for your discord bot combining Click and SmallD.
  • Converse: Anonymous (nameless) chat on discord.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

smalld-0.3.0.tar.gz (23.8 kB view details)

Uploaded Source

Built Distribution

smalld-0.3.0-py3-none-any.whl (13.7 kB view details)

Uploaded Python 3

File details

Details for the file smalld-0.3.0.tar.gz.

File metadata

  • Download URL: smalld-0.3.0.tar.gz
  • Upload date:
  • Size: 23.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.6.1 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.1 CPython/3.6.13

File hashes

Hashes for smalld-0.3.0.tar.gz
Algorithm Hash digest
SHA256 381d534b48b2327791fd88fc4f611e6b08c82653c12bceafb89ccb8130cf209c
MD5 1ec0cf904da2ae4ade25dea89b90aee1
BLAKE2b-256 c8dfcced5da43768059d4521b7b9c834c696e9d52d612fad9325c7639d73f314

See more details on using hashes here.

File details

Details for the file smalld-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: smalld-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 13.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.6.1 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.1 CPython/3.6.13

File hashes

Hashes for smalld-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0c8567537cc25afb4a497bae19768aaf2e317883af34112717bf29d62cf18fc8
MD5 ec01c3a6769f71aa00c3e9fce4c1f219
BLAKE2b-256 b9711f64d2e315d8ca8988a4511158f174f9dfbd7fbcc78a822acd0acb6ab7fd

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page