How to select a button from a interactive message with a bot? - slack

I'm trying to get a bot to "click" a button on an interactive message in Slack (preferably as a bot, but using a user token works too).
I've found that the link to send the action information to be
https://blue-hybrid.slack.com/api/chat.attachmentAction
My problem is I can't find any documentation for "chat.attachmentAction." Looking at the request sent when using my browser, it has one http argument: "_x_id" and the payload is a WebKitForm, containing 4 items: payload, client_id, payload_id, and token.
I'm sure if I'm just not sending the appropriate data or authentication or what. All of my POSTs return "invalid_payload" or "invalid_arg_name."
Any help is greatly appreciated.

Looks like I figured it out, finally!
I had to work it out the old fashioned way. Slack Customer Support would only help with the official public API. I'll leave the solution here in Javascript.
To do this, you need 3 things:
choice_num
the number of the choice within the list of options.
e.g. If a message has the buttons (from left to right): yes, no, and maybe, then yes=0, no=1 and maybe=2.
message
the json of the interactive message
SLACK_TOKEN
your slack token (not sure if bot tokens work, user tokens do however)
The method chat.attachmentAction itself requires 3 arguments:
payload
service_id AND/OR bot_user_id
token
args = encodeURI(
'payload={'
+ '"actions":[' + JSON.stringify(message.attachments[0]["actions"][choice_num]) + '],'
+ '"attachment_id":"' + message.attachments[0]["id"] + '",'
+ '"callback_id":"' + message.attachments[0]["callback_id"] + '",'
+ '"channel_id":"' + message.channel + '",'
+ '"message_ts":"' + message.ts + '"}'
+ '&service_id=' + message.bot_id
+ '&bot_user_id=' + message.user
+ '&token=' + SLACK_TOKEN
)
request_url = 'https://YOURSLACKTEAM.slack.com/api/chat.attachmentAction?' + args
then just send an async POST to the request_url and you should get back something like this:
{"replaced":true,"ok":true}

Related

How can I send an email with my outlook add-in

my friends and I are making an outlook add-in that can take the text from an email in the user's inbox and send it to our email address.
the email part of this is proving to be very difficult.
So far we have tried to do this with nodemailer and similar modules but from what I can tell you would need a server which we would like to avoid.
To get around this we copied some code and made a website that sends the email for us. The problem with this is we cant figure out how to do this all within the taskpane which you can see in the first image. When we click 'submit' nothing will happen until we open the same thing in a separate HTML popup which can be seen in image 2.
Is there a way to do this only from the taskpane so that all the user has to do is click one button that will both take the text and send it to us automatically? If there isn't, how do we get the content of the email from the task pane to the popout (from the right side of image two to the left side)?
You can use makeEwsRequestAsync() to send an email. Here is a sample you could adjust. (note this example sends a mail with the version number of Outlook in the body, but you can adjust it to put whatever data you want inside). See documentation for makeEwsRequestAsync, to see what else it supports that may solve your scneario: https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/web-services
var request = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
' <soap:Header><t:RequestServerVersion Version="Exchange2010" /></soap:Header>'+
' <soap:Body>'+
' <m:CreateItem MessageDisposition="SendAndSaveCopy">'+
' <m:SavedItemFolderId><t:DistinguishedFolderId Id="sentitems" /></m:SavedItemFolderId>'+
' <m:Items>'+
' <t:Message>'+
' <t:Subject>Hello, Outlook!</t:Subject>'+
' <t:Body BodyType="HTML">This message was sent from ' + Office.context.mailbox.diagnostics.hostName + ', version ' + Office.context.mailbox.diagnostics.hostVersion + '!</t:Body>'+
' <t:ToRecipients>'+
' <t:Mailbox><t:EmailAddress>' + Office.context.mailbox.userProfile.emailAddress + '</t:EmailAddress></t:Mailbox>'+
' </t:ToRecipients>'+
' </t:Message>'+
' </m:Items>'+
' </m:CreateItem>'+
' </soap:Body>'+
'</soap:Envelope>';
Office.context.mailbox.makeEwsRequestAsync(request, function (asyncResult) {
if (asyncResult.status == "failed") {
console.log("Action failed with error: " + asyncResult.error.message);
}
else {
console.log("Message sent!");
}
});
You could also use displayNewMessageFormAsync() https://learn.microsoft.com/en-us/javascript/api/outlook/office.mailbox?view=outlook-js-preview#outlook-office-mailbox-displaynewmessageformasync-member(1)
If you want to create a new mail UI, that the user has to send manually.
The response above is showing how to send an email using EWS. (Exchange Web Services). however, the question is also asking how to send the body of the message.
in order to get the body you need to call the body.getAsync() method, check our the sample.
function getSelectedData() {
Office.context.mailbox.item.body.getAsync("html" /*you can also do 'text' */, function(result){
console.log(result.value);
});
}
you can also use the consume the Microsoft Graph from the Office Add-in (instead of EWS) check out this video on how to do it. Here is how to use the Graph to send an e-mail for reference.

