Repository: niveshbirangal/discord-rpc
Branch: master
Commit: 65d1557f0c55
Files: 10
Total size: 25.9 KB
Directory structure:
gitextract_5_3xzlh8/
├── .gitignore
├── AdobeAfterEffects/
│ ├── README.md
│ ├── aftereff.py
│ └── rpc.py
├── AdobeXD/
│ ├── adobexd.py
│ └── rpc.py
├── LICENSE
├── README.md
├── example.py
└── rpc.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
*.idea
*.DS_Store
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
================================================
FILE: AdobeAfterEffects/README.md
================================================
## Output
They can be customized according to the assets.
================================================
FILE: AdobeAfterEffects/aftereff.py
================================================
import rpc
import time
from time import mktime
print("Demo for python-discord-rpc")
client_id = '745944488882602035' # Your application's client ID as a string. (This isn't a real client ID)
rpc_obj = rpc.DiscordIpcClient.for_platform(client_id) # Send the client ID to the rpc module
print("RPC connection successful.")
time.sleep(5)
start_time = mktime(time.localtime())
while True:
activity = {
"state": "Adobe", # anything you like
"details": "Editing", # anything you like
"timestamps": {
"start": start_time
},
"assets": {
"small_text": "Adobe", # anything you like
"small_image": "small", # must match the image key
"large_text": "After Effects", # anything you like
"large_image": "large1" # must match the image key
}
}
rpc_obj.set_activity(activity)
time.sleep(900)
================================================
FILE: AdobeAfterEffects/rpc.py
================================================
# References:
# * https://github.com/devsnek/discord-rpc/tree/master/src/transports/IPC.js
# * https://github.com/devsnek/discord-rpc/tree/master/example/main.js
# * https://github.com/discordapp/discord-rpc/tree/master/documentation/hard-mode.md
# * https://github.com/discordapp/discord-rpc/tree/master/src
# * https://discordapp.com/developers/docs/rich-presence/how-to#updating-presence-update-presence-payload-fields
from abc import ABCMeta, abstractmethod
import json
import logging
import os
import socket
import sys
import struct
import uuid
OP_HANDSHAKE = 0
OP_FRAME = 1
OP_CLOSE = 2
OP_PING = 3
OP_PONG = 4
logger = logging.getLogger(__name__)
class DiscordIpcError(Exception):
pass
class DiscordIpcClient(metaclass=ABCMeta):
"""Work with an open Discord instance via its JSON IPC for its rich presence API.
In a blocking way.
Classmethod `for_platform`
will resolve to one of WinDiscordIpcClient or UnixDiscordIpcClient,
depending on the current platform.
Supports context handler protocol.
"""
def __init__(self, client_id):
self.client_id = client_id
self._connect()
self._do_handshake()
logger.info("connected via ID %s", client_id)
@classmethod
def for_platform(cls, client_id, platform=sys.platform):
if platform == 'win32':
return WinDiscordIpcClient(client_id)
else:
return UnixDiscordIpcClient(client_id)
@abstractmethod
def _connect(self):
pass
def _do_handshake(self):
ret_op, ret_data = self.send_recv({'v': 1, 'client_id': self.client_id}, op=OP_HANDSHAKE)
# {'cmd': 'DISPATCH', 'data': {'v': 1, 'config': {...}}, 'evt': 'READY', 'nonce': None}
if ret_op == OP_FRAME and ret_data['cmd'] == 'DISPATCH' and ret_data['evt'] == 'READY':
return
else:
if ret_op == OP_CLOSE:
self.close()
raise RuntimeError(ret_data)
@abstractmethod
def _write(self, date: bytes):
pass
@abstractmethod
def _recv(self, size: int) -> bytes:
pass
def _recv_header(self) -> (int, int):
header = self._recv_exactly(8)
return struct.unpack(" bytes:
buf = b""
size_remaining = size
while size_remaining:
chunk = self._recv(size_remaining)
buf += chunk
size_remaining -= len(chunk)
return buf
def close(self):
logger.warning("closing connection")
try:
self.send({}, op=OP_CLOSE)
finally:
self._close()
@abstractmethod
def _close(self):
pass
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
def send_recv(self, data, op=OP_FRAME):
self.send(data, op)
return self.recv()
def send(self, data, op=OP_FRAME):
logger.debug("sending %s", data)
data_str = json.dumps(data, separators=(',', ':'))
data_bytes = data_str.encode('utf-8')
header = struct.pack(" (int, "JSON"):
"""Receives a packet from discord.
Returns op code and payload.
"""
op, length = self._recv_header()
payload = self._recv_exactly(length)
data = json.loads(payload.decode('utf-8'))
logger.debug("received %s", data)
return op, data
def set_activity(self, act):
# act
data = {
'cmd': 'SET_ACTIVITY',
'args': {'pid': os.getpid(),
'activity': act},
'nonce': str(uuid.uuid4())
}
self.send(data)
class WinDiscordIpcClient(DiscordIpcClient):
_pipe_pattern = R'\\?\pipe\discord-ipc-{}'
def _connect(self):
for i in range(10):
path = self._pipe_pattern.format(i)
try:
self._f = open(path, "w+b")
except OSError as e:
logger.error("failed to open {!r}: {}".format(path, e))
else:
break
else:
return DiscordIpcError("Failed to connect to Discord pipe")
self.path = path
def _write(self, data: bytes):
self._f.write(data)
self._f.flush()
def _recv(self, size: int) -> bytes:
return self._f.read(size)
def _close(self):
self._f.close()
class UnixDiscordIpcClient(DiscordIpcClient):
def _connect(self):
self._sock = socket.socket(socket.AF_UNIX)
pipe_pattern = self._get_pipe_pattern()
for i in range(10):
path = pipe_pattern.format(i)
if not os.path.exists(path):
continue
try:
self._sock.connect(path)
except OSError as e:
logger.error("failed to open {!r}: {}".format(path, e))
else:
break
else:
return DiscordIpcError("Failed to connect to Discord pipe")
@staticmethod
def _get_pipe_pattern():
env_keys = ('XDG_RUNTIME_DIR', 'TMPDIR', 'TMP', 'TEMP')
for env_key in env_keys:
dir_path = os.environ.get(env_key)
if dir_path:
break
else:
dir_path = '/tmp'
return os.path.join(dir_path, 'discord-ipc-{}')
def _write(self, data: bytes):
self._sock.sendall(data)
def _recv(self, size: int) -> bytes:
return self._sock.recv(size)
def _close(self):
self._sock.close()
================================================
FILE: AdobeXD/adobexd.py
================================================
import rpc
import time
from time import mktime
print("Demo for python-discord-rpc")
client_id = '467310358567190559' # Your application's client ID as a string. (This isn't a real client ID)
rpc_obj = rpc.DiscordIpcClient.for_platform(client_id) # Send the client ID to the rpc module
print("RPC connection successful.")
time.sleep(5)
start_time = mktime(time.localtime())
while True:
activity = {
"state": "Adobe",
"details": "Designing",
"timestamps": {
"start": start_time
},
"assets": {
"small_text": "Adobe",
"small_image": "adobe",
"large_text": "Illustrator",
"large_image": "xd"
}
}
rpc_obj.set_activity(activity)
time.sleep(900)
================================================
FILE: AdobeXD/rpc.py
================================================
# References:
# * https://github.com/devsnek/discord-rpc/tree/master/src/transports/IPC.js
# * https://github.com/devsnek/discord-rpc/tree/master/example/main.js
# * https://github.com/discordapp/discord-rpc/tree/master/documentation/hard-mode.md
# * https://github.com/discordapp/discord-rpc/tree/master/src
# * https://discordapp.com/developers/docs/rich-presence/how-to#updating-presence-update-presence-payload-fields
from abc import ABCMeta, abstractmethod
import json
import logging
import os
import socket
import sys
import struct
import uuid
OP_HANDSHAKE = 0
OP_FRAME = 1
OP_CLOSE = 2
OP_PING = 3
OP_PONG = 4
logger = logging.getLogger(__name__)
class DiscordIpcError(Exception):
pass
class DiscordIpcClient(metaclass=ABCMeta):
"""Work with an open Discord instance via its JSON IPC for its rich presence API.
In a blocking way.
Classmethod `for_platform`
will resolve to one of WinDiscordIpcClient or UnixDiscordIpcClient,
depending on the current platform.
Supports context handler protocol.
"""
def __init__(self, client_id):
self.client_id = client_id
self._connect()
self._do_handshake()
logger.info("connected via ID %s", client_id)
@classmethod
def for_platform(cls, client_id, platform=sys.platform):
if platform == 'win32':
return WinDiscordIpcClient(client_id)
else:
return UnixDiscordIpcClient(client_id)
@abstractmethod
def _connect(self):
pass
def _do_handshake(self):
ret_op, ret_data = self.send_recv({'v': 1, 'client_id': self.client_id}, op=OP_HANDSHAKE)
# {'cmd': 'DISPATCH', 'data': {'v': 1, 'config': {...}}, 'evt': 'READY', 'nonce': None}
if ret_op == OP_FRAME and ret_data['cmd'] == 'DISPATCH' and ret_data['evt'] == 'READY':
return
else:
if ret_op == OP_CLOSE:
self.close()
raise RuntimeError(ret_data)
@abstractmethod
def _write(self, date: bytes):
pass
@abstractmethod
def _recv(self, size: int) -> bytes:
pass
def _recv_header(self) -> (int, int):
header = self._recv_exactly(8)
return struct.unpack(" bytes:
buf = b""
size_remaining = size
while size_remaining:
chunk = self._recv(size_remaining)
buf += chunk
size_remaining -= len(chunk)
return buf
def close(self):
logger.warning("closing connection")
try:
self.send({}, op=OP_CLOSE)
finally:
self._close()
@abstractmethod
def _close(self):
pass
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
def send_recv(self, data, op=OP_FRAME):
self.send(data, op)
return self.recv()
def send(self, data, op=OP_FRAME):
logger.debug("sending %s", data)
data_str = json.dumps(data, separators=(',', ':'))
data_bytes = data_str.encode('utf-8')
header = struct.pack(" (int, "JSON"):
"""Receives a packet from discord.
Returns op code and payload.
"""
op, length = self._recv_header()
payload = self._recv_exactly(length)
data = json.loads(payload.decode('utf-8'))
logger.debug("received %s", data)
return op, data
def set_activity(self, act):
# act
data = {
'cmd': 'SET_ACTIVITY',
'args': {'pid': os.getpid(),
'activity': act},
'nonce': str(uuid.uuid4())
}
self.send(data)
class WinDiscordIpcClient(DiscordIpcClient):
_pipe_pattern = R'\\?\pipe\discord-ipc-{}'
def _connect(self):
for i in range(10):
path = self._pipe_pattern.format(i)
try:
self._f = open(path, "w+b")
except OSError as e:
logger.error("failed to open {!r}: {}".format(path, e))
else:
break
else:
return DiscordIpcError("Failed to connect to Discord pipe")
self.path = path
def _write(self, data: bytes):
self._f.write(data)
self._f.flush()
def _recv(self, size: int) -> bytes:
return self._f.read(size)
def _close(self):
self._f.close()
class UnixDiscordIpcClient(DiscordIpcClient):
def _connect(self):
self._sock = socket.socket(socket.AF_UNIX)
pipe_pattern = self._get_pipe_pattern()
for i in range(10):
path = pipe_pattern.format(i)
if not os.path.exists(path):
continue
try:
self._sock.connect(path)
except OSError as e:
logger.error("failed to open {!r}: {}".format(path, e))
else:
break
else:
return DiscordIpcError("Failed to connect to Discord pipe")
@staticmethod
def _get_pipe_pattern():
env_keys = ('XDG_RUNTIME_DIR', 'TMPDIR', 'TMP', 'TEMP')
for env_key in env_keys:
dir_path = os.environ.get(env_key)
if dir_path:
break
else:
dir_path = '/tmp'
return os.path.join(dir_path, 'discord-ipc-{}')
def _write(self, data: bytes):
self._sock.sendall(data)
def _recv(self, size: int) -> bytes:
return self._sock.recv(size)
def _close(self):
self._sock.close()
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2020 Nivesh Birangal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
Discord RPC
"Discord RPC is a library for interfacing your game with a locally running Discord desktop client"
### Status:
### Requirements:

3.0 and above
### Setup:
clone this to your local device
```bash
git clone https://github.com/niveshbirangal/discord-rpc.git
```
Go to the developer portal and create an application
```bash
https://discord.com/developers/applications
```
Add assets(image) to your application
Select images and clear all fields except PARTY ID and JOIN SECRET
Now go to example.py, put your client id, and change the activity code according to your best fit
```bash
activity = {
"state": "Adobe", # anything you like
"details": "Editing", # anything you like
"timestamps": {
"start": start_time
},
"assets": {
"small_text": "Adobe", # anything you like
"small_image": "adobe", # must match the image key
"large_text": "Illustrator", # anything you like
"large_image": "illustrator" # must match the image key
}
}
```
Make sure your desktop app is running and then run the example.py
```bash
python3 example.py
```
## Roadmap
See the [open issues](https://github.com/niveshbirangal/discord-rpc/issues) for a list of proposed features (and known issues).
## Contributing
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## License
Distributed under the MIT License. See `LICENSE` for more information.
## Connect with me:
[
][website]
[
][linkedin]
[
][instagram]
[
][youtube]
[website]: https://niveshb.com
[youtube]: https://www.youtube.com/channel/UCpwUP_HiOyG_GHluWpQK59g?view_as=subscriber
[instagram]: https://instagram.com/niveshbirangal
[linkedin]: https://linkedin.com/in/niveshbirangal
================================================
FILE: example.py
================================================
import rpc
import time
from time import mktime
print("Demo for python-discord-rpc Adobe illustrator")
client_id = '467570845993271307' # Your application's client ID as a string. (This isn't a real client ID)
rpc_obj = rpc.DiscordIpcClient.for_platform(client_id) # Send the client ID to the rpc module
print("RPC connection successful.")
time.sleep(5)
start_time = mktime(time.localtime())
while True:
activity = {
"state": "Adobe", # anything you like
"details": "Editing", # anything you like
"timestamps": {
"start": start_time
},
"assets": {
"small_text": "Adobe", # anything you like
"small_image": "adobe", # must match the image key
"large_text": "Illustrator", # anything you like
"large_image": "illustrator" # must match the image key
}
}
rpc_obj.set_activity(activity)
time.sleep(900)
================================================
FILE: rpc.py
================================================
# References:
# * https://github.com/devsnek/discord-rpc/tree/master/src/transports/IPC.js
# * https://github.com/devsnek/discord-rpc/tree/master/example/main.js
# * https://github.com/discordapp/discord-rpc/tree/master/documentation/hard-mode.md
# * https://github.com/discordapp/discord-rpc/tree/master/src
# * https://discordapp.com/developers/docs/rich-presence/how-to#updating-presence-update-presence-payload-fields
from abc import ABCMeta, abstractmethod
import json
import logging
import os
import socket
import sys
import struct
import uuid
OP_HANDSHAKE = 0
OP_FRAME = 1
OP_CLOSE = 2
OP_PING = 3
OP_PONG = 4
logger = logging.getLogger(__name__)
class DiscordIpcError(Exception):
pass
class DiscordIpcClient(metaclass=ABCMeta):
"""Work with an open Discord instance via its JSON IPC for its rich presence API.
In a blocking way.
Classmethod `for_platform`
will resolve to one of WinDiscordIpcClient or UnixDiscordIpcClient,
depending on the current platform.
Supports context handler protocol.
"""
def __init__(self, client_id):
self.client_id = client_id
self._connect()
self._do_handshake()
logger.info("connected via ID %s", client_id)
@classmethod
def for_platform(cls, client_id, platform=sys.platform):
if platform == 'win32':
return WinDiscordIpcClient(client_id)
else:
return UnixDiscordIpcClient(client_id)
@abstractmethod
def _connect(self):
pass
def _do_handshake(self):
ret_op, ret_data = self.send_recv({'v': 1, 'client_id': self.client_id}, op=OP_HANDSHAKE)
# {'cmd': 'DISPATCH', 'data': {'v': 1, 'config': {...}}, 'evt': 'READY', 'nonce': None}
if ret_op == OP_FRAME and ret_data['cmd'] == 'DISPATCH' and ret_data['evt'] == 'READY':
return
else:
if ret_op == OP_CLOSE:
self.close()
raise RuntimeError(ret_data)
@abstractmethod
def _write(self, date: bytes):
pass
@abstractmethod
def _recv(self, size: int) -> bytes:
pass
def _recv_header(self) -> (int, int):
header = self._recv_exactly(8)
return struct.unpack(" bytes:
buf = b""
size_remaining = size
while size_remaining:
chunk = self._recv(size_remaining)
buf += chunk
size_remaining -= len(chunk)
return buf
def close(self):
logger.warning("closing connection")
try:
self.send({}, op=OP_CLOSE)
finally:
self._close()
@abstractmethod
def _close(self):
pass
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
def send_recv(self, data, op=OP_FRAME):
self.send(data, op)
return self.recv()
def send(self, data, op=OP_FRAME):
logger.debug("sending %s", data)
data_str = json.dumps(data, separators=(',', ':'))
data_bytes = data_str.encode('utf-8')
header = struct.pack(" (int, "JSON"):
"""Receives a packet from discord.
Returns op code and payload.
"""
op, length = self._recv_header()
payload = self._recv_exactly(length)
data = json.loads(payload.decode('utf-8'))
logger.debug("received %s", data)
return op, data
def set_activity(self, act):
# act
data = {
'cmd': 'SET_ACTIVITY',
'args': {'pid': os.getpid(),
'activity': act},
'nonce': str(uuid.uuid4())
}
self.send(data)
class WinDiscordIpcClient(DiscordIpcClient):
_pipe_pattern = R'\\?\pipe\discord-ipc-{}'
def _connect(self):
for i in range(10):
path = self._pipe_pattern.format(i)
try:
self._f = open(path, "w+b")
except OSError as e:
logger.error("failed to open {!r}: {}".format(path, e))
else:
break
else:
return DiscordIpcError("Failed to connect to Discord pipe")
self.path = path
def _write(self, data: bytes):
self._f.write(data)
self._f.flush()
def _recv(self, size: int) -> bytes:
return self._f.read(size)
def _close(self):
self._f.close()
class UnixDiscordIpcClient(DiscordIpcClient):
def _connect(self):
self._sock = socket.socket(socket.AF_UNIX)
pipe_pattern = self._get_pipe_pattern()
for i in range(10):
path = pipe_pattern.format(i)
if not os.path.exists(path):
continue
try:
self._sock.connect(path)
except OSError as e:
logger.error("failed to open {!r}: {}".format(path, e))
else:
break
else:
return DiscordIpcError("Failed to connect to Discord pipe")
@staticmethod
def _get_pipe_pattern():
env_keys = ('XDG_RUNTIME_DIR', 'TMPDIR', 'TMP', 'TEMP')
for env_key in env_keys:
dir_path = os.environ.get(env_key)
if dir_path:
break
else:
dir_path = '/tmp'
return os.path.join(dir_path, 'discord-ipc-{}')
def _write(self, data: bytes):
self._sock.sendall(data)
def _recv(self, size: int) -> bytes:
return self._sock.recv(size)
def _close(self):
self._sock.close()