Why I am unable to send message to the user via chat postMessage api? - slack-api

We have application that integrates with Slack API and sends the messages via https://api.slack.com/methods/chat.postMessage Slack API. Recently this API started to failing to sent messages to users with error message: method_deprecated. I cannot find the reason why it's deprecated and stopped working in last month.
In order to sent message we use following:
String userId = slackFacade.getUserId(recipientEmail);
String channelId = slackFacade.getDirectChannelId(userId);
slackFacade.postMessage(
Message.builder()
.channel(channelId)
.text(message)
.mrkdwn(true)
.attachment(attachment)
.build());
where slackFacade implementation looks like:
public String getUserId(String email) throws SlackCommunicationException {
return logErrors(slackClient.getUserByEmail(email)).getUser().getId(); //users.lookupByEmail
}
public String getDirectChannelId(String userId) throws SlackCommunicationException {
return logErrors(slackClient.imOpen(userId)).getChannel().getId();
}

I've found the root cause. Actually it was not problem with chat.postMessage but it was part of the changes related to imOpen API:
https://api.slack.com/changelog/2020-01-deprecating-antecedents-to-the-conversations-api

Related

Spring AMQP- Receiving Message Object Instead of Content

I'm using Spring AMQP to send message from one microservice to other one and get response.
I can send message and receive content with this code part:
public void sendAmqpCoreMessage(Message message) throws JsonProcessingException {
List<MyCustomType> response = rabbitTemplate.convertSendAndReceiveAsType("jms.durable.queues", this.queue.getName(), message, new ParameterizedTypeReference<List<MyCustomType>>() {
});
logger.info("Response: {}", new ObjectMapper().writeValueAsString(response));
}
But instead of getting only message content, I need the whole Message object because I'm using some headers which stay in messageProperties of response which's type is Message.
How can I get Message object as response?
Don't use the convert... methods with a Message, just use sendAndReceive().

Sending messages to specific users in Teams using Graph API

