How to send response back to initiator - python-3.x

so i am trying to set up a FIX server that will serve me to accept FIX messages.
i managed to receive messages from a demo client that i made.
i want to perform an action according to the received message and then return a response to the initiator.
i have added the code that i use, it somehow sends it through the acceptor back to the initiator.
import quickfix as fix
def create_fix_response_for_wm(self, session_id, message, api_response):
try:
report = quickfix50sp2.ExecutionReport()
report.setField(fix.Text(api_response.text))
report.setField(fix.ListID(message.getField(66)))
if message.getFieldIfSet(fix.OrderID()):
report.setField(fix.OrderID(message.getField(14)))
elif message.getFieldIfSet(fix.ListID()):
report.setField(fix.OrderID(message.getField(66)))
fix.Session.sendToTarget(report, session_id)
except Exception as e:
logger.exception(f'could not create response')

so after looking and testing a couple of times this is what i found.
import quickfix as fix
def create_fix_response_for_wm(self, session_id, message, api_response):
try:
report = quickfix50sp2.ExecutionReport()
report.setField(fix.Text(api_response.text))
report.setField(fix.ListID(message.getField(66)))
if message.getFieldIfSet(fix.OrderID()):
report.setField(fix.OrderID(message.getField(14)))
elif message.getFieldIfSet(fix.ListID()):
report.setField(fix.OrderID(message.getField(66)))
fix.Session.sendToTarget(report, session_id)
except Exception as e:
logger.exception(f'could not create response')
session_id = should be a SessionID object which can be built like this:
session_id = fix.SessionID("FIXT.1.1", <ACCEPTOR - SenderCompID of the acceptor configuration>, <INITIATOR - TargetCompID in the acceptor configuration >)
configuration example:
[SESSION]
SocketAcceptPort=12000
StartDay=sunday
EndDay=friday
AppDataDictionary=./glossary/FIX50SP2.xml
TransportDataDictionary=./glossary/FIXT11.xml
DefaultApplVerID=FIX.5.0SP2
BeginString=FIXT.1.1
SenderCompID=MYACCEPTOR
TargetCompID=CLIENT
session_id = fix.SessionID("FIXT.1.1","MYACCEPTOR" , "CLIENT") - in our case
you you this sessionID object when sending.
fix.Session.sendToTarget(<YOUR MESSAGE>, session_id)

Related

Getting not persistent messages from nats.io server

My question is simple:
Now this code sends empty message to subject chan.01.msg and gets message that is being currently broadcasted or prints nats: timeout. Altogether this request message is also shown (something like: Received a message on chan.01.msg _INBOX.<hash_my>.<salt_up>: b'') on subject and is not desirable there. I do filter it in callback, but I really feel that it's kinda wrong way to do it.
Can I just pull messages with desired subject?
async def msgcb(msg):
"""
Message callback function
"""
subject = msg.subject
reply = msg.reply
data = msg.data
if len(data) > 0:
print(f"Received a message on {subject} {reply}: {data}")
logging.debug("Prepare to subscribe")
sub = await nc.subscribe(subject="chan.01.msg", cb=msgcb)
logging.debug("loop process messages on subject")
while True:
await asyncio.sleep(1)
try:
resp = await nc.request('chan.01.msg')
print(resp)
except Exception as e:
print(e)
You are subscribing to the same subject where you are publishing so naturally would get the message when sending a request. To avoid receiving messages the same client produces you can use the no_echo option on connect.

send message from bot to direct message after typing /slash command

