How to allow discord bot to respond to webhook. Python. Discord.py - 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.

Related

Stripe webhook returns 301 error but works in localhost

I have implemented a Stripe webhook to handle payment events in my Django rest framewrok application. When I test the webhook locally, it works as expected and I am able to receive and process the payment events. However, when I deploy the application and try to use the webhook, I receive a 301 error from Stripe. There is no response from the webhook call as shown in Stripe dashboard. The webhook URL is reachable and I am able to access it without any issues. I have also checked the logs and there are no errors on the server side, which mean that the content of post function is not executed.
I am not sure what is causing this issue and would appreciate any help in troubleshooting and fixing it. Thank you.
The webhook url
urlpatterns = [
path('stripe-webhook', stripe_webhook.as_view()),]
The webhook function is as shown:
class stripe_webhook(APIView):
def post(self, request):
#verify webhook request
print(request.body)
payload = request.body
sig_header = request.headers['STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError as e:
# Invalid payload
raise e
except stripe.error.SignatureVerificationError as e:
# Invalid signature
raise e
# Handle the event
if event['type'] == 'payment_intent.succeeded':
payment_intent = event['data']['object']
print(payment_intent)
else:
print('Unhandled event type {}'.format(event['type']))
return HttpResponse(status=200)
You might happen to have a middleware or a load balancer for the server hosting your webhook endpoint which might explain 301 status code. Just a guess though. You would likely want to talk to your hosting provider to see if they can shed any lights on why the requests are being redirected once they come in.

FastAPI 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?

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()

Loopback js connector rest with async / await

I am using the loopback-connector-rest (version 5.2.0) in order to invoke a third party API.
Even though i successfully invoke the API, it seems that i cannot get the response using async await operation.
res = await app.models.coupon.invoke({...});
I couldn't find an example with async await in the current docs.
Am i missing something?
Thanks.
Update
As it turns out everything was working as expected. The problem arised from the fact that i was invoking the third party API inside an async loop using await Promise.all() but i was trying to get the promises before all promises got resolved/rejected.
Thanks everyone for your time.

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