A discord.py extension for inter-process communication.
Python >=3.5.3 is required.
pip install --upgrade discord-ext-ipc
- The documentation.
- The usage examples.
- The Ext-Creators Discord.
๐ A discord.py extension for inter-process communication.
Home Page: https://ext-creators.github.io/docs/ipc
License: Apache License 2.0
A discord.py extension for inter-process communication.
Python >=3.5.3 is required.
pip install --upgrade discord-ext-ipc
How do I change the port of the ipc.Server
The link to the documentation in the README.rst only leads to a page saying that the page doesn't exist.
I would like to see documentation of the project there.
Sometimes I getting This Error: OSError: [WinError 10038] an operation was attempted on something that is not a socket
I thinking this error comes when I refresh page
System: Windows 10 64x
It seems like in discord.py 2.0, ever since Client.dispatch
uses asyncio.create_task
, we can't really start the server before the bot is running.
Traceback (most recent call last):
File "C:\Users\sarah\PycharmProjects\bot_manager\main.py", line 14, in <module>
bot.server.start()
File "C:\Users\sarah\PycharmProjects\bot_manager\venv\lib\site-packages\discord\ext\ipc\server.py", line 253, in start
self.bot.dispatch("ipc_ready")
File "C:\Users\sarah\PycharmProjects\bot_manager\venv\lib\site-packages\discord\ext\commands\bot.py", line 132, in dispatch
super().dispatch(event_name, *args, **kwargs)
File "C:\Users\sarah\PycharmProjects\bot_manager\venv\lib\site-packages\discord\client.py", line 383, in dispatch
self._schedule_event(coro, method, *args, **kwargs)
File "C:\Users\sarah\PycharmProjects\bot_manager\venv\lib\site-packages\discord\client.py", line 343, in _schedule_event
return asyncio.create_task(wrapped, name=f'discord.py: {event_name}')
File "C:\Users\sarah\AppData\Local\Programs\Python\Python39\lib\asyncio\tasks.py", line 360, in create_task
loop = events.get_running_loop()
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'Client._run_event' was never awaited
I was expecting the bot to run normally as it is in 1.7.3.
from discord.ext import commands, ipc
class SBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.server = ipc.Server(self, secret_key="my_secret_key")
async def on_ipc_ready(self):
print("Ipc is ready")
bot = SBot("bot ")
bot.server.start()
bot.run("...")
I'm able to fix it by not using on_ipc_ready
event as of now.
Hello. When I try to get bot servers (bot.guilds) I get an empty list. When I want to fetch the servers using bot.fetch_guilds().flatten()
, I get the error given in the issue title.
AttributeError: '_MissingSentinel' object has no attribute 'request'
File C:\Users\main\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\http.py, line 354
Guild list
I described it in the description
I'm using discord.py 2.0 beta.
Windows 11 BETA, latest version
Python 3.9
I am using the latest version 2.1.0 and the following code returns the wrong value for some reason:
bot:
@ipc.server.route()
async def get_guild_count(self, data):
return len(self.bot.guilds) # returns the len of the guilds to the client
dashboard
guild_count = await ipc_client.request("get_guild_count")
result:
{'message': 'Connection success', 'port': '8765', 'code': 200}
I didn't change the code, I just updated to the latest version
In a function I have that sends messages to a specific channel, there is (obviously) an await channel.send(...)
line to actually send the message. Whenever this function is run via the ipc server though, the code past this line never gets executed - the message itself is sent without a problem, but the execution stops at the await and seemingly never returns from that statement.
I am pretty sure this problem is caused by the ipc module, because when I transform the function into a regular discord bot command, everything works fine and as expected.
The message gets sent to the specified channel, but code after that sending operation is completely ignored and never runs. With that, it is also impossible to run the function again, as it is still stuck in that instance.
There are no errors whatsoever, just nothing happens.
Here is the server code:
class Bot(commands.Bot):
self.ipc = ipc.Server(self, secret_key="abc")
...
bot = Bot()
bot.ipc.start()
bot.run()
@Bot.ipc.route()
async def send_message(channel_id):
await client.get_channel(channel_id).send('hi')
print('hi')
And the client:
ipc_client = ipc.Client(secret_key='abc')
async def request():
await ipc_client.request('send_message', channel_id=...)
First, I started the server (which went fine and without errors), then ran the client function a few times with the above described results - the 'hi' never gets printed.
Python 3.9.4
discord.py 1.7.3
discord-ext-ipc 2.1.1
IPC routes defined with the class level @route
decorator cannot be reloaded. We've chatted about this on the Discord a fair amount already, but for sake of visibility, an issue is worth adding.
from discord.ext import commands, ipc
class IpcRoutes(commands.Cog):
def __init__(self, bot):
self.bot = bot
# This route is not reloaded
@ipc.server.route()
async def ping(self, data):
return "Pong"
def setup(bot):
bot.add_cog(IpcRoutes(bot))
I was able to workaround this issue by manually defining routes on the IPC server.
from discord.ext import commands, ipc
class IpcRoutes(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def ping(self, data):
return "Pong"
def setup(bot):
bot.ipc.endpoints["ping"] = IpcRoutes.ping
bot.add_cog(IpcRoutes(bot))
I started my bot for the first time with ipc.server. It errored because 'bot' object has no attribute 'loop'
This error happened in server.py
.
Also, this may be the cause of my bot subclass... but I'm not totally sure.
See additional information
for my bot subclass. Also, I didn't find any bot.loop
in the discord.py documentation
Traceback (most recent call last):
File "c:\Users\natalie\Groot\main\launcher.py", line 33, in <module>
bot = GrootBot(**bot_data)
File "c:\Users\natalie\Groot\main\bot.py",
line 38, in __init__
self.ipc = ipc.Server(self, secret_key="akey")
File "C:\Users\natalie\Python39\lib\site-packages\discord\ext\ipc\server.py", line 68, in __init__
self.loop = bot.loop
AttributeError: 'GrootBot' object has no attribute 'loop'
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000247DC4A44C0>
Expected the bot to run smoothly.
# deleted unrelevant imports
from discord.ext import commands, ipc, tasks
class GrootBot(commands.Bot):
def __init__(self, **kwargs):
#deleted unrelevant things
self.ipc = ipc.Server(self, secret_key="GrootBotAdmin")
super().__init__(self.get_prefix, **kwargs)
#deleted code
def starter(self):
"""Starts the bot properly"""
try:
loop = asyncio.get_event_loop()
db = loop.run_until_complete(aiosqlite.connect(f"{self.cwd}/data/main.sqlite3"))
except Exception as e:
print_exception("Could not connect to database:", e)
else:
self.launch_time = datetime.datetime.utcnow()
self.db = db
self.loop.run_until_complete(self.after_db())
self.ipc.start()
self.run(self.token)
# Events
async def on_ready(self):
logging.warning(f"Logged in as {self.user}, SQLite3 database initialized.")
print(f"CHECK: Bot ready 1/2")
async def on_ipc_ready(self):
logging.warning(f"IPC is ready to go!")
print("CHECK: IPC ready 2/2")
async def on_ipc_error(self, endpoint, error):
logging.warning(f"{endpoint} raised {error}")```
Windows 10
It would be nice to be able to install this from pypi.
Love your work ๐
When reloading a cog with IPC routes, they will reload as expected. However if you change the name of the function (Or name=
in decor), then this new route will be added to IPC as expected. However, the old route will also still exist.
The old route isn't removed as the underlying key changed for said func
The old route is removed
@ipc.server.route()
async def get_member_count(self, data):
guild = self.bot.get_guild(data.guild_id) # get the guild object using parsed guild_id
return guild.member_count # return the member count to the client
@ipc.server.route(name="test")
async def get_member_count(self, data):
guild = self.bot.get_guild(data.guild_id) # get the guild object using parsed guild_id
return guild.member_count # return the member count to the client
1
route (test), expect it has 2
(test, get_member_count)I'm not sure how to fix this, hence why I am opening an issue and not a pull request.
IPC: Latest on main
System independant
Error by Handling Multiple Requests
@app.route(API_BASE_ROUTE + 'bot/guild', methods=['POST'])
async def isBotOnGuild():
try:
data = await request.json
guild_id: int = data['guild_id']
except:
print('Bad Request')
print(f'Guild_ID: {guild_id}')
result = await ipc_client.request('is_on_guild', guild_id=guild_id)
print(f'Result: {result}')
return {"result": result}
My Frontend is sending multiple requets to this Endpoint very fast.
Error
[2021-02-24 13:15:58,550] Error in ASGI Framework
Traceback (most recent call last):
File "/home/username/myproject/venv/lib/python3.9/site-packages/hypercorn/asyncio/context.py", line 39, in _handle
await invoke_asgi(app, scope, receive, send)
File "/home/username/myproject/venv/lib/python3.9/site-packages/hypercorn/utils.py", line 239, in invoke_asgi
await app(scope, receive, send)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 2117, in __call__
await self.asgi_app(scope, receive, send)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 2140, in asgi_app
await asgi_handler(receive, send)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/asgi.py", line 33, in __call__
_raise_exceptions(done)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/asgi.py", line 256, in _raise_exceptions
raise task.exception()
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/asgi.py", line 72, in handle_request
response = await self.app.handle_request(request)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1866, in handle_request
return await self.handle_exception(error)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1118, in handle_exception
raise error
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1862, in handle_request
return await self.full_dispatch_request(request_context)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1887, in full_dispatch_request
result = await self.handle_user_exception(error)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1104, in handle_user_exception
raise error
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1885, in full_dispatch_request
result = await self.dispatch_request(request_context)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1933, in dispatch_request
return await handler(**request_.view_args)
File "/home/username/myproject/main.py", line 106, in isBotOnGuild
result = await ipc_client.request('is_on_guild', guild_id=guild_id)
File "/home/username/myproject/venv/lib/python3.9/site-packages/discord/ext/ipc/client.py", line 120, in request
return json.loads(recv.data)
File "/usr/lib/python3.9/json/__init__.py", line 339, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not RuntimeError
[2021-02-24 13:15:58,552] 127.0.0.1:44610 POST /api/v1/bot/guild 1.1 500 - 47588
[2021-02-24 13:15:58,559] 127.0.0.1:44604 OPTIONS /api/v1/bot/guild 1.1 200 0 23103
[2021-02-24 13:15:58,570] 127.0.0.1:44634 OPTIONS /api/v1/bot/guild 1.1 200 0 27357
Guild_ID: 647535887495856100
[2021-02-24 13:15:58,583] 127.0.0.1:44642 OPTIONS /api/v1/bot/guild 1.1 200 0 16591
Guild_ID: 707601932142772200
Guild_ID: 786606423383212000
[2021-02-24 13:15:58,597] Error in ASGI Framework
Traceback (most recent call last):
File "/home/username/myproject/venv/lib/python3.9/site-packages/hypercorn/asyncio/context.py", line 39, in _handle
await invoke_asgi(app, scope, receive, send)
File "/home/username/myproject/venv/lib/python3.9/site-packages/hypercorn/utils.py", line 239, in invoke_asgi
await app(scope, receive, send)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 2117, in __call__
await self.asgi_app(scope, receive, send)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 2140, in asgi_app
await asgi_handler(receive, send)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/asgi.py", line 33, in __call__
_raise_exceptions(done)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/asgi.py", line 256, in _raise_exceptions
raise task.exception()
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/asgi.py", line 72, in handle_request
response = await self.app.handle_request(request)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1866, in handle_request
return await self.handle_exception(error)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1118, in handle_exception
raise error
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1862, in handle_request
return await self.full_dispatch_request(request_context)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1887, in full_dispatch_request
result = await self.handle_user_exception(error)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1104, in handle_user_exception
raise error
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1885, in full_dispatch_request
result = await self.dispatch_request(request_context)
File "/home/username/myproject/venv/lib/python3.9/site-packages/quart/app.py", line 1933, in dispatch_request
return await handler(**request_.view_args)
File "/home/username/myproject/main.py", line 106, in isBotOnGuild
result = await ipc_client.request('is_on_guild', guild_id=guild_id)
File "/home/username/myproject/venv/lib/python3.9/site-packages/discord/ext/ipc/client.py", line 103, in request
await self.websocket.send_str(json.dumps(fmt))
File "/home/username/myproject/venv/lib/python3.9/site-packages/aiohttp/client_ws.py", line 150, in send_str
await self._writer.send(data, binary=False, compress=compress)
File "/home/username/myproject/venv/lib/python3.9/site-packages/aiohttp/http_websocket.py", line 687, in send
await self._send_frame(message, WSMsgType.TEXT, compress)
File "/home/username/myproject/venv/lib/python3.9/site-packages/aiohttp/http_websocket.py", line 598, in _send_frame
raise ConnectionResetError("Cannot write to closing transport")
ConnectionResetError: Cannot write to closing transport
[2021-02-24 13:15:58,599] 127.0.0.1:44638 POST /api/v1/bot/guild 1.1 500 - 55090
No Error
Handling requests step by step
Send many Requets very fast
Arch Linux (5.10.16-arch1-1)
Python 3.9.1
Originally posted by ripperaim July 16, 2021
is there a way to close the client session?
i had an error fixed of mine of that reload by just making
ipc_client = ipc.Client(secret_key="code")
as soon as i get in a route so the session was left open and if i reload it worked fine but i had an message in my terminal that Unclosed client session
so i was wondering how can i close the session and also how can i fix the site reload problem without doing this cause its not a good practice xD
i tried doing that #44 workaround but had errors that* 'ipc' has no attribute 'endpoints'*
thank you...
After a while the connection closes and I get an ConnectionResetError: Cannot write to closing transport
error on my console and on quart webpage I get an guild_count {'error': 'IPC Server Unreachable, restart client process.', 'code': 500}
error
when i use this how in the examples in the linux server i got ipc is not defined
but the same code on windows it works
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.