Get Member details using Java in Microsoft Bot Framework SDK - java

I am currently working on delivering 1:1 messages to the users in Teams.
Problem Statement: I am having trouble trying to get the member details to populate the Channel Account to set the ConverstationParameters object to create conversation if the user is not part of a team. Is there a way I could get the details of the user without having the user part of a Team. I wasn't able to find any reference documentation to how to get this information for Java.
Below is my code snippet:
Setup credentials and initialize a connection using Connector Client.
Populate Channel account with recipient details for set members on Conversation Parameters Object.
Activity message = MessageFactory.text("Hello World");
MicrosoftAppCredentials credentials = new MicrosoftAppCredentials(appClientID, appClientSecret);
try (ConnectorClient client = new RestConnectorClient(serviceUrl, credentials)) {
logger.info("** Connector Client Set: {} **", client);
ConversationParameters conversationParameters = new ConversationParameters();
conversationParameters.setIsGroup(false);
CompletableFuture<ChannelAccount> user = ((Conversations) client.getConversations())
.getConversationMember(recipient, teamsInternalId); // Don't want to use this because the user has to be part of the same team which is not true in our case.
logger.info("** Aysnc get User details call **");
logger.info("** AAID: {} **", user.get().getAadObjectId());
try {
conversationParameters.setMembers(Collections.singletonList(user.get()));
} catch (ErrorResponseException e) {
logger.error("** User Error : {}**", e.getMessage());
}
conversationParameters.setTenantId(tenantId);
TenantInfo tenantInfo = new TenantInfo(tenantId);
TeamsChannelData channelData = new TeamsChannelData();
channelData.setTenant(tenantInfo);
conversationParameters.setChannelData(channelData);
CompletableFuture<ConversationResourceResponse> conversationResourceResponse = new CompletableFuture<ConversationResourceResponse>();
try {
conversationResourceResponse = client.getConversations()
.createConversation(conversationParameters);
logger.info("** Create Conversation: {} **", conversationResourceResponse.get().getId());
} catch (ErrorResponseException e) {
logger.error("** Create Conversation : {} **", e.getMessage());
}
CompletableFuture<ResourceResponse> response = client.getConversations()
.sendToConversation(conversationResourceResponse.get().getId(), message);
logger.info("** Send Conversation **", response.get().getId());

I solved the above requirement following these steps:
Check if my app is installed for the user using Graph API.
If not installed, force install the app for the user using Graph API.
Then retrieve the conversation chat id.
Use this chat id to send the message to the user.
There steps are outline here on the MSFT reference page:
https://learn.microsoft.com/en-us/microsoftteams/platform/graph-api/proactive-bots-and-messages/graph-proactive-bots-and-messages?tabs=dotnet
I hope this answer helps anyone in the same boat who would like to send messages directly 1:1 from an app to a Teams user without any mutual Team condition.

Related

Watch Google Calendar event for changes and updating server-side

I'm trying to listen to a Google Calendar event I created using a watch request but I have no clue how to get the event details once I get the push notification.
So this is what I have so far, I create the Calendar event using JavaScript (it prompts the user for authorization):
function createEvent(data) {
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': data
});
request.execute(function(event) {
if (!event.code) {
openToast('The event was added to your Google Calendar')
watchEvent(data.id);
}
});
}
And then I create a watch request to get the PUSH notifications:
function watchEvent(eventId) {
gapi.client.calendar.events.watch({
auth: gapi.auth2.getAuthInstance(),
resource: {
id: eventId,
type: 'web_hook',
address: webhookUrl
},
calendarId: 'primary'
}).execute(function onWatchCalendarEvent(event) {
if (event.error) {
console.error('Error creating event watch webhook', event.error);
}
});
}
So far so good, this is working OK and I receive a PUSH notification with the channelID from which I can get my own internal meetingId.
#PostMapping
public void onCalendarEventUpdate(#RequestHeader(name = "x-goog-channel-id") String channelId,
#RequestHeader(name = "x-goog-resource-state") String resourceState) {
log.info("Received Google Calendar event update notification: " + resourceState);
// only when the event is modified google posts the resource state as "exists"
// (what kind of name is that anyway?)
if (resourceState.equals("exists")) {
// get the meeting ID from the channel ID
Long meetingId = findMeetingIdFromChannelId(channelId);
calendarService.updateMeeting(meetingsService.findById(meetingId));
}
}
I've read the docs for Authorizing Requests, PUSH Notifications and Java API Getting Started but they all prompt for the user authorization. Since this PUSH notification is happening asynchronously how am I supposed to get the updated event details? Thanks
if you have the calendar and event id (e.g. from the notification you get from Google that you receive and parse at your webhookUrl location), you can make calendar api calls to get all the event details: https://developers.google.com/calendar/api/v3/reference/events/get

