FastAPI WebSocket - websocket

I have a background process, which does a file preparation after receiving a file on the endpoint.
I have a websocket defined also:
#app.websocket_route("/ws/{uid}")
async def websocket(websocket: WebSocket):
await websocket.accept()
await websocket.send_text("Hello")
await websocket.close()
This solution sends the Hello text when the user connects.
But I want to send the text only after the background process is finished.
So my aim is to define a websocket in other function and from there send the text to a websocket.
How can i do it?

Related

In a group chat, should the new message event (websocket) be sent by the client or the API?

I have a doubt, in a group chat system that has a database with a rest API, who should issue the event of a new message?
The client or the endpoint to create the new message?
For example: X user sends a message to group Y, then uses the api endpoint api.com/message-create and that endpoint emits the message-create event through websocket
Example 2: X user sends a message to group Y, then uses the api api.com/message-create endpoint and the endpoint does not emit the message-create event, but was emitted when the user pressed the send message button
I still don't quite understand if it would occupy more websocket channels to achieve that, if a global one is enough, etc.
The server should be responsible for communication logic. So your first example is better.
But: why do you use two communication channels for sending an creating messages?
If you use websocket, you don't need create a message from a client by using additional rest endpoint.
This approach is prone to errors. For example if the client will loose network connection after sending message through websocket and before executing call to the REST endpoint?
The message will not be stored in a database.
Your flow should looks as follows:
User clicks the send button.
Message is send through the websocket.
Message is stored in the database asynchronously (you can do it directly from communication server, or use rest endpoint)
Emit "new message" event to the group.

Send Slack Modal Data to Third Party

Is it possible to send data gathered from a Slack modal to an external site?
I’m using Slack Bolt for JavaScript
I’ve tried receiver.router.post('siteToSendData', (req, res) => { // You're working with an express req and res now. console.log('post to slack') res.send(dataToSend); });
You cannot send the captured data directly to a third party site. What you can do instead, is process the submission event.
https://api.slack.com/surfaces/modals/using#handling_submissions
Slack Bolt Reference : https://slack.dev/bolt-js/concepts#view_submissions
The captured data will be sent to your application first. You can then re-route it to the desired external website.
Here is example of payload that you can expect: https://api.slack.com/reference/interaction-payloads/views

How to allow discord bot to respond to webhook. Python. Discord.py

I have a problem trying to get a webhook to interact with a bot
For some reason, the bot doesn't respond to commands initiated by the webhook
Is there a way to make sure it initiates?
It works normally otherwise
My command:
# registering new commands that can be called by the flask webhook
#client.command()
async def new_message_received(ctx, trade_hash: str = ''):
print(f'New Trade Received! {trade_hash}')
paxful_cogs = client.get_cog('Paxful_Cogs')
await paxful_cogs.new_trade_received(trade_hash=trade_hash)
await ctx.send(f'{trade_hash} executed.')
print(f'Trade Done Execution! {trade_hash}')
My webhooks are sent successfully, but the bot does not respond to them.
Bot Responds to Me, but not to webhook.
Okay, figured it out with a lot of help from the python discord server.
#client.event
async def on_message(message):
# Manually get the invocation context from the message
ctx = await client.get_context(message)
# Verify that the context has a command and can be used
if ctx.valid:
# Invoke the command using the earlier defined bot/client/command
await client.invoke(ctx)
https://i.gyazo.com/d23edb65efeeaa834c5de33d70f00484.png
Basically, we're overriding the on_message fx, checking to see if the message matches our prefix/command structure with ctx.valid and then forcing the command to be processed with client.invoke(ctx) regardless if it's from a bot/webhook or not.

Webhook Switch Channel With Bot

I want that when you use the command webhook should send the message in the channel where the code is used.But I dont know how to do it please help.
#bot.command()
async def deneme(ctx, test):
webhook = Webhook.partial(webhookid, webhooktoken, adapter=RequestsWebhookAdapter())
webhook.send(test, username=ctx.author.name, avatar_url=ctx.author.avatar_url)
If your channel already has a created webhook you can get a list of all of the webhook of the channel the message is sent in by using ctx.channel.webhooks() picking one and getting its url by doing WEBHOOK.url(). If your channel does not have a webhook you can create one by using await ctx.channel.create_webhook(name='WEBHOOK NAME') you can assign this to a variable and get the url by using WEBHOOK.url().
NOTE: Creating a webhook is only supported by discord.py-rewrite.
Alternatively you can just use your bot to reply instead of using a webhook by using ctx.channel.send()

Detect when client closes a connection from aiohttp request handler

I have a long running request during which I push data down to a client as it is received. However, the request requires some resources that are created server side that I'd like to clean up whenever the client disconnects. I've looked through the docs, but I can't seem to find a way to detect when that happens. Any ideas?
This isn't super obvious looking at the docs, but the key here is that the asyncio server will throw a CancelledError into handler coroutine when the connection is closed. You can catch the CancelledError wherever you wait for an asynchronous operation to complete.
Using this, I clean up after a connection with something like this:
async def passthrough_data_until_disconnect():
await create_resources()
while True:
try:
await get_next_data_item()
except (concurrent.futures.CancelledError,
aiohttp.ClientDisconnectedError):
# The request has been cancelled, due to a disconnect
await do_cleanup()
# Re-raise the cancellation error so the handler
# task gets cancelled for real
raise
else:
await write_data_to_client_response()

Resources