Any endpoint for sending messages to specific users in Teams via the Graph API?
(Edited because of clarity and added Custom-Requests)
You can send messages via Graph API to private users BUT there is a problem that you can't create a new chat between two users via the Graph API. This means that if you want to send a message from a user to a user, the chat must already exist. (Messages must first have been exchanged via the MSTeams client for a chat to exist)
So make sure that you have a open chat!
If so, have a look at this MSDoc (This document explains how you can list chats from a user):
https://learn.microsoft.com/en-us/graph/api/chat-list?view=graph-rest-beta&tabs=http
After you have all your chats listed, you can have a look at this MSDoc (This document explains how you can send a message to a user):
https://learn.microsoft.com/en-us/graph/api/chat-post-messages?view=graph-rest-beta&tabs=http
Pay attention to the permissions! For sending messages and listing chats there are only delegated permissions so far AND these calls are only available in BETA, so be carefull with it.
I can only provide you Java code for an example.
(For everything I do I use ScribeJava to get an Auth-Token)
For delegated permissions you need to have a "User-Auth-Token". That means you have to use a Password-Credential-Grant like this:
private void _initOAuth2Service()
{
oAuth2Service = new ServiceBuilder(clientId)
.apiSecret(clientSecret)
.defaultScope(GRAPH_SCOPE)
.build(MicrosoftAzureActiveDirectory20Api.custom(tenantId));
//PASSWORD CREDENTIALS FLOW
try
{
oAuth2Token = oAuth2Service.getAccessTokenPasswordGrant(username, password);
}
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
catch (ExecutionException e) { e.printStackTrace(); }
}
username and password are the credentials from the user you want to send a message (sender).
Initial situation
This is my TeamsClient:
ScribeJava
Get all open chats
("me" in the URL is the user from above (sender).)
private Response _executeGetRequest()
{
final OAuthRequest request = new OAuthRequest(Verb.GET, "https://graph.microsoft.com/beta/me/chats");
oAuth2Service.signRequest(oAuth2Token, request);
return oAuth2Service.execute(request);
}
The response I get from this request looks like this:
{"#odata.context":"https://graph.microsoft.com/beta/$metadata#chats","value":[{"id":"{PartOfTheID}_{firstHalfOfUserID}-e52a55572b49#unq.gbl.spaces","topic":null,"createdDateTime":"2020-04-25T09:22:19.86Z","lastUpdatedDateTime":"2020-04-25T09:22:20.46Z"},{"id":"{secondUserChatID}#unq.gbl.spaces","topic":null,"createdDateTime":"2020-03-27T08:19:29.257Z","lastUpdatedDateTime":"2020-03-27T08:19:30.255Z"}]}
You can see that I have two open chats and get two entries back from the request.
Get the right conversatonID
You have to know that the id can be split in three sections. {JustAPartOfTheId}_{userId}#{EndOfTheId}. The {userId} is the id from your chatpartner (recipient).
This is a GraphExplorer response which gives me all users and all informations about them.
Now you can see that the first ID:
"id":"{PartOfTheID}_{firstHalfOfUserID}-e52a55572b49#unq.gbl.spaces"
matches the UserID after the "_".
You can split the ID at the "_" filter and find the ID you need.
Send Message to user
Now you know the right Id and can send a new request for the message like this:
final OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.microsoft.com/beta/chats/{PartOfTheID}_{firstHalfOfUserID}-e52a55572b49#unq.gbl.spaces/messages");
oAuth2Service.signRequest(oAuth2Token, request);
request.addHeader("Accept", "application/json, text/plain, */*");
request.addHeader("Content-Type", "application/json");
request.setPayload("{\"body\":{\"content\":\" " + "Hi Hi Daniel Adu-Djan" + "\"}}");
oAuth2Service.execute(request);
GraphAPI-Custom-Requests
In the Graph-SDK is no opportunity to use the beta endpoint except for Custom-Requests. (For these requests I also use ScribeJava to get an Auth-Token)
Set the BETA-Endpoint
When you want to use the BETA-Endpoint you have to use the setEndpoint() function like this:
IGraphServiceClient graphUserClient = _initGraphServiceUserClient();
//Set Beta-Endpoint
graphUserClient.setServiceRoot("https://graph.microsoft.com/beta");
Get all chats
try
{
JsonObject allChats = graphUserClient.customRequest("/me/chats").buildRequest().get();
}
catch(ClientException ex) { ex.printStacktrace(); }
Same response like above
Same situation with the userId => split and filter
Send message
IGraphServiceClient graphUserClient = _initGraphServiceUserClient();
//Set Beta-Endpoint again
graphUserClient.setServiceRoot("https://graph.microsoft.com/beta");
try
{
JsonObject allChats = graphUserClient.customRequest("/chats/{PartOfTheID}_{firstHalfOfUserID}-e52a55572b49#unq.gbl.spaces/messages").buildRequest().post({yourMessageAsJsonObject});
}
catch(ClientException ex) { ex.printStacktrace();
}
Here is a little GIF where you can see that I didn't type anything. I just started my little application and it sends messages automatically.
I hope this helps you. Feel free to comment if you don't understand something! :)
Best regards!
As of now, We do not have any endpoint to send messages to specific users via Graph API.
You may submit/vote a feature request in the UserVoice or just wait for the update from the Product Team.
You can vote for a below feature requests which are already created. All you have to do is enter your email ID and vote.
https://microsoftteams.uservoice.com/forums/555103-public/suggestions/40642198-create-new-1-1-chat-using-graph-api
https://microsoftteams.uservoice.com/forums/555103-public/suggestions/39139705-is-there-any-way-to-generate-chat-id-by-using-grap
Update:
Please find below one more user voice created for the same in Microsoft Graph user voices and vote for it.
https://microsoftgraph.uservoice.com/forums/920506-microsoft-graph-feature-requests/suggestions/37802836-add-support-for-creating-chat-messages-on-the-user

Proper way to NOT send a reply back from webhook

I have setup a webhook and everything is working properly, however iam used to using a long number where STOP is handled automatically, but now I have a short code where we have to handle STOP ourselves. This isnt an issue on sending a message as I can check with my 'blacklist' numbers before sending the message. My question is in the Reply webhook, what is the best way or standard way to NOT send the reply message.
Below is twilios sample code (i added the comment where i would check if they are black listed)
public class SmsController : TwilioController
{
public TwiMLResult Index(SmsRequest incomingMessage)
{
var messagingResponse = new MessagingResponse();
// check for phone number in blacklist to NOT SEND
messagingResponse.Message("The copy cat says: " +
incomingMessage.Body);
return TwiML(messagingResponse);
}
}
If the number is blacklisted and i dont want to send the reply how do I "gracefully" not reply to them as this example takes a TwiMLResult and message response. Do i just set the message to an empty string ? do I return null? Any thoughts ? Thank you !