Python-Telegram bot running locally, but not on Heroku

I'm looking to deploy my python-telegram bot on Heroku but the bot seems to be unresponsive. The .py works just fine locally, but when I deploy it the app builds perfectly and is on, but produces no response on telegram when prompted. The code is very basic but I think I am missing something with the webhook maybe? I'm new to web stuff as my background is more in data science. Below is my code and procfile.
"""import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
import ftx
client = ftx.FtxClient()
telegram_bot_token = "token"
updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
def start(update, context):
chat_id = update.effective_chat.id
context.bot.send_message(chat_id=chat_id, text= "1 ***=" + "$" + str(client.get_market('***/USD')['last']) + "\n" + "24 Change =" + str(round(client.get_market('***/USD')['change24h'],2)*100) + "%" + "\n" + "24 Hour Volume =" + str(client.get_market('***/USD')['volumeUsd24h']) + "USD"
+ "\n"*2 + "The information presented by the price tracker is not meant to be taken as financial advice.")
#I think over here I need something else
dispatcher.add_handler(CommandHandler("***", start))
updater.start_polling()"""
#Proc
"""worker: python bot.py"""
I'm happy to write a if dunder main, but I'm unsure still if I even need a webhook. Thanks!
AFAIK Heroku doesn't support long polling, so you should use a webhook. python-telegram-bot comes with a built-in webhook. See here and also this skeleton-repo.

Request signature failing for Alibaba Cloud API call

