Orbit Developers

Python

A complete bot using only the standard library. It replies pong to !ping and waves at hello. You'll need Python 3.9 or newer.

Run it

git clone https://github.com/z0roday/OrbitApi.git
cd OrbitApi/examples/python
export ORBIT_TOKEN='1234567890123456789.Qm9...'
python3 bot.py

Then type !ping in a server your bot is in.

How it works

orbit.py is a tiny API client. It adds your token to every request, waits and retries on 429, and raises an OrbitError with status and code when something fails:

from orbit import Orbit, OrbitError

orbit = Orbit(os.environ["ORBIT_TOKEN"])
me = orbit.me()
orbit.send(channel_id, "Hello", reply_to=message_id)
orbit.react(channel_id, message_id, "๐Ÿ‘‹")

orbit.events() reads the event stream and yields (name, data) pairs. bot.py remembers the last message it handled in each channel and only fetches what's new:

for name, data in orbit.events():
    if name == "hello":
        track()
    elif name == "messages":
        catch_up(data["channel_id"])
    elif name in ("guild", "guilds"):
        track()

It also offers /ping and /roll. It registers them when it starts and answers each interaction event with a card:

orbit.set_commands([{"name": "ping", "description": "Checks that the bot is awake"}])

asked = orbit.interaction(data["interaction_id"])
orbit.reply(asked["id"], "", embeds=[{"title": "Pong", "color": 0x5B8DEF}])

When the connection drops, the bot reconnects, waiting a little longer each time, and catches up on what it missed. On 401 it stops, since that means the token was replaced.

Tests

python3 -m unittest

The tests run the client against a small fake API.

Keep it running

Use the systemd setup from the Node.js example, with these two lines instead:

WorkingDirectory=/opt/OrbitApi/examples/python
ExecStart=/usr/bin/python3 -u bot.py