discord-rpc: Documentation


Installation

pip install discord-rpc

Discord desktop app must be running on the same machine.


Getting Application ID

  1. Go to https://discord.com/developers/applications
  2. Click “New Application” if you don’t have application
  3. Insert the name of your application
  4. Copy APPLICATION ID

Quick Start

Step-by-step making simple rich presence using Discord-RPC.

  1. Make sure Discord-RPC is installed.

  2. Import Discord-RPC

    import discordrpc
  3. Make rpc variable from discordrpc.RPC with your unique (Application ID).

    # Change `app_id` to your app id
    rpc = discordrpc.RPC(app_id=1234)
  4. Customizing activity using rpc.set_activity().

    rpc.set_activity(
      state="A super simple rpc",
      details="simple RPC"
    )
  5. Creating loop for rpc so that it can keep running. (Only required if you only run Discord RPC on this file or current instance)

    rpc.run()
  6. Done! Run your file.


API Reference

RPC

class RPC:
    def __init__(...): -> None

RPC.__init__

Creates an IPC client and attempts to connect to the local Discord instance.

Parameters :

  • app_id (int): Your Discord Application (Client) ID.
  • debug (bool, default: False): If True, enables verbose logging (DEBUG).
  • output (bool, default: True): If False, silences logger output.
  • exit_if_discord_close (bool, default: True): If True, raises when Discord is not found or closed.
  • exit_on_disconnect (bool, default: True): If True, exits the process when the socket disconnects.

Variables :

  • is_running (bool): Whether the RPC successfully set an activity.
  • try_reconnecting (bool, default: True): Whether to attempt reconnecting on disconnect.
  • connected (bool, property): Whether the IPC connection to Discord is alive. Read-only alias for self.ipc.connected.
  • User (cached_property): Returns a User object populated after handshake. See User.
  • App (cached_property): Returns an Application object fetched from Discord API. See App.
  • assets (cached_property): Returns an AssetManager containing all uploaded Rich Presence assets. See AssetManager.

RPC.set_activity

def set_activity(...): -> Optional[bool]

Sets or updates the current Rich Presence. Returns True on success.

Parameters (all optional unless stated):

  • name (str): Name of the activity. If not provided, Discord uses the application name.
  • details (str): Upper line of the activity.
  • state (str): Lower line of the activity.
  • act_type (Activity, default: Activity.Playing): See Activity Types.
  • status_type (StatusDisplay, default: StatusDisplay.Name): Which field (name/state/details) is considered the “status name” for some clients.
  • large_image (str or Asset): Key of an uploaded Rich Presence Asset, an Asset from AssetManager, or an external direct URL.
  • large_text (str): Tooltip text when hovering the large image.
  • large_url (str): Optional URL for the large image.
  • small_image (str or Asset): Key of a small asset, an Asset, or an external direct URL.
  • small_text (str): Tooltip for the small image.
  • small_url (str): Optional URL for the small image.
  • state_url, details_url (str): Optional link targets when clicking the text.
  • ts_start, ts_end (int): Unix timestamps (seconds). Use helpers in Utils.
  • party_id (str): ID to identify a party/session.
  • party_size (list[int, int]): Current and max size, e.g. [2, 5].
  • join_secret, spectate_secret, match_secret (str): Secrets for join/spectate/match. See Events.
  • buttons (list[dict]): Up to 2 buttons created by button().
  • clear (bool): If True, clears the activity. Same thing as rpc.clear().

Notes & validation:

  • act_type must be a value of types.Activity; otherwise InvalidActivityType is raised.
  • As of Discord policy, Activity.Streaming and Activity.Custom are disabled for Rich Presence updates and will raise ActivityTypeDisabled.
  • Images can be an uploaded asset key or an external direct URL (PNG, JPEG, WebP, GIF, AVIF).
  • status_type also accepts the plain int value (0, 1, or 2).
  • state and details must be 2 to 128 characters long, otherwise ActivityError is raised.
  • Each button needs a label of 1 to 32 characters and a URL of at most 512 characters, otherwise ButtonError is raised.
  • Discord rejects buttons together with join_secret, spectate_secret, or match_secret, so that combination raises ButtonError.
  • If Discord is not running, DiscordNotOpened may be raised (depending on exit_if_discord_close).