I tried creating a method in Postman and got really close but am having issues with the signature. We are trying to query the IP ranges for VPCs to add to a WAF rule, in order to allow traffic to a secure application.
Postman allows a pre-request script, in Javascript, and supports a handful of included JS libraries, including CryptoJS.
The code here creates exactly the request that Ali Cloud says needs to be signed. It signs with HMAC-SHA1 from CryptoJS and encodes to base 64.
All of the variables are included in the request parameters. I'm not sure what else it could be complaining about.
var dateIso = new Date().toISOString();
var randomString = function(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
var accesskeyid = "LTAI4GC7VEijsm5bV3zwcZxZ"
var action = "DescribePublicIPAddress"
var format = "XML"
var regionid = "cn-shanghai-eu13-a01"
var signaturemethod = "HMAC-SHA1"
var signaturenonce = randomString(16)
var signatureversion = "1.0"
var timestamp = dateIso.replace(/:/gi, "%253A")
var version = "2016-04-28"
pm.environment.set("AccessKeyId", accesskeyid)
pm.environment.set("Action", action)
pm.environment.set("Format", format)
pm.environment.set("RegionID", regionid)
pm.environment.set("SignatureMethod", signaturemethod)
pm.environment.set("SignatureNonce", signaturenonce)
pm.environment.set("SignatureVersion", signatureversion)
pm.environment.set("Timestamp", dateIso)
pm.environment.set("Version", version)
var request = "GET&%2F&" + "AccessKeyID%3D" + accesskeyid + "%26Action%3D" + action + "%26Format%3D" + format + "%26RegionID%3D" + regionid + "%26SignatureMethod%3D" + signaturemethod + "%26SignatureNonce%3D" + signaturenonce + "%26SignatureVersion%3D" + signatureversion + "%26Timestamp%3D" + timestamp + "%26Version%3D" + version
pm.environment.set("Request", request)
var hash = CryptoJS.HmacSHA1(request, "spwH5dNeEm4t4dlpqvYWVGgf7aEAxB&")
var base64 = CryptoJS.enc.Base64.stringify(hash)
var encodesig = encodeURIComponent(base64)
pm.environment.set("Signature", encodesig);
console.log(base64)
console.log(request)
The console output shows:
Signature: XbVi12iApzZ0rRgJLBv0ytJJ0LY=
Parameter string to be signed:
GET&%2F&AccessKeyID%3DLTAI4GC7VEijsm5bV3zwcZvC%26Action%3DDescribePublicIPAddress%26Format%3DXML%26RegionID%3Dcn-shanghai-eu13-a01%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3DiP1QJtbasQNSOxVY%26SignatureVersion%3D1.0%26Timestamp%3D2020-06-01T15%253A38%253A12.266Z%26Version%3D2016-04-28
Request sent:
GET https://vpc.aliyuncs.com/?AccessKeyID=LTAI4GC7VEijsm5bV3zwcZvC&Action=DescribePublicIPAddress&Format=XML&RegionID=cn-shanghai-eu13-a01&SignatureMethod=HMAC-SHA1&SignatureNonce=iP1QJtbasQNSOxVY&SignatureVersion=1.0&Timestamp=2020-06-01T15:38:12.266Z&Version=2016-04-28&Signature=XbVi12iApzZ0rRgJLBv0ytJJ0LY%3D
Response Received:
<?xml version='1.0' encoding='UTF-8'?><Error><RequestId>B16D216F-56ED-4D16-9CEC-633C303F2B61</RequestId><HostId>vpc.aliyuncs.com</HostId><Code>IncompleteSignature</Code><Message>The request signature does not conform to Aliyun standards. server string to sign is:GET&%2F&AccessKeyID%3DLTAI4GC7VEijsm5bV3zwcZvC%26Action%3DDescribePublicIPAddress%26Format%3DXML%26RegionID%3Dcn-shanghai-eu13-a01%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3DiP1QJtbasQNSOxVY%26SignatureVersion%3D1.0%26Timestamp%3D2020-06-01T15%253A38%253A12.266Z%26Version%3D2016-04-28</Message><Recommend><![CDATA[https://error-center.aliyun.com/status/search?Keyword=IncompleteSignature&source=PopGw]]></Recommend></Error>
When I check the "server string to sign" from the response and the parameter string that was signed in a compare, they are identical.
It looks like everything is built as needed but the signature is still barking. Guessing I missed something simple but haven't found it yet.
Note: The accesskeyID and key posted are for example purposes and not a real account so this code will not copy and paste to execute in Postman.
PS - I learned quite a bit from the other few threads on this topic, which is how I got to this point. akostadinov was super helpful on another thread.
I believe you have double encoded &. I have implemented other Alibaba Cloud REST APIs successfully. Could you please check this.
Following is the expected string to sign format:
GET&%2F&AccessKeyId%3Dtestid&Action%3DDescribeVpcs&Format%3DXML&
SignatureMethod%3DHMAC-SHA1&SignatureNonce%3D3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&SignatureVersion%3D1.0&TimeStamp%3D2016-02-23T12%253A46%
253A24Z&Version%3D2014-05-15
A bit late to the party, but as this is the first result when googling for the IncompleteSignature error, I thought I might comment and hopefully save someone else the grief I have been through.
For me, the subtle detail that I missed in the official documentation here is that the key used for the signature requires an ampersand & to be added to the end, before being used.
As soon as I caught that, everything else worked perfectly.

how to track ajax requests and responses through selenium webdriver?

I have a use-case where, I will fill the career form on the given site through selenium web-driver, after that when i will click on the submit button, I want to know, whether the form is successfully submitted or not.
Basically there are 2 cases possible in this case,
a) site populate error through java-script on career page
b) front-end make a call to server in form of ajax request, and get some response.
Is there any way, by which i can identify, whether browser is making a ajax call on click or not, and if it is making ajax call, response status code of that call?
In my project I'm using something like this:
object response = ((IJavaScriptExecutor) Driver.WebDriver).ExecuteAsyncScript(
"var url = arguments[0];" +
"var callback = arguments[arguments.length - 1];" +
"var xhr = new XMLHttpRequest();" +
"xhr.open('GET', url, true);" +
"xhr.onreadystatechange = function() {" +
" if (xhr.readyState == 4) {" +
" callback(xhr.getAllResponseHeaders());" +
" }" +
"};" +
"xhr.send();", url);
You can change xhr.getAllResponseHeaders() to get all response not only header.
After that you can serialize response, or even parse it and try to find text

How to send feed back information to server via my application?

In my application feedback form will be used .i have to send feedback information to server.please help me how to send information to server in windows phone.
You could use the EmailTask:
var emailTask = new EmailComposeTask
{
To = "feedback#mycompany.com",
Subject = subjectTextBox.Text,
Body = String.Format("Dear {0},/nPlease let {1}" +
" know that I would like to {2}.\nThis " +
"has been bothering me for {3} days now. " +
"I hope you can help me out. Kindest " +
"regards,\n{4}\n", toTextBox.Text,
nameTextBox.Text, activityTextBox.Text,
daysTextBox.Text, senderTextBox.Text)
};
emailTask.Show();
or you could publish a web service or you could have a web page that you point the WebBrowser control to.
It all depends on the way you want to receive the feedback and (perhaps) continue the conversation.

Resources