discord-rpc: Documentation
Installation
pip install discord-rpcDiscord desktop app must be running on the same machine.
Getting Application ID
- Go to https://discord.com/developers/applications
- Click “New Application” if you don’t have application
- Insert the name of your application
- Copy
APPLICATION ID
Quick Start
Step-by-step making simple rich presence using Discord-RPC.
Make sure Discord-RPC is installed.
Import Discord-RPC
import discordrpcMake
rpcvariable fromdiscordrpc.RPCwith your unique (Application ID).# Change `app_id` to your app id rpc = discordrpc.RPC(app_id=1234)Customizing activity using
rpc.set_activity().rpc.set_activity( state="A super simple rpc", details="simple RPC" )Creating loop for
rpcso that it can keep running. (Only required if you only run Discord RPC on this file or current instance)rpc.run()Done! Run your file.
API Reference
RPC
class RPC:
def __init__(...): -> NoneRPC.__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): IfTrue, enables verbose logging (DEBUG). - output (bool, default:
True): IfFalse, silences logger output. - exit_if_discord_close (bool, default:
True): IfTrue, raises when Discord is not found or closed. - exit_on_disconnect (bool, default:
True): IfTrue, 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
Userobject populated after handshake. See User. - App (cached_property): Returns an
Applicationobject fetched from Discord API. See App. - assets (cached_property): Returns an
AssetManagercontaining 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
Assetfrom 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 asrpc.clear().
Notes & validation:
act_typemust be a value oftypes.Activity; otherwiseInvalidActivityTypeis raised.- As of Discord policy,
Activity.StreamingandActivity.Customare disabled for Rich Presence updates and will raiseActivityTypeDisabled. - Images can be an uploaded asset key or an external direct URL (PNG, JPEG, WebP, GIF, AVIF).
status_typealso accepts the plain int value (0,1, or2).stateanddetailsmust be 2 to 128 characters long, otherwiseActivityErroris raised.- Each button needs a label of 1 to 32 characters and a URL of at most 512 characters, otherwise
ButtonErroris raised. - Discord rejects buttons together with
join_secret,spectate_secret, ormatch_secret, so that combination raisesButtonError. - If Discord is not running,
DiscordNotOpenedmay be raised (depending onexit_if_discord_close).
RPC.run()
def run(update_every: int = 1, ping_every: int = 15): -> NoneKeeping 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 :
KeyboardInterruptwill callRPC.disconnect.
RPC.clear()
def clear(): -> Optional[bool]Clears the current activity without disconnecting. Returns the same result as set_activity().
RPC.disconnect()
def disconnect(): -> NoneCloses 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): -> boolSubscribe or unsubscribe to a Rich Presence event. See Events.
User
rpc.User # cached_property, populated after handshakeA 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 APIAn 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. Userpc.Appdirectly.
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
Nonewhen Discord does not report it.
AssetManager
rpc.assets # cached_property, lazy-loaded from Discord APIAn 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 anAssetby its key name, orNoneif 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_imagevalue). - 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): -> dictCreates a Discord-compatible button payload. Discord allows up to 2 buttons per activity.
Button()was renamed tobutton()in 6.0.
Parameters :
- text (str): Button label, 1 to 32 characters.
- url (str): Must be a valid
http://orhttps://URL, at most 512 characters. If invalid, raisesInvalidURL.
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_idis required for the “Ask to Join” button and theACTIVITY_JOIN_REQUESTevent 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_secretandspectate_secretmust have different values. Discord rejects the activity withsecrets must be uniquewhen 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 anEventmember or a valid event string.unsubscribe()returnsFalsewhen the event is not currently subscribed.- An unknown event name raises
InvalidEvent, and a non-string, non-enum value raisesInvalidEventType. - When Discord is closed and
exit_if_discord_close=True, both raiseDiscordNotOpened. - The
@rpc.on()decorator raisesRPCExceptionif 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(), orunsubscribe(). - 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 stopsrun(). - An exception raised inside a callback is logged and does not stop the reader.
Disconnect and reconnect
disconnect()clears all subscriptions and callbacks.subscribe()andunsubscribe()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 utilsutils.timestamp
def timestamp(): -> intReturns the current time in epoch timestamp.
Since 7.0 this is a function, not a variable. Use
timestamp()instead oftimestamp.
utils.date_to_timestamp
def date_to_timestamp(date: str): -> intDate to timestamp converter.
Parameters :
date (
str) : a date and time in string with format%d/%m/%Y-%H:%M:%Sorday/month/year-hour:minute:second. Example :date_to_timestamp('14/06/2025-00:00:00')
utils.use_local_time
def use_local_time(): -> dictReturns a ts_start payload starting from midnight today.
utils.progress_bar
def progress_bar(current: int, duration: int): -> dictSimplified 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): -> dictFetch application info standalone without initializing RPC class.
Parameters :
- app_id (
intorstr): Your Discord Application ID.
Return : Payload dict containing application details directly from Discord API.
utils.get_assets
def get_assets(app_id: int): -> listFetch 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): -> strValidates 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): -> strValidates 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): -> dictRecursively removes None values and empty dicts from a dict.
Types
Activity Types
from discordrpc import ActivityTypes 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 StatusDisplayAttributes :
StatusDisplay.Name(0)StatusDisplay.State(1)StatusDisplay.Details(2)
Exceptions
All exceptions extend RPCException.
| Exception | Description |
|---|---|
RPCException | Base 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
RPCExceptionif 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_DIRor/tmpcontainsdiscord-ipc-*sockets. Flatpak Discord is also detected. ActivityTypeDisabled: Discord no longer acceptsStreamingandCustomvia Rich Presence updates. UsePlaying,Listening,Watching, orCompetinginstead.- Buttons don’t show: You can only have up to 2 buttons. All URLs must begin with
http://orhttps://. - 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=Falsewhen creatingRPCif you prefer to handle disconnects yourself. - Silence logs: Pass
output=FalsetoRPC(...)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.
Links
Licence & Copyright
Discord-RPC project is under MIT License.
Copyright (c) 2021-2025 Senophyx.