RPC.run()

def run(update_every: int = 1, ping_every: int = 15): -> None

Keeping the RPC alive. Not required if another task is running on the same file.

Parameters :

  • update_every (int, default: 1): Loop sleep interval in seconds.
  • ping_every (int, default: 15): OP_PING heartbeat interval to prevent socket timeout.

Exceptions :

  • KeyboardInterrupt will call RPC.disconnect.

RPC.clear()

def clear(): -> Optional[bool]

Clears the current activity without disconnecting. Returns the same result as set_activity().

RPC.disconnect()

def disconnect(): -> None

Closes the IPC socket, clears subscriptions and callbacks, and marks the client as disconnected. If exit_on_disconnect=True, the process exits after issuing the close command.

RPC.subscribe() / RPC.unsubscribe()

def subscribe(event): -> bool
def unsubscribe(event): -> bool

Subscribe or unsubscribe to a Rich Presence event. See Events.


User

rpc.User  # cached_property, populated after handshake

A lightweight User model of the user to whom the connection occurred.

Attributes :

  • id (int): Discord user ID.
  • username (str): Username.
  • name (str): Global display name.
  • avatar (str): CDN URL (animated GIF detection supported).
  • avatar_decoration (str): CDN URL to the avatar decoration preset, or "" when not set.
  • bot (bool): Whether the user is a bot.
  • premium_type (int): Discord Nitro tier (details).
import discordrpc

rpc = discordrpc.RPC(app_id=123456789)
print(rpc.User.name)
print(f"@{rpc.User.username}")
rpc.run()

App

rpc.App  # cached_property, lazy-loaded from Discord API

An Application model. The HTTP request is lazy-loaded, so it won’t run until rpc.App is accessed for the first time, keeping the RPC initialization fast.

RPC.get_app_info() was removed in 6.0. Use rpc.App directly.

Attributes :

  • id (int): Application ID.
  • name (str): Application name.
  • description (str): Application description.
  • icon (str): CDN URL to the application icon.
  • cover (str): CDN URL to the application cover image, or "" when not set.
  • verified (bool): Whether the application is verified.
  • public (bool or None): Whether the bot is public, or None when Discord does not report it.

AssetManager

rpc.assets  # cached_property, lazy-loaded from Discord API

An AssetManager (subclass of list) containing all uploaded Rich Presence art assets. Fetched once on first access using utils.get_assets().

Methods :

  • assets.get(name: str) -> Asset | None: Returns an Asset by its key name, or None if not found.
  • assets.names (property): Returns a list of all asset names.

Each Asset has these attributes :

  • id (int): Asset ID.
  • name (str): Asset key name (used as large_image / small_image value).
  • type (int): Asset type from Discord.
  • url (str): Full CDN URL to the asset image (PNG, 1024px).
import discordrpc

rpc = discordrpc.RPC(app_id=123456789)

# List all available asset names
print(rpc.assets.names)

# Loop through all assets with their CDN URLs
for asset in rpc.assets:
    print(f"{asset.name}: {asset.url}")

# Set activity using an asset by name
rpc.set_activity(
    state="Assets example",
    large_image=rpc.assets.get("cat")
)

rpc.run()

For basic usage, you can still pass asset key strings directly (e.g. large_image="cat"). The manager is useful when you need to discover assets dynamically or access their CDN URLs.


Buttons

from discordrpc import button

def button(text: str, url: str): -> dict

Creates a Discord-compatible button payload. Discord allows up to 2 buttons per activity.

Button() was renamed to button() in 6.0.