Youtube Live API get game information

I would like to integrate with the youtube livestream api.
I noticed that many live streams on youtube show the game the streamer is currently playing when their stream is open in the browser. however, when looking at the api documentation, it seems that this information is missing.
Looking at other similar apis from streaming companies such as the Twitch and Mixer, this data is retrievable. I was hoping that someone could point me in the direction of how i can find it when dealing with youtube, or how i can put in a request to get this information added as i feel it would make the api more complete.
Here is a code example that illustrates what i am trying to do:
// This OAuth 2.0 access scope allows for read-only access to the
// authenticated user's account, but not other types of account access.
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.readonly");
try {
// Authorize the request.
Credential credential = Auth.authorize(scopes, "listbroadcasts");
// This object is used to make YouTube Data API requests.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
.setApplicationName("youtube-cmdline-listbroadcasts-sample").build();
// Create a request to list broadcasts.
YouTube.LiveBroadcasts.List liveBroadcastRequest =
youtube.liveBroadcasts().list("id,snippet");
// Indicate that the API response should not filter broadcasts
// based on their type or status.
liveBroadcastRequest.setBroadcastType("all").setBroadcastStatus("all");
// Execute the API request and return the list of broadcasts.
LiveBroadcastListResponse returnedListResponse = liveBroadcastRequest.execute();
List<LiveBroadcast> returnedList = returnedListResponse.getItems();
// TODO: Get the name of the game the broadcasts are associated with
}
} catch (GoogleJsonResponseException e) {
System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getMessage());
t.printStackTrace();
}
}
As you can see, the TODO in the snippet above highlights what I am trying to do.
To make it more clear, here is an example of a broadcast in the browser. Please make note that it displays the name of the game "Fortnite":
https://imgur.com/a/xzMim6v

I get chatId in tdlib but i can not get message (tdAPI or telegram database library for java)

I am trying to use telegram database library for java (tdlib or tdapi) but when i get chatId of a channel by SearchPublicChat and try to get messages or view messages i get an error.
Error{code=6 message= Chat not found}
I can not understand why the chatId i receive above why when i pass it to another method i get that error
Please help me about that problem and that library.
Thank you.
example for getting last 15 messages from chat
String username = "any_chat_public_link";
TdApi.SearchPublicChat searchPublicChat=new TdApi.SearchPublicChat(username);
TG.getClientInstance().send(searchPublicChat, new Client.ResultHandler() {
#Override
public void onResult(TdApi.TLObject object) {
TdApi.Chat chat = (TdApi.Chat) object;
TdApi.Message topMessage = chat.topMessage;
long chatId = chat.id;
TdApi.GetChatHistory getChatHistory = new TdApi.GetChatHistory(chatId, topMessage.id, 0, 15);
TG.getClientInstance().send(getChatHistory, new Client.ResultHandler() {
#Override
public void onResult(TdApi.TLObject object) {
TdApi.Messages messages = (TdApi.Messages) object;
}
});
}
});
Before requesting chat by id the TdLib must know about this chat in current session. You need search this chat by #mention_link if it public, or getting whole your chat list. Also, the library will be know about chat if some action happens with this chat (like new message from chat, chat updated...)
And this applies also to messages, users and etc. You can request it by id only when TdLib know about this entity.
Before receiving the message history, you need to subscribe to the chat by sending TdApi.JoinChat. The procedure is as follows:
1) TdApi.SearchPublicChat
2) TdApi.JoinChat
3) TdApi.GetChatHistory
TdApi.GetChatHistory requires the id of the last chat message. It can be obtained using the TdApi.GetChat method.
I used tdlib/example. Information about chats is updated automatically by the getMainChatList method, then it can be obtained from chats.get(chatId)

How can i add extra key in UrbanAirship API using java