My android project crashed when I called token.jwt for twilio chat

I am trying to generate access token for twilio chat but got this error:I have been trying to figure out where the error is coming from but can't get it figured out. I will really appreciate your help. Thanks
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zihron.projectmanagementapp, PID: 16355
java.lang.Error: javax.xml.datatype.DatatypeConfigurationException: Provider org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl not found
at javax.xml.bind.DatatypeConverterImpl.<clinit>(DatatypeConverterImpl.java:744)
at javax.xml.bind.DatatypeConverter.<clinit>(DatatypeConverter.java:78)
at javax.xml.bind.DatatypeConverter.printBase64Binary(DatatypeConverter.java:547)
at io.jsonwebtoken.impl.Base64Codec.encode(Base64Codec.java:24)
at io.jsonwebtoken.impl.Base64UrlCodec.encode(Base64UrlCodec.java:22)
at
io.jsonwebtoken.impl.AbstractTextCodec.encode(AbstractTextCodec.java:31)
at io.jsonwebtoken.impl.DefaultJwtBuilder.base64UrlEncode(DefaultJwtBuilder.java:314)
at io.jsonwebtoken.impl.DefaultJwtBuilder.compact(DefaultJwtBuilder.java:282)
at com.twilio.jwt.Jwt.toJwt(Jwt.java:100)
at ZihronChatApp.token.TokenGenerator.getToken(TokenGenerator.java:34)
at com.zihron.projectmanagementapp.ChatActivity.onCreateView(ChatActivity.java:43)
I have my details below:
public AccessToken getToken() {
// Required for all types of tokens
String twilioAccountSid ="AC601f2c7***7ed***640***264c***d0d";
String twilioApiKey = "SK684***dda***c81****6c4a****093**";
String twilioApiSecret ="96****dbc06****b74d50***b9***3*4";
String serviceSid="IS***a29****e24****5d****4b20**3e*";
String identity = "joshua.hamilton#gmail.com";
ChatGrant grant = new ChatGrant();
grant.setServiceSid(serviceSid);
AccessToken token = new AccessToken.Builder(twilioAccountSid,
twilioApiKey, twilioApiSecret)
.identity(identity).grant(grant).build();
Log.e("++==--",""+token.toJwt());
//.identity(identity).grant(grant);
return token;
}
Twilio developer evangelist here.
The Twilio Java library is not intended for use within Android projects.
The issue here is that you should not be storing your credentials within your application. A malicious user could decompile your application, take your credentials and abuse them.
Instead, you should create a server (or use some sort of serverless environment, like Twilio Functions) that can run this code and return the token. You should then make an HTTP request from your Android application to fetch that token. Check out the Twilio Programmable Chat Android Quickstart to see how it's done there.

how to Send an SMS through java by using twilio sdk

I am trying to send an sms from twilio API,but i am getting an error for the getMessageFactory().
MessageFactory messageFactory = client.getAccount().getMessageFactory();
The method getMessageFactory() is undefined for the type Account
what is the problem ?
I am pasting entire code below :
import java.util.*;
import com.twilio.sdk.*;
import com.twilio.sdk.resource.factory.*;
import com.twilio.sdk.resource.instance.*;
import com.twilio.sdk.resource.list.*;
public class TwilioTest {
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "[Accountsid]";
public static final String AUTH_TOKEN = "[AuthToken]";
public static void main(String[]args) throws TwilioRestException {
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
// Build the parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("To", "+16518675309"));
params.add(new BasicNameValuePair("From", "+14158141829"));
params.add(new BasicNameValuePair("Body", "Hey Jenny! Good luck on the bar exam!"));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
Message message = messageFactory.create(params);
System.out.println(message.getSid());
}
}
I added all the required jars file and account sid and authtoken which i got from registering on twilio.com website i added valid phone nos
Are you on a free trial account using the java helper library? If so, you will want to double check that you're following a few key steps:
Be sure to verify any non-Twilio phone number before sending or
receiving any SMS messages to/from it.
You will be able to send SMS from your Twilio SMS enabled number, but not from your verified personal number. This rule will also apply
after the trial.
Alphanumeric Sender IDs cannot be used with trial accounts.
You may be eligible to use Global SMS on your trial account. If this is something you're attempting learn more here.

Resources