Parameters :

  • text (str): Button label, 1 to 32 characters.
  • url (str): Must be a valid http:// or https:// URL, at most 512 characters. If invalid, raises InvalidURL.

Example


Events

You can subscribe to Rich Presence events and receive callbacks when they fire.

import discordrpc
from discordrpc import Event

rpc = discordrpc.RPC(app_id=123456789)

@rpc.on(Event.JOIN_REQUEST)
def on_join_request(data):
    print("Ask to Join:", data)

rpc.run()

Supported events (from discordrpc.Event) :

  • Event.JOIN (ACTIVITY_JOIN)
  • Event.JOIN_REQUEST (ACTIVITY_JOIN_REQUEST)
  • Event.SPECTATE (ACTIVITY_SPECTATE)
  • Event.INVITE (ACTIVITY_INVITE)

Only these activity events are currently exposed. Other Discord RPC events are not supported yet.

Enabling JOIN and SPECTATE events

  • party_id is required for the “Ask to Join” button and the ACTIVITY_JOIN_REQUEST event to work. Without it, Discord cannot resolve the party, the event is never delivered, and the requester gets “Your message could not be delivered.”
  • join_secret and spectate_secret must have different values. Discord rejects the activity with secrets must be unique when they match.
rpc.set_activity(
    name="VALORANT",
    details="Valorant Ranked",
    party_id=1234,
    join_secret="anything",
    spectate_secret="idk",
)

Direct subscribe and unsubscribe

rpc.subscribe("ACTIVITY_JOIN")        # string form accepted
rpc.subscribe(Event.JOIN)             # enum form accepted
rpc.unsubscribe(Event.JOIN)
  • subscribe() / unsubscribe() accept either an Event member or a valid event string.
  • unsubscribe() returns False when the event is not currently subscribed.
  • An unknown event name raises InvalidEvent, and a non-string, non-enum value raises InvalidEventType.
  • When Discord is closed and exit_if_discord_close=True, both raise DiscordNotOpened.
  • The @rpc.on() decorator raises RPCException if the subscription is rejected by Discord.

Callback behavior

  • Each event’s callbacks run on their own thread, so a callback can safely call set_activity(), subscribe(), or unsubscribe().
  • Callbacks for events that arrive close together can run at the same time. Use locks or queues if your callback touches shared state.
  • Calling disconnect() inside a callback also stops run().
  • An exception raised inside a callback is logged and does not stop the reader.

Disconnect and reconnect

  • disconnect() clears all subscriptions and callbacks.
  • subscribe() and unsubscribe() automatically attempt to reconnect when the pipe is disconnected.
  • Unsubscribing from the last event keeps the connection open, so your presence stays visible.

Utils

from discordrpc import utils

utils.timestamp

def timestamp(): -> int

Returns the current time in epoch timestamp.

Since 7.0 this is a function, not a variable. Use timestamp() instead of timestamp.

utils.date_to_timestamp

def date_to_timestamp(date: str): -> int

Date to timestamp converter.

Parameters :

  • date (str) : a date and time in string with format %d/%m/%Y-%H:%M:%S or day/month/year-hour:minute:second. Example :

    date_to_timestamp('14/06/2025-00:00:00')

utils.use_local_time

def use_local_time(): -> dict

Returns a ts_start payload starting from midnight today.

utils.progress_bar

def progress_bar(current: int, duration: int): -> dict

Simplified ts_start and ts_end payload in RPC.set_activity.

Parameters :

  • current (int)
  • duration (int)

Return : Payload dict of ts_start and ts_end.

Raises ProgressbarError if current is negative, duration is zero or negative, or current > duration.

utils.get_app_info

def get_app_info(app_id: int): -> dict

Fetch application info standalone without initializing RPC class.

Parameters :

  • app_id (int or str): Your Discord Application ID.

Return : Payload dict containing application details directly from Discord API.

utils.get_assets