I am sending push notifications using UrbanAirship API using java.
Here is the doc: http://docs.urbanairship.com/api/
I want to send a push notifications with custom key/value. For example, I want send to following to Android/iOS device
name: "Jack"
String appKey = "appKey";
String appSecret = "appSecret";
// Setup an authenticated APIClient with your application key and
// application master secret.
APIClient apiClient = APIClient.newBuilder()
.setKey(appKey)
.setSecret(appSecret)
.build();
// Setup a push payload to send to the API with our handy builders
PushPayload payload = PushPayload.newBuilder()
.setAudience(Selectors.all())
.setNotification(Notifications.notification("UA Push"))
.setDeviceTypes(DeviceTypeData.of(DeviceType.IOS))
.build();
// Try and send, handle anything that comes up
try {
APIClientResponse<APIPushResponse> response = apiClient.push(payload);
logger.info("Sent a push message!");
}
// Non 200 responses throw an APIRequestException. Check the documentation
// to debug your request.
catch (APIRequestException ex){
logger.error("Non 200 request, checking error details and taking action");
}
// An underlying error occurred, most likely outside of the scope of the
// UA library, do some HTTP debugging
catch (IOException e){
logger.error("Broken pipe what?");
}
Here is the code reference for android - https://github.com/urbanairship/java-library/blob/master/src/test/java/com/urbanairship/api/push/model/notification/android/AndroidDevicePayloadTest.java
How can i do send push notification with custom key/value using AndroidDevicePayload ?
You can create your notification like this:
public PushPayload createPushPayloadCustom(String namedUser, String message) {
Notification notification = Notification.newBuilder()
.addDeviceTypeOverride(DeviceType.IOS, IOSDevicePayload.newBuilder()
.setAlert(message)
.build())
.addDeviceTypeOverride(DeviceType.ANDROID, AndroidDevicePayload.newBuilder()
.setAlert(message)
.build())
.build();
return PushPayload.newBuilder()
.setAudience(Selectors.namedUser(namedUser))
.setNotification(notification)
.setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID, DeviceType.IOS))
.build();
}
You can add to the "extras" object any key/value:
DeviceTypeData deviceTypeData = DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID);
IOSDevicePayload iosPayload = IOSDevicePayload.newBuilder()
.setAlert(message)
.addExtraEntry("custom_ios_key", "custom value for IOS")
.build();
AndroidDevicePayload androidPayload = AndroidDevicePayload.newBuilder()
.setAlert(message)
.addExtraEntry("custom_android_key", "custom value for Android")
.build();
PushPayload payload = PushPayload.newBuilder()
.setAudience(Selectors.namedUser(email))
.setNotification(Notifications.notification(iosPayload,androidPayload))
.setDeviceTypes(deviceTypeData)
.build();
Then in the received push, you will find the object:
For more details go to urbanairship official documentation

Android Facebook Error: Failed to generate preview for user

I am trying to post a Custom Open graph story in Facebook integration with SDK 4.5 , but i am not able to post it. i have created a object and action in my code
I am getting this error:
Failed to generate preview for user.com.facebook.http.
protocol.ApiException: [code] 100 [message]: (#100)
App xxxx is not allowed to create actions of type
restaurant:Wants To Visit for user xxxxx [extra]:
My code:
public void SongRequest(){
try {
// Create an object
ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
.putString("og:type", "restaurant.restaurant")
.putString("og:title", "Peddlers")
.putString("og:image", "https://scontent.fdel1-1.fna.fbcdn.net/hphotos-xpt1/v/t1.0-9/11996901_943588275699701_6661729706633501716_n.jpg?oh=5ebb6e29eff2009e0f4c68f86b06923d&oe=56A8B7CE")
.putString("og:description", "Peddlers Under The Big Ben")
.putString("restaurant:contact_info:street_address", "1601 Willow Rd.")
.putString("restaurant:contact_info:locality", "Menlo Park")
.putString("restaurant:contact_info:region", "California")
.putString("restaurant:contact_info:postal_code", "160022")
.putString("restaurant:contact_info:country_name", "India")
.putString("restaurant:contact_info:email", "brian#example.com")
.putString("restaurant:contact_info:phone_number", "212-555-1234")
.putString("restaurant:contact_info:website", "https://www.facebook.com/peddlersrock")
.putString("place:location:latitude", "30.70516586")
.putString("place:location:longitude", "76.8010025")
.putString("og:url", "https://www.facebook.com/CompetentGroove")
.build();
//Then create an action and link the object to the action.
// Create an action
ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
.setActionType("restaurant.wants_to_visit")
.putObject("restaurant", object)
.build();
//Finally, create the content model to represent the Open Graph story.
// Create the content
ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName("restaurant")
.setAction(action)
.build();
//Present the Share dialog by using the show method on ShareDialog.
ShareDialog.show(HelloFacebookSampleActivity.this, content);
} catch (Exception e) {
Log.e("Graph Stories.Exception", e.toString());
}
}

Categories