I'm trying to make SlackBot and if I call him in some public channel it works fine but when I call him (type slash-command) in any direct channel I receive "The server responded with: {'ok': False, 'error': 'channel_not_found'}". In public channels where I've invited my bot it works fine, but if I type "/my-command" in any DM-channel I receive response in separate DM-channel with my bot. I expect to receive these responses in that DM-channel where I type the command.
Here is some part of my code:
if slack_command("/command"):
self.open_quick_actions_message(user_id, channel_id)
return Response(status=status.HTTP_200_OK)
def open_quick_actions_message(self, user, channel):
"""
Opens message with quick actions.
"""
slack_template = ActionsMessage()
message = slack_template.get_quick_actions_payload(user=user)
client.chat_postEphemeral(channel=channel, user=user, **message)
Here are my Event Eubscriptions
Here are my Bot Token Scopes
Can anybody help me to solve this?
I've already solved my problem. Maybe it will help someone in the future. I've sent my payload as the immediate response as it was shown in the docs and the response_type by default is set to ephemeral.
The part of my code looks like this now:
if slack_command("/command"):
res = self.slack_template.get_quick_actions_payload(user_id)
return Response(data=res, status=status.HTTP_200_OK)
else:
res = {"text": "Sorry, slash command didn't match. Please try again."}
return Response(data=res, status=status.HTTP_200_OK)
Also I have an action-button and there I need to receive some response too. For this I used the response_url, here are the docs, and the requests library.
Part of this code is here:
if action.get("action_id", None) == "personal_settings_action":
self.open_personal_settings_message(response_url)
def open_personal_settings_message(self, response_url):
"""
Opens message with personal settings.
"""
message = self.slack_template.get_personal_settings_payload()
response = requests.post(f"{response_url}", data=json.dumps(message))
try:
response.raise_for_status()
except Exception as e:
log.error(f"personal settings message error: {e}")
P. S. It was my first question and first answer on StackOverflow, so don't judge me harshly.

Discord.py v1.0 How to retrieve every message from a channel and delete them one by one

I have a clear command setup and the idea was to delete every message in a channel which I have the name hard-coded, but since I read that the method only deletes messages newer than 14 days I figured I'd have to somehow manually retrieve all the messages and then delete each one of them with the delete method.
I looked around but every example is either from before v1.0 or doesn't use commands with context the way I do.
Code:
#self.discord_bot.command()
async def clear(ctx):
try:
if ctx.channel != self.channel_name:
return
# clear history
# retrieve messages using context ctx
# for each loop that deletes them with self.discord_bot.delete()
except Exception as e:
await ctx.trigger_typing()
await ctx.send("Oops something happened! %s" % str(e))
return
Thanks in advance!
This should be possible using channel.purge(). This will delete every message in the specified channel if the bot account has sufficient permissions.
#self.discord_bot.command()
async def clear(ctx):
try:
if ctx.channel != self.channel_name:
return
# clear history
await ctx.channel.purge(limit=None)
except Exception as e:
await ctx.trigger_typing()
await ctx.send("Oops something happened! %s" % str(e))
return

Azure Functions HTTP Trigger : How to return exception from python worker log to the API caller

I'm new to Azure functions
Wished to know how to return exception from python worker log to the API caller .
In a HTTP Trigger with COSMOS DB binding , on firing an insert call to the binding , if data already exists , it fails with
"System.Private.CoreLib: Exception while executing function: Functions.insertEntityData. Microsoft.Azure.DocumentDB.Core: Entity with the specified id already exists in the system."
How can this message be sent back to the end user ? It is not getting captured anywhere.
def main(req: func.HttpRequest, cosmosdata: func.Out[func.Document]) -> func.HttpResponse:
try:
message = ""
logging.info('Python HTTP trigger function processed a request.')
entity_name = req.route_params['entity']
status_code = 500
payload = req.get_json()
if payload:
try:
logging.info(payload)
resultant = cosmosdata.set(func.Document.from_dict(payload))
logging.info(resultant)
status_code = 200
message = "Insert Successful to %s" % (entity_name)
except Exception as e:
return func.HttpResponse(str(e), status_code=500)
else:
status_code = 400
message = "Please pass data in the POST Request"
except Exception as e:
return func.HttpResponse(str(e), status_code=500)
return func.HttpResponse(message, status_code=500)
The try / catch block is not working because you're using an Output binding to Cosmos Db, which is the one that is failing. However, it also looks weird to me because by default it performs and Upsert operation.
I believe the problem relates to your partition Key defined in the function.json file.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-cosmosdb-v2#input---python-examples

How to parse the gmail messages.get() batch response in python 3

I have batched and executed my request using the following code:
batch = BatchHttpRequest()
for msg_id in message_ids:
batch.add(service.users().messages().get(userId = 'me', id = msg_id['id']), callback = mycallbackfunc)
batch.execute()
How can I access the responses for each of the requests? I have looked through the documentation but there is no public method to get the responses.
You access the response of each request in the callback function, which is called mycallbackfunc in your example:
def process_message(request_id, response, exception):
if exception is not None:
# Do something with the exception
pass
else:
# Do something with the response
pass
batch = BatchHttpRequest()
for msg_id in message_ids:
batch.add(service.users().messages().get(userId = 'me', id = msg_id['id']), callback=process_message)
batch.execute()

Resources