def get_assets(app_id: int): -> list

Fetch all uploaded Rich Presence assets without initializing RPC class. Returns a list of asset dicts with id, name, and type keys.

utils.valid_url

def valid_url(url): -> str

Validates an optional URL. Returns the URL unchanged if valid, or None if not provided. Raises InvalidURL if the URL is not a valid http:// or https:// URL.

utils.required_url

def required_url(url): -> str

Validates a required URL. Raises InvalidURL if missing or not a valid http:// or https:// URL. Used by set_activity() to validate button URLs.

utils.remove_none

def remove_none(d: dict): -> dict

Recursively removes None values and empty dicts from a dict.


Types

Activity Types

from discordrpc import Activity

Types Streaming and Custom are currently disabled from Discord itself.

Attributes :

  • Activity.Playing (0)
  • Activity.Streaming (1)
  • Activity.Listening (2)
  • Activity.Watching (3)
  • Activity.Custom (4)
  • Activity.Competing (5)

Status Display Types

from discordrpc import StatusDisplay

Attributes :

  • StatusDisplay.Name (0)
  • StatusDisplay.State (1)
  • StatusDisplay.Details (2)

Exceptions

All exceptions extend RPCException.

ExceptionDescription
RPCExceptionBase exception
Error(message)Generic user error
DiscordNotOpened()Discord not found/running
ActivityError(message)Invalid activity payload, such as state or details outside 2 to 128 characters
InvalidURL(message)URL is not a valid http/https URL
InvalidID()Invalid Application ID
ButtonError(message)More than 2 buttons, bad label or URL length, or buttons combined with secrets
ProgressbarError(message)Invalid progress values
InvalidActivityType(message)act_type is not a valid Activity
ActivityTypeDisabled()Streaming/Custom blocked by Discord
InvalidEvent(message)Event name is not subscribable
InvalidEventType(message)Event input is not a string or Event

Catch RPCException if you want to handle all library errors.


Examples

Basic presence

import discordrpc

rpc = discordrpc.RPC(app_id=12345678910)

rpc.set_activity(
      state="A super simple rpc",
      details="simple RPC"
    )

rpc.run()

Presence with buttons

import discordrpc
from discordrpc import button

buttons = [
    button("Repository", "https://github.com/Senophyx/discord-rpc"),
    button("Discord", "https://discord.gg/qpT2AeYZRN"),
]

rpc = discordrpc.RPC(app_id=1234567891011)

rpc.set_activity(
      state="Made by Senophyx",
      details="Discord-RPC",
      buttons=buttons
    )


rpc.run()

More examples can be found here.


Troubleshooting

  • “Discord is closed” / could not find IPC: Ensure the desktop app is open. On Linux, confirm $XDG_RUNTIME_DIR or /tmp contains discord-ipc-* sockets. Flatpak Discord is also detected.
  • ActivityTypeDisabled: Discord no longer accepts Streaming and Custom via Rich Presence updates. Use Playing, Listening, Watching, or Competing instead.
  • Buttons don’t show: You can only have up to 2 buttons. All URLs must begin with http:// or https://.
  • No images appear: Upload assets to the Art Assets section of your application and reference their keys, not file paths.
  • App exits on disconnect: Set exit_on_disconnect=False when creating RPC if you prefer to handle disconnects yourself.
  • Silence logs: Pass output=False to RPC(...) to disable log output.
  • Handshake timed out: Discord did not answer within 30 seconds. Restarting Discord usually helps.

FAQ

Q: Do I need a bot token?
A: No. This library communicates locally with the Discord client via IPC; only an Application ID is needed.

Q: Can I update the presence from a server?
A: No. This is a client-side integration; the user’s Discord app must run on the same machine.

Q: Can I use streaming or custom activity?
A: Those types are disabled for RPC updates and raise ActivityTypeDisabled.


Discord-RPC project is under MIT License.
Copyright (c) 2021-2025 Senophyx.