Giter VIP home page Giter VIP logo

pypresence's Introduction

A Discord Rich Presence Client in Python? Looks like you've come to the right place.

GitHub stars license GitHub last commit GitHub top language PyPI

NOTE: Only Python versions 3.8 and above are supported.


Use this badge in your project's Readme to show you're using pypresence! The markdown code is below.

pypresence

[![pypresence](https://img.shields.io/badge/using-pypresence-00bb88.svg?style=for-the-badge&logo=discord&logoWidth=20)](https://github.com/qwertyquerty/pypresence)

Installation

Install pypresence with pip

For the latest development version:

pip install https://github.com/qwertyquerty/pypresence/archive/master.zip

For the latest stable version:

pip install pypresence


Documentation

Note

You need an authorized app to do anything besides rich presence!


Examples

Examples can be found in the examples directory, and you can contribute your own examples if you wish, just read examples.md!


Written by: qwertyquerty

Notable Contributors: GiovanniMCMXCIX, GhostofGoes

pypresence's People

Contributors

2qar avatar ahappyconstant avatar ahhj93 avatar brostosjoined avatar cclauss avatar cheddar-cheeze avatar davispuh avatar failspy avatar flibitijibibo avatar frazew avatar gasinvein avatar ghostofgoes avatar hunter2809 avatar iamjsd avatar ioistired avatar jaymehoward avatar jess-sio avatar josemanrod avatar mcmi460 avatar mgfcf avatar nikoverflow avatar noeppi-noeppi avatar pandaninjas avatar qwertyquerty avatar thespookycat avatar theuntraceable avatar tusky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pypresence's Issues

Cannot create Client() due to lack of redirect URI

Issue

Can't connect over RPC to access the Discord API, as data sent in Client.authorize() does not contain a URL to redirect to.

Platform / Dependencies

Ubuntu 18.04.2 LTS
Python 3.6.7
pypresence 3.3.1

Steps to reproduce

Run the following code

from pypresence import Client
client_id = "replaceme"
client = Client(client_id)
client.start()
client.authorize(client_id, scopes=["rpc", "rpc.api"]) # this throws a ServerError exception

This will cause the following error to be thrown:

pypresence.exceptions.ServerError: Oauth2 error: invalid_request: missing redirect uri.

Discord sends back the same error as above, with a status code of 5000.

Attempts to fix
I tried manually adding the data URL when being sent by modifying the BaseClient class, however the discord client still didn't like this, as I believe you need to manually modify the HTTP headers. This seemed a bit to wild for me at this point, as I didn't want to unintentionally break any other features without making an issue first.

Users data

How i get user data from Presence? the data is written on the console but I don't know how to access it.

Loop already running

Hi there.
I'm passing my own asyncio.ProactorEventLoop() to pypresence.Presence(), connecting and updating the RPC. After that I call a coroutine in the event loop that uses rpc.update() and I'm getting the error RuntimeError: This event loop is already running. Why is that, and how do I fix it?

My code, stripped down to the necessary stuff:

loop = asyncio.ProactorEventLoop()
rpc = pypresence.Presence(client_id, loop=loop)
rpc.connect()
rpc.update(state='Test')
rpc.clear()
asyncio.set_event_loop(loop)

async def api():
    # doing some api calls here

async def set_presence(parameters):
    rpc.update(state='Test')

async def main():
    parameters = await api()
    await set_presence(parameters)
    await asyncio.sleep(15)

if __name__ == '__main__':
    loop.run_until_complete(main())
    rpc.close()
    loop.close()

I dont quite get how to add the loop to the RPC.

Presence#update does nothing on the new Discord client

i'm hoping this is just a matter of me being blind and missing something, but i'm currently unable to get pypresence to actually display anything on Linux or Windows.

minimal script to reproduce:

from pypresence import Presence
from time import sleep
from sys import exit

RPC = Presence('440997014315204609')
RPC.connect()
print("Sending update")
RPC.update(state='Hello', details='World')

while True:
    print("Sleeping...")
    try:
        sleep(15)
    except KeyboardInterrupt as e:
        RPC.close()
        print("RPC closed")
        exit(0)

i'm using virtualenv so it's a controlled environment in terms of python libs installed & python version used. my environment:

  • Arch Linux (Kernel version 5.7.12)
    • Python 3.8.5 / 3.6.11 (tried both)
    • pypresence 3.2.2 / 4.0.0 (tried both, with both versions of python)
    • Discord 0.0.11 (the new client as of a few days ago)
  • Windows 10
    • Python 3.7.4
    • pypresence 4.0.0
    • Latest Discord client (forgot to check version)

i'm hoping i'm wrong but i'm thinking maybe it's something changed with the new Discord client. it connects just fine, throws no errors when calling RPC.update, and in all senses seems to work just fine. the only problem being... no rich presence:

image

I've also tried a different client ID using a fresh Discord app in the developers portal, but no dice. same problem, it just doesn't update anything at all it seems.

I'm also not the only one unable to get this to work, I have a simple program using pypresence called discord-rpc-mpris that is currently nonfunctional because of this. that's actually how this issue came to my attention, as a user tried to install discord-rpc-mpris, and it did nothing

RPC Update Requires all Inputs

When I use the example code from examples, (
RPC.update(state="Lookie Lookie", details="A test of qwertyquerty's Python Discord RPC wrapper, pypresence!")
), I get the error

Traceback (most recent call last):
File "/Users/user1/Documents/gameplaying.py", line 8, in
print(RPC.update(state="Lookie Lookie", details="A test of qwertyquerty's Python Discord RPC wrapper, pypresence!")) # Set the presence
File "/usr/local/lib/python3.6/site-packages/pypresence/presence.py", line 31, in update
return self.loop.run_until_complete(self.read_output())
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete
return future.result()
File "/usr/local/lib/python3.6/site-packages/pypresence/baseclient.py", line 82, in read_output
raise ServerError(payload["data"]["message"])
pypresence.exceptions.ServerError: Child "activity" fails because child "timestamps" fails because child "start" fails because "start" must be a number

When I specify start, it asks for another requirement.

(I Don't know if this is a bug or not, please tell me)

Adding a project

I have a project that uses pypresence, Astolfo. Should I make a pull request, or do you want to just add it to the list?

Error while running code.

I tried to use it and i got this error:

Traceback (most recent call last):
  File "C:\Users\azerb\Desktop\pypresence-master\examples\rich-presence.py", line 8, in <module>
    RPC.update(state="Developing", details="In VSCode!")
  File "C:\Users\azerb\Desktop\pypresence-master\examples\pypresence\presence.py", line 32, in update
    return self.loop.run_until_complete(self.read_output())
  File "C:\Users\azerb\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 608, in run_until_complete
    return future.result()
  File "C:\Users\azerb\Desktop\pypresence-master\examples\pypresence\baseclient.py", line 105, in read_output
    status_code, length = struct.unpack('<II', data[:8])
struct.error: unpack requires a buffer of 8 bytes

what do i do?

If i closing RPC terminal typing me error.

If i closing RPC terminal typing me this error:
Traceback (most recent call last): File "startgui.pyw", line 79, in StopRPC RPC.close() File "C:\Users\Dom\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypresence\presence.py", line 43, in close self.send_data(2, {'v': 1, 'client_id': self.client_id}) File "C:\Users\Dom\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypresence\baseclient.py", line 93, in send_data self.sock_writer.write( AttributeError: 'NoneType' object has no attribute 'write'
Python version 3.6.8 .

Random error popping up on my friends pc

We have the same code and everything, but he gets an error when running it that i dont.

Traceback

C:\Users\robin\Desktop\devio>python main.py
Exception in callback _ProactorReadPipeTransport._loop_reading(<_OverlappedF...5781250000"}'>)
handle: <Handle _ProactorReadPipeTransport._loop_reading(<_OverlappedF...5781250000"}'>)>
Traceback (most recent call last):
  File "C:\Users\robin\AppData\Local\Programs\Python\Python37\lib\asyncio\events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "C:\Users\robin\AppData\Local\Programs\Python\Python37\lib\asyncio\proactor_events.py", line 293, in _loop_reading
    self._data_received(data)
  File "C:\Users\robin\AppData\Local\Programs\Python\Python37\lib\asyncio\proactor_events.py", line 244, in _data_received
    self._protocol.data_received(data)
  File "C:\Users\robin\AppData\Local\Programs\Python\Python37\lib\asyncio\streams.py", line 257, in data_received
    self._stream_reader.feed_data(data)
  File "C:\Users\robin\AppData\Local\Programs\Python\Python37\lib\site-packages\pypresence\client.py", line 56, in on_event
    raise DiscordError(payload["data"]["code"], payload["data"]["message"])
pypresence.exceptions.DiscordError: Error Code: 5000 Message: OAuth2 Error: invalid_scope: The requested scope is invalid, unknown, or malformed.
Traceback (most recent call last):
File "main.py", line 6, in <module>
    sharing.connect()
  File "C:\Users\robin\Desktop\devio\sharing.py", line 17, in connect
    client.authorize(ID, ["rpc"])
  File "C:\Users\robin\AppData\Local\Programs\Python\Python37\lib\site-packages\pypresence\client.py", line 61, in authorize
    return self.loop.run_until_complete(self.read_output())
  File "C:\Users\robin\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 573, in run_until_complete
    return future.result()
  File "C:\Users\robin\AppData\Local\Programs\Python\Python37\lib\site-packages\pypresence\baseclient.py", line 86, in read_output
    raise ServerError(payload["data"]["message"])
pypresence.exceptions.ServerError: Oauth2 error: invalid_scope: the requested scope is invalid, unknown, or malformed.

Part of the code thats causing the issue:

    client.authorize(ID, ["rpc"])

Invalid syntax error.

I starting my app.
Terminal typing me this error:
Traceback (most recent call last): File "main.py", line 2, in <module> from pypresence import Presence File "C:\Users\Dom\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pypresence\__init__.py", line 7, in <module> from .activity import Activity File "C:\Users\Dom\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pypresence\activity.py", line 5, in <module> from .presence import Presence File "C:\Users\Dom\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pypresence\presence.py", line 5, in <module> from .baseclient import BaseClient File "C:\Users\Dom\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pypresence\baseclient.py", line 31 self.ipc_path = f'{tempdir}/{pipe_file}'
And this error in all apps.
I using python 3.5.4

Bug: Brokenpipeerror when closing discord

Hello, if I start discord, start my program that uses pypresence, close discord and reopen it, try to change my rich presence, it crashes with this error message [I tried to make a try: except: around it, it seems to be ignored]:

Traceback (most recent call last):
  File "/home/user/.local/lib/python3.8/site-packages/pypresence/baseclient.py", line 99, in read_output
    data = await self.sock_reader.read(1024)
  File "/usr/lib/python3.8/asyncio/streams.py", line 665, in read
    raise self._exception
  File "/usr/lib/python3.8/asyncio/selector_events.py", line 908, in write
    n = self._sock.send(data)
BrokenPipeError: [Errno 32] Broken pipe

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/bin/climp3", line 491, in play
    RPC.update(state=out)
  File "/home/user/.local/lib/python3.8/site-packages/pypresence/presence.py", line 32, in update
    return self.loop.run_until_complete(self.read_output())
  File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/user/.local/lib/python3.8/site-packages/pypresence/baseclient.py", line 101, in read_output
    raise InvalidID
pypresence.exceptions.InvalidID: Client ID is Invalid
$ pip3 show pypresence
Name: pypresence
Version: 4.0.0
Summary: Discord RPC client written in Python
Home-page: https://github.com/qwertyquerty/pypresence
Author: qwertyquerty
Author-email: None
License: MIT
Location: /home/user/.local/lib/python3.8/site-packages
Requires: 
Required-by:

Having RPC stay the same until some kind of Python script is ran?

Hey, me again. I really wanted to somehow keep RPC in the background having the same info and update them when I execute the Python file. However, unless I do some super dumb hacky shit (terminate python script then run it again), I cannot get the Python script to update without restarting it. Right now I'm stuck in a loop (literally, have to run the script in loop instead of updating it when there's a change.

Can't run event loop

I installed pypresence from pip and was testing on the basic example. I tried running the code but it keeps giving me this error:

RuntimeError                              Traceback (most recent call last)
<ipython-input-49-0399602e0ca4> in <module>()
      4 client_id = 'real id is here when i ran'  # Discord application ID
      5 RPC = Presence(client_id,pipe=0)  # Initialize the client class
----> 6 RPC.connect() # Start the handshake loop
      7 
      8 print(RPC.update(state="Lookie Lookie", details="A test of qwertyquerty's Python Discord RPC wrapper, pypresence!"))  # Set the presence

~\AppData\Local\Programs\Python\Python36\lib\site-packages\pypresence\presence.py in connect(self)
    121 
    122     def connect(self):
--> 123         self.loop.run_until_complete(self.handshake())
    124 
    125     def close(self):

~\AppData\Local\Programs\Python\Python36\lib\asyncio\base_events.py in run_until_complete(self, future)
    453         future.add_done_callback(_run_until_complete_cb)
    454         try:
--> 455             self.run_forever()
    456         except:
    457             if new_task and future.done() and not future.cancelled():

~\AppData\Local\Programs\Python\Python36\lib\asyncio\base_events.py in run_forever(self)
    410         if events._get_running_loop() is not None:
    411             raise RuntimeError(
--> 412                 'Cannot run the event loop while another loop is running')
    413         self._set_coroutine_wrapper(self._debug)
    414         self._thread_id = threading.get_ident()

RuntimeError: Cannot run the event loop while another loop is running

I usually know how to fix stuff like this myself but i'm just totally confused. Other potentially helpful stuff: no other python was running, and I was not running anything else that was using the discord rpc.

Cannot connect when running from a root account

This is my console output, I'm just using example #1.
aurailus@aurailus-xubuntu:~/Documents/Rich Presence$ sudo python3.6 app.py Traceback (most recent call last): File "app.py", line 6, in <module> RPC.connect() File "/home/aurailus/.local/lib/python3.6/site-packages/pypresence/presence.py", line 145, in connect self.loop.run_until_complete(self.handshake()) File "/usr/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete return future.result() File "/home/aurailus/.local/lib/python3.6/site-packages/pypresence/presence.py", line 80, in handshake self.sock_reader, self.sock_writer = yield from asyncio.open_unix_connection(self.ipc_path, loop=self.loop) File "/usr/lib/python3.6/asyncio/streams.py", line 134, in open_unix_connection lambda: protocol, path, **kwds) File "/usr/lib/python3.6/asyncio/unix_events.py", line 245, in create_unix_connection yield from self.sock_connect(sock, path) File "/usr/lib/python3.6/asyncio/selector_events.py", line 450, in sock_connect return (yield from fut) File "/usr/lib/python3.6/asyncio/selector_events.py", line 455, in _sock_connect sock.connect(address) FileNotFoundError: [Errno 2] No such file or directory

Apologies if this is a stupid issue, I'm a bit of a noob at Python.

client id invalid

Used the same code 4 days ago, now it doesnt work... and no. The client id is correct.

A way to close RPC without stopping the Python loop

Kind of funny how I asked the opposite a month ago.

In my script, I have a loop script to check whether the window is open or not. I need it so that if it's not open, close the RPC connection and keep checking. I've tried RPC.close(), but that returns

Traceback (most recent call last):
  File "./gimp-rpc.py", line 56, in <module>
    print(RPC.update(details=line1, state=line2, large_image="gimp-papirus", large_text=version))
  File "/home/diamond/Scripts/gimp-rpc/presence.py", line 122, in update
    return self.loop.run_until_complete(self.read_output())
  File "/usr/lib/python3.6/asyncio/base_events.py", line 444, in run_until_complete
    self._check_closed()
  File "/usr/lib/python3.6/asyncio/base_events.py", line 358, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Script is basically if Bash file (yes, laugh) returns blank, run RPC loop, if it's no longer blank, recheck the Bash file until it's blank again, then initiate the RPC loop. I want to stop the RPC connection at the part where it rechecks the Bash file. Script if it helps you: https://hastebin.com/qucekelowo.py

FileNotFoundError: [Errno 2] No such file or directory

im getting this error when running the quotes example im using Ubuntu 18.04, zsh, vscode, and pipenv .
Not sure what file its referring to?

  File "/home/jordan/Documents/CustomDiscordRichPresence/core.py", line 9, in <module>
    RPC.connect()  # Start the handshake loop
  File "/home/jordan/.local/share/virtualenvs/CustomDiscordRichPresence-UCeHkaM9/lib/python3.6/site-packages/pypresence/presence.py", line 123, in connect
    self.loop.run_until_complete(self.handshake())
  File "/usr/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete
    return future.result()
  File "/home/jordan/.local/share/virtualenvs/CustomDiscordRichPresence-UCeHkaM9/lib/python3.6/site-packages/pypresence/presence.py", line 58, in handshake
    self.sock_reader, self.sock_writer = yield from asyncio.open_unix_connection(self.ipc_path, loop=self.loop)
  File "/usr/lib/python3.6/asyncio/streams.py", line 134, in open_unix_connection
    lambda: protocol, path, **kwds)
  File "/usr/lib/python3.6/asyncio/unix_events.py", line 245, in create_unix_connection
    yield from self.sock_connect(sock, path)
  File "/usr/lib/python3.6/asyncio/selector_events.py", line 450, in sock_connect
    return (yield from fut)
  File "/usr/lib/python3.6/asyncio/selector_events.py", line 455, in _sock_connect
    sock.connect(address)
FileNotFoundError: [Errno 2] No such file or directory```

excepting InvalidPipe

        try:
            self.rpc.connect()
        except InvalidPipe:
            logger.info("Discord not open, waiting for discord to launch...")
            while 1:
                try:
                    self.rpc.connect()
                    break
                except InvalidPipe:
                    pass
                await asyncio.sleep(5)

This is something I'm trying to do, while with a wide except of something like Exception, I am able to make it work, it still outputs Task exception never received in the console which i think is not something i can catch/except only on connect.
PS. I wonder if this would work if connect was changed to a coro and then handshake was called with await?

ERROR:asyncio:Task exception was never retrieved
future: <Task finished coro=<Presence.handshake() done, defined at I:\pypresence\presence.py:55> exception=InvalidPipe('Pipe Not Found - Is Discord Running?',)>
Traceback (most recent call last):
  File "I:\pypresence\presence.py", line 64, in handshake
    self.sock_writer, _ = yield from self.loop.create_pipe_connection(lambda: reader_protocol, self.ipc_path)
  File "C:\Python\Python36\lib\asyncio\windows_events.py", line 317, in create_pipe_connection
    pipe = yield from f
  File "C:\Python\Python36\lib\asyncio\windows_events.py", line 547, in connect_pipe
    handle = _overlapped.ConnectPipe(address)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "I:\pypresence\presence.py", line 66, in handshake
    raise InvalidPipe
pypresence.exceptions.InvalidPipe: Pipe Not Found - Is Discord Running?

Connection seems to work fine but updating doesn't

Issue description

When trying to update the status, I get an "Unknown error" message in the server's response, which looks like this:

{'cmd': 'SET_ACTIVITY', 'data': {'code': 1000, 'message': 'Unknown Error'}, 'evt': 'ERROR', 'nonce': '1525529333.90793704986572265625'}

and read_output() raises a ServerError exception

Observations

The connection step before that (Presence.connect()) seems to work just fine, as I get this response from the server:

{'cmd': 'DISPATCH', 'data': {'v': 1, 'config': {'cdn_host': 'cdn.discordapp.com', 'api_endpoint': '//discordapp.com/api', 'environment': 'production'}, 'user': {'id': 'XXXX', 'username': 'XXXX', 'discriminator': 'XXXX', 'avatar': 'XXXX', 'bot': False}}, 'evt': 'READY', 'nonce': None}

with my correct user info (in place of the XXXX), suggesting that this part is OK.

Reproduction

I first encountered this issue when running the rich-presence.py example, but it similarly happens with any other script where the Presence.update() method is used.

System info

  • pypresence 2.0.0 downloaded from the GitHub repo and installed with pip install .
  • Python 3.6.5 installed with Homebrew
  • OS X 10.11.6.

SyntaxError: invalid syntax on Python 2.7

Error when running the example on python 2.7.

$ python rich-presence.py 
Traceback (most recent call last):
  File "rich-presence.py", line 1, in <module>
    from pypresence import Presence
  File "build/bdist.linux-x86_64/egg/pypresence/__init__.py", line 7, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pypresence-3.2.2-py2.7.egg/pypresence/activity.py", line 12
    def __init__(self, client: Presence, pid: int = os.getpid(),
                             ^
SyntaxError: invalid syntax

feedback

pretty nice considering its python , Using C makes it complicated and just a waste of time compared to this good job

Example #4 not working

Traceback (most recent call last): File "F:\somethingy\pyql\test.py", line 8, in <module> print(RPC.update(state="Lookie Lookie", details="A test of qwertyquerty's Python Discord RPC wrapper, pypresence!")) # Set the presence File "C:\Users\INDIA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypresence\presence.py", line 107, in update return self.loop.run_until_complete(self.read_output()) File "C:\Users\INDIA\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py", line 467, in run_until_complete return future.result() File "C:\Users\INDIA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypresence\presence.py", line 43, in read_output raise ServerError(payload["data"]["message"]) pypresence.exceptions.ServerError: Unknown error

Issues with start time

Running into some issues with the start parameter in client.update(). What we want is for the time to start from when the update is issued, however, that doesn't seem to be possible.

If set to 0, the following error occurs:

pypresence.exceptions.ServerError: Child "activity" fails because child "timestamps" fails
 because child "start" fails because "start" must be larger than or equal to 1

If set to 1, the "start" time gets set to ~5 hours, which is definitely not what I expected. Example: https://imgur.com/6vp9RMf

Example code:

from pypresence import Presence
import time

# PUT A TEST CLIENT ID HERE
client_id = ''

RPC = Presence(client_id)
RPC.connect()

start_time = 1
print(RPC.update(state="No important DMs please", details="Trying to sleep", start=start_time,
                 large_image="monoblobsleep", large_text="Sleeping. Please no DMs",
                 join="MTI4NzM0OjFpMmhuZToxMjMxMjM="))
while True: 
    time.sleep(15) 

[WinError 232] The pipe is being closed

Using the example rich presence code - getting this:

{"v": 1, "client_id": mmm}
{"cmd": "SET_ACTIVITY", "args": {"pid": 11536, "activity": {"state": "wait", "details": "testing", "timestamps": {}, "assets": {}, "party": {}, "secrets": {}, "instance": true}}, "nonce": "1523592330.50662136077880859375"}
Traceback (most recent call last):
  File "chrome ext.py", line 354, in <module>
    c.set_activity(state="wait", details="testing")
  File "chrome ext.py", line 256, in set_activity
    return self.loop.run_until_complete(self.read_output())
  File "C:\Users\lll\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py", line 467, in run_until_complete
    return future.result()
  File "chrome ext.py", line 31, in read_output
    data = await self.sock_reader.read(1024)
  File "C:\Users\lll\AppData\Local\Programs\Python\Python36-32\lib\asyncio\streams.py", line 615, in read
    raise self._exception
  File "C:\Users\lll\AppData\Local\Programs\Python\Python36-32\lib\asyncio\proactor_events.py", line 291, in _loop_writing
    self._write_fut = self._loop._proactor.send(self._sock, data)
  File "C:\Users\lll\AppData\Local\Programs\Python\Python36-32\lib\asyncio\windows_events.py", line 457, in send
    ov.WriteFile(conn.fileno(), buf)
BrokenPipeError: [WinError 232] The pipe is being closed```

Traceback error in pypresence.py

This is the error I get when trying to run an RPC Client pypresence script:

Traceback (most recent call last):
  File "windows.py", line 2, in <module>
    from pypresence import presence
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\pypresence\__init__.py", line 7, in <module>
    from .activity import Activity
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\pypresence\activity.py", line 4, in <module>
    from .presence import Presence
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\pypresence\presence.py", line 51
    super().__init__(*args, **kwargs, async=True)
                                          ^
SyntaxError: invalid syntax

Not sure what this means tbh

FileNotFound Error in Sock.connect(Address)

Hey, i've been trying to solve this error without any luck:
Traceback (most recent call last): File "presence-weeb.py", line 11, in <module> RPC.connect() File "/usr/local/lib/python3.6/dist-packages/pypresence/presence.py", line 123, in connect self.loop.run_until_complete(self.handshake()) File "/usr/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete return future.result() File "/usr/local/lib/python3.6/dist-packages/pypresence/presence.py", line 58, in handshake self.sock_reader, self.sock_writer = yield from asyncio.open_unix_connection(self.ipc_path, loop=self.loop) File "/usr/lib/python3.6/asyncio/streams.py", line 134, in open_unix_connection lambda: protocol, path, **kwds) File "/usr/lib/python3.6/asyncio/unix_events.py", line 245, in create_unix_connection yield from self.sock_connect(sock, path) File "/usr/lib/python3.6/asyncio/selector_events.py", line 450, in sock_connect return (yield from fut) File "/usr/lib/python3.6/asyncio/selector_events.py", line 455, in _sock_connect sock.connect(address) FileNotFoundError: [Errno 2] No such file or directory Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x7fe3291dd7b8>

Code:

`import discord
from discord.ext import commands
import asyncio
from pypresence import Presence

client = commands.Bot(command_prefix = '#')

client.remove_command('help')
presence_id = '472522976638533663'
RPC = Presence(presence_id)
RPC.connect()
client.change_presence(game=None)
@client.event
async def on_ready():
    print("ready to post some weeb shit")
    await client.RPC.update(details = "#help for help", state = "Anime = Mistake", large_text="Please end me", large_image="r-weeb_jpg")





client.run("TOKEN")
`

Joining Example

Not sure if this is the best place to ask this, but do you have an example that utilizes the Client() method that can take player requests to join the game?

Script fails on 3.5.3

python --version returns 3.5.3

Traceback (most recent call last):
  File "rich.py", line 2, in <module>
    from presence import Presence
  File "/home/richpresence/presence.py", line 47
    self.sock_reader: asyncio.StreamReader = None
                    ^
SyntaxError: invalid syntax

When running PyPresence

Exception ignored in: <function _ProactorBasePipeTransport.del at 0x03904FA8>
Traceback (most recent call last):
File "C:\Program Files (x86)\Python37-32\lib\asyncio\proactor_events.py", line 93, in del
warnings.warn(f"unclosed transport {self!r}", ResourceWarning,
File "C:\Program Files (x86)\Python37-32\lib\asyncio\proactor_events.py", line 57, in repr
info.append(f'fd={self._sock.fileno()}')
File "C:\Program Files (x86)\Python37-32\lib\asyncio\windows_utils.py", line 102, in fileno
raise ValueError("I/O operation on closed pipe")
ValueError: I/O operation on closed pipe

Error during install of 3.3.0 on Linux

Basically, if you run pip install pypresence on Linux, a scary-looking error occurs during install. While the installation actually finishes successfully, the error output gives the impression that it failed. This does not happen on Windows, oddly enough.

This is likely my fault. I added a line to setup.cfg in this commit that wants the license file to be included, likely because I was reusing code from another project of mine. Apologies.

Fixes are either:

  • Don't have setup tools include the license file when installing a binary wheel (by removing the line from setup.cfg)
  • Ensure it gets included in distribution by adding a MANIFEST.in file

Output:

(testrange-wsl) Supercomputer-14:~$ pip install -U pypresence
Collecting pypresence
  Downloading https://files.pythonhosted.org/packages/8c/fc/d80abc40275c1fbc9b7fc09bc2965a20372d48adee3ec95eb5d26fdf66fb/pypresence-3.3.0.tar.gz
Building wheels for collected packages: pypresence
  Running setup.py bdist_wheel for pypresence ... error
  Complete output from command /home/goesc/.virtualenvs/testrange-wsl/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-wmk82e5_/pypresence/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmph0ex37qbpip-wheel- --python-tag cp36:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib
  creating build/lib/pypresence
  copying pypresence/__init__.py -> build/lib/pypresence
  copying pypresence/activity.py -> build/lib/pypresence
  copying pypresence/baseclient.py -> build/lib/pypresence
  copying pypresence/client.py -> build/lib/pypresence
  copying pypresence/exceptions.py -> build/lib/pypresence
  copying pypresence/payloads.py -> build/lib/pypresence
  copying pypresence/presence.py -> build/lib/pypresence
  copying pypresence/response.py -> build/lib/pypresence
  copying pypresence/utils.py -> build/lib/pypresence
  installing to build/bdist.linux-x86_64/wheel
  running install
  running install_lib
  creating build/bdist.linux-x86_64
  creating build/bdist.linux-x86_64/wheel
  creating build/bdist.linux-x86_64/wheel/pypresence
  copying build/lib/pypresence/__init__.py -> build/bdist.linux-x86_64/wheel/pypresence
  copying build/lib/pypresence/activity.py -> build/bdist.linux-x86_64/wheel/pypresence
  copying build/lib/pypresence/baseclient.py -> build/bdist.linux-x86_64/wheel/pypresence
  copying build/lib/pypresence/client.py -> build/bdist.linux-x86_64/wheel/pypresence
  copying build/lib/pypresence/exceptions.py -> build/bdist.linux-x86_64/wheel/pypresence
  copying build/lib/pypresence/payloads.py -> build/bdist.linux-x86_64/wheel/pypresence
  copying build/lib/pypresence/presence.py -> build/bdist.linux-x86_64/wheel/pypresence
  copying build/lib/pypresence/response.py -> build/bdist.linux-x86_64/wheel/pypresence
  copying build/lib/pypresence/utils.py -> build/bdist.linux-x86_64/wheel/pypresence
  running install_egg_info
  running egg_info
  writing pypresence.egg-info/PKG-INFO
  writing dependency_links to pypresence.egg-info/dependency_links.txt
  writing top-level names to pypresence.egg-info/top_level.txt
  reading manifest file 'pypresence.egg-info/SOURCES.txt'
  writing manifest file 'pypresence.egg-info/SOURCES.txt'
  Copying pypresence.egg-info to build/bdist.linux-x86_64/wheel/pypresence-3.3.0-py3.6.egg-info
  running install_scripts
  error: [Errno 2] No such file or directory: 'LICENSE'

  ----------------------------------------
  Failed building wheel for pypresence
  Running setup.py clean for pypresence
Failed to build pypresence
Installing collected packages: pypresence
  Running setup.py install for pypresence ... done
Successfully installed pypresence-3.3.0

qwertypls

kot83-desktop% python3.6 test.py 
{"v": 1, "client_id": "64567352374564"}
{"cmd": "SET_ACTIVITY", "args": {"pid": 12611, "activity": {"state": "ree", "timestamps": {}, "assets": {}, "party": {}, "secrets": {}, "instance": true}}, "nonce": "1522862178.79681730270385742188"}
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print(RPC.set_activity(state="ree")) #Set the presence
  File "/home/kot83/Documents/pypresence.py", line 256, in set_activity
    return self.loop.run_until_complete(self.read_output())
  File "/usr/local/lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete
    return future.result()
  File "/home/kot83/Documents/pypresence.py", line 31, in read_output
    data = await self.sock_reader.read(1024)
  File "/usr/local/lib/python3.6/asyncio/streams.py", line 634, in read
    yield from self._wait_for_data('read')
  File "/usr/local/lib/python3.6/asyncio/streams.py", line 464, in _wait_for_data
    yield from self._waiter
  File "/usr/local/lib/python3.6/asyncio/selector_events.py", line 723, in _read_ready
    data = self._sock.recv(self.max_size)
ConnectionResetError: [Errno 104] Connection reset by peer

[Suggestion] Event Loop kwarg

Hi, Great RPC Client btw!
Just wanted to know if you would consider adding a kwarg for people to be able to pass their own established event loop as a kwarg?
I made a shoddy patch on my project at https://github.com/xKynn/PathOfExileRPC to use it that way, though in hindsight i think I could've just initialized the Presence object before my own and pass the loop in from there to my class

AioClient.authorize never responding

Using AioClient doesn't work, but the same code with Client works fine. Code and output follows:

Code:

import asyncio
import pypresence

CLIENT_ID = "<>"


def sync():
    discord = pypresence.Client(CLIENT_ID)
    print("discord.start")
    print("start:", discord.start())
    print("authorize", discord.authorize(CLIENT_ID, ['rpc']))


async def aio():
    discord = pypresence.AioClient(CLIENT_ID)
    print("discord.start")
    print("start:", await discord.start())
    print("authorize", await discord.authorize(CLIENT_ID, scopes=["rpc"]))


if __name__ == '__main__':
    # sync()
    asyncio.run(aio())

Output for sync():

discord.start
start: None
authorize {'cmd': 'AUTHORIZE', 'data': {'code': 'RNMrhdCRLdF*snip*DDovEW'}, 'evt': None, 'nonce': '1592948477.55941104888916015625'}

Output for aio():

discord.start
start: None
/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/streams.py:257: RuntimeWarning: coroutine 'AioClient.on_event' was never awaited
  self._stream_reader.feed_data(data)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Then it gets stuck and never finishes. Discord does prompt for authorization, but accepting makes no difference.

Enviroment:
Python 3.7.7
macOS 10.15.5

Pip version is outdated

The version downloaded off pip is outdated; it needs to be updated to latest version. (the docs don't mention this)

Not working

I've tried to use this but nothing shows up on discord. I've tried the examples (copy and paste) but it still doesn't work.

Also, can you add a usage section in the documentation? It's really confusing without it.

Support for older Python versions

Hello,
Nice to see so developed Discord RPC library in Python. I was working on simple RPC client but I did not wrapped full SDK (no needed for me). It will be really nice if you can get rid of asyncio because not all of users will be using that with the newest version of Python interpreter.
Good work,
Cheers

FileNotFoundError in sock.connect() Ubuntu 18.04

Hello, I've been trying to solve this issue on Ubuntu 18.04 without much luck. Getting the error:

Traceback (most recent call last):
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/usr/lib/rhythmbox/plugins/discord-rhythmbox-plugin/discord-status.py", line 9, in <module>
    class discord_status (GObject.Object, Peas.Activatable):
  File "/usr/lib/rhythmbox/plugins/discord-rhythmbox-plugin/discord-status.py", line 11, in discord_status
    RPC.connect()
  File "/home/topkek/.local/lib/python3.6/site-packages/pypresence/presence.py", line 123, in connect
    self.loop.run_until_complete(self.handshake())
  File "/usr/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete
    return future.result()
  File "/home/topkek/.local/lib/python3.6/site-packages/pypresence/presence.py", line 58, in handshake
    self.sock_reader, self.sock_writer = yield from asyncio.open_unix_connection(self.ipc_path, loop=self.loop)
  File "/usr/lib/python3.6/asyncio/streams.py", line 134, in open_unix_connection
    lambda: protocol, path, **kwds)
  File "/usr/lib/python3.6/asyncio/unix_events.py", line 245, in create_unix_connection
    yield from self.sock_connect(sock, path)
  File "/usr/lib/python3.6/asyncio/selector_events.py", line 450, in sock_connect
    return (yield from fut)
  File "/usr/lib/python3.6/asyncio/selector_events.py", line 455, in _sock_connect
    sock.connect(address)
FileNotFoundError: [Errno 2] No such file or directory

I've tried reinstalling pypresence with no luck. So far only found this issue on Ubuntu. Debian and Manjaro seem to work fine. Not sure if this is an issue with pypresence or asyncio, but thought I'd start here. Any help is appreciated! Thanks!

File not found error?

Hello, I downloaded this package from this github (not pypi) and Its giving me this: FileNotFoundError: [Errno 2] No such file or directory

full error

How to get join request?

I can throw an invitation to the game to a friend in discord chat, but how to get information about trying to connect

Error installing the module

This is what I get when I install pypresence (pip install pypresence):
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-0rsa25u1/pypresence/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-hn2y1230/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-0rsa25u1/pypresence/

AttributeError: 'Presence' object has no attribute 'Update'

Hey. Fixing my osu-linux-rpc code, but I met some trouble from release 1.1.0:

Traceback (most recent call last):
  File "osu-linux-rpc.py", line 22, in <module>
    RPC.Update(details=full, state=info, large_image="osu-large", large_text="Linux is better", small_image="wine", small_text=winever)
AttributeError: 'Presence' object has no attribute 'Update'

I did from presence import Presence and

client_id = 'id' # My ID, please no abuse :(
RPC = Presence(client_id)
RPC.connect() # Magic PyPresence stuff, no idea :(

but that doesn't seem to be the problem here.

The only thing I modified is this part:

from exceptions import *
from utils import *

since I have the script stored locally instead of in the system. The 2 files are still there, untouched.

Oh yea, just want to mention, I import the pypresence.py file, not client.py file. Kind of confused on which file to use, as client.py's syntax seems to differ from the examples.

RPC queries don't update quickly enough

Hey, I'm making an RPC script. Discovered this long ago, but even with time.sleep(0.5), RPC still takes at least 10-15 seconds to update, which for my kind of game, is slow. Is there a way I can improve this?

How do I use?

I know python and all, but the documentation isn't helping alot.
Do I need to use async? Please make a tutorial, this is really not helping out and pretty bad documentation overall.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.