I am using Javascript SDK for 1-1 chat in Quickblox, but somehow I am not able to store the chat history.
I am following this link.
var message = {
body: text,
type: 'chat',
extension: {
nick: chatUser.email,
// token from session is set on window object
token: window.token,
// MyChat is a custom class_name
class_name: 'MyChat'
}
};
I am passing the class_name and token since I saw the android sdk following the same pattern.
private Message createMsgWithAdditionalInfo(int userId, String body, Map<?, ?> addinfoParams){
Message message = new Message(QBChatUtils.getChatLoginFull(userId), Message.Type.chat);
String addInfo = ToStringHelper.toString(addinfoParams, "", Consts.ESCAPED_AMPERSAND);
//
MessageExtension messageExtension = new MessageExtension(Consts.QB_INFO, "");
try {
messageExtension.setValue("token", QBAuth.getBaseService().getToken());
messageExtension.setValue("class_name", "ChatMessage");
messageExtension.setValue("additional", addInfo);
} catch (BaseServiceException e) {
e.printStackTrace();
}
message.addExtension(messageExtension);
message.setBody(body);
return message;
}
Also in instructions I see this.
<message id="123" type="chat" to="291-92#chat.quickblox.com" from="292-92#chat.quickblox.com"><body>Hi there</body><quickblox xmlns=""><token>848d4bf336d99532deff6bf7c8bb4b7e7b1a71f9</token><class_name>ChatMessage</class_name></quickblox></message>
Here also I see token & class passed so I am guessing how to I structure in my message object so that I get it to work.
The way I have created chatService is this.
chatService = new QBChat(params);
// to send message I am using sendMessage function
// message object is same as defined above.
chatService.sendMessage(recipientID, message);
This is an old and deprecated method to store chat history
Look at this guide http://quickblox.com/developers/Chat#Server-side_chat_history
var msg = {
body: "Hey",
extension: {
save_to_history: 1
},
senderId: currentUser.id,
};
You have to use 'save_to_history' to store a message
You can use this branch as a basis
https://github.com/QuickBlox/quickblox-javascript-sdk/tree/develop.chat/samples/chat
Related
So, basically I'm trying to receive a call from provider to my app. For that purpose Quickblox gives us a listener to receive the upcoming calls onCallListener. So here is my code snippet that should work but doesn't.
const calleesIds = [4104]
const sessionType = QB.webrtc.CallType.VIDEO
const additionalOptions = {}
let callSession = QB.webrtc.createNewSession(calleesIds, sessionType, null, additionalOptions)
console.log(callSession, "SESSION")
const mediaParams = {
audio: true,
video: true,
options: {
muted: true,
mirror: true,
},
elemId: "myVideoStream"
}
QB.webrtc.onCallListener = function(session: any, extension: object) {
callSession = session
console.log('asdasd')
// if you are going to take a call
session.getUserMedia(mediaParams, function (error: object, stream: object) {
if (error) {
console.error(error)
} else {
session.accept(extension)
session.attachMediaStream("videoStream", stream)
}
})
}
P.S. I also integrated chat which works perfect!
Found the solution by myself! Whenever you create a user and dialog id, search that user in the quickblox dashboard by the dialogId and change its settings: you will see that userId and providerId is the same which is wrong. So put your userId in the userId field and save that. After that you video calling listeners will work fine!)
P. S. also in the backend replace provider token with user token.
So I'm using discord.js with this code here:
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "Getting Data..."
}
}
})
I would like to be able to edit this message afterwards, but everything I have seen requireds a message id, and I seem to be unable to get the message id off of this code.
You can edit an interaction response with this patch request (See: Followup Messages):
PATCH /webhooks/<application_id>/<interaction_token>/messages/#original
Basic example using the axios library:
axios.patch(`https://discord.com/api/v8/webhooks/${appId}/${interaction.token}/messages/#original`, { content: 'New content' });
The answer to this request will also contain the message-id.
Here is an example function that will edit the original message either as plain text or an embed object and returns the discord message object for further usage (e.g. add reply emojis etc.):
const editInteraction = async (client, interaction, response) => {
// Set the data as embed if reponse is an embed object else as content
const data = typeof response === 'object' ? { embeds: [ response ] } : { content: response };
// Get the channel object by channel id:
const channel = await client.channels.resolve(interaction.channel_id);
// Edit the original interaction response:
return axios
.patch(`https://discord.com/api/v8/webhooks/${appId}/${interaction.token}/messages/#original`, data)
.then((answer) => {
// Return the message object:
return channel.messages.fetch(answer.data.id)
})
};
Also instead of sending an initial message like "getting data..." you also can send an empty response of type 5. This is the build-in method and displays a little loading animation too :) See here (One advantage is that this way no "edited" appears.)
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 5,
},
})
I have set the project up as described in the blog post Twilio WhatsApp API and Flex in Minutes.
I followed the instructions and even after repeating the process twice, on two different accounts, when I send the message (through sandbox), the following error occurs:
cvc-complex-type.2.4.a: Invalid content was found starting with element 'Enqueue'. One of '{Sms, Message, Redirect}' is expected.
The task does not show in Flex.
I have tried checking what WhatsApp sends vs what is sent when SMS arrives. This is what a simple function says about trigger.message for SMS:
{
EventType=onMessageSent,
InstanceSid=IS5aa457db5a2d44049c95f2d0b2699f56,
Attributes={\"proxied\":true},
DateCreated=2019-01-16T12:37:43.664Z,
Index=3,
From=sms_g13aggbhlwpgk7tbah3llj2kyjpsvvju,
MessageSid=IM9123e909eeda41ac92890201a6c3f1b4,
Source=API,
AccountSid=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
ChannelSid=CHbc79143368db4680a66c6c504103619f,
RetryCount=0,
ClientIdentity=sms_g13aggbhlwpgk7tbah3llj2kyjpsvvju,
WebhookType=studio,
To=CHbc79143368db4680a66c6c504103619f,
Body=Test Message,
ChannelAttributes={
status=ACTIVE,
forwarding=true,
serviceNumber=sms_g13aggbhlwpgk7tbah3llj2kyjpsvvju,
twilioNumber=+1228xxxxxxx,
from=+44798xxxxxxx,
channel_type=sms,
proxySession=KC1be96a19ed42aca39f9b6a9f06c26997
},
WebhookSid=WHcfc83a43a7c2424693fd0053b8b00a01
}
This is what is shows for WhatsApp message:
{
ApiVersion=2010-04-01,
SmsSid=SMb44cfdb4854c41e9ee255032a5449199,
SmsStatus=received,
SmsMessageSid=SMb44cfdb4854c41e9ee255032a5449199,
NumSegments=1,
From=whatsapp:+44798xxxxxxx,
To=whatsapp:+1228xxxxxxx,
MessageSid=SMb44cfdb4854c41e9ee255032a5449199,
Body=Test Message,
AccountSid=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
NumMedia=0
}
As you can see, the ChannelAttributes and ChannelSid are missing, and this is what Flex uses.
I then tried to transform the response with a function:
exports.handler = function(context, event, callback) {
let response;
if (!event.message.ChannelAttributes) {
response = {
name: event.message.From,
channelType: 'sms',
channelSid: 'CHbc79143368db4680a66c6c504103619f'
};
}
else {
response = {
name: "WhatsApp_" + event.message.ChannelAttributes.from,
channelType: event.message.ChannelAttributes.channel_type,
channelSid: event.message.ChannelSid
};
}
const twilioResponse = new Twilio.Response();
twilioResponse.setStatusCode(200);
twilioResponse.appendHeader('Content-Type', 'application/json');
twilioResponse.setBody(response);
callback(null, twilioResponse);
};
And assign the attributes in Studio like:
{
"name":"{{widgets.MyFunction.body.name}}",
"channelType":"{{widgets.MyFunction.body.channelType}}",
"channelSid":"{{widgets.MyFunction.body.channelSid}}"
}
Unfortunately, this shows the same error.
I can't delete an object on the client side, using the destroy function, I created an admin role and gave it all the necessary rights, but unfortunately I am always sent object not found when I want to delete an object. Voila Mon code.
`
user = getCurrentParseUser();
sessionToken = user.getSessionToken();
query = new Parse.Query(BillingPackage);
billingPackage = await query.get(billingPackageId);
console.log("billingPackage",billingPackage); //the object is retrieve here
if(billingPackage){
await billingPackage.destroy({sessionToken:sessionToken});
return {status: true, message: "The Billing Package Has Been Deleted"}
}else{
return {status: false, message: "The Billing Package Already Deleted"}
}`
The CLP Where Set True For All the action (create, read, delete, find)
You're not passing the session token to the query to find it.
billingPackage = await query.get(billingPackageId, {sessionToken:sessionTokne});
If you are logged in as the current user (user = getCurrentParseUser()), then you don't need to pass the sessionToken to the destroy method. If you are not logged in as the currentUser, you will not be allowed to get the other users sessionToken.
Assuming that you are logged in as the current user or you are a user who can delete the object, I have corrected your code bellow. Hope to be used as a reference for others too.
try {
const billingPackage = await new Parse.Query(BillingPackage).get(billingPackageId);
if (billingPackage) {
try {
await billingPackage.destroy();
return {
status: true,
message: "The Billing Package Has Been Deleted"
}
} catch (parseError) {
return {
{
status: false,
message: parseError.message
}
}
}
}
} catch (parseError) {
console.log(parseError.message);
}
I'm using Direct Line 3.0 and the Microsoft Bot Framework and require the webpage to send some form fields to the bot as if the user sent them. For example when the user presses Submit, the fields email, phone etc are sent to the bot as if the user sent them like this: email, phone, etc.
This is because the bot redirects the user depending on what the values are. The bot is in C# and is hosted on Azure. The logic for submitting the information should be in JavaScript.
Bot is initiated like this:
<div id="chat" style="background-color:white;
width:250px;height:600px;"><div id="bot" />
<script src="https://cdn.botframework.com/botframework-
webchat/latest/botchat.js"></script></div></div>
and through a DirectLine script:
<script>
const botConnection = new BotChat.DirectLine({
secret: 'secret',
});
BotChat.App({
user: { id: 'You' },
bot: { id: 'myId' },
resize: 'detect',
botConnection: botConnection
}, document.getElementById("bot"));
</script>
All I need is to send one string as if the user sent it. I cannot do this with HTML manipulation it seems.
Thanks for anyone pointing me in the right direction!
Sending a message to the bot "like the user would do" is possible using the "Backchannel" functionnality of the webchat.
There is a good sample of use in the Readme file on Github webchat's page: https://github.com/Microsoft/BotFramework-WebChat#the-backchannel.
You have to use your botConnection previously created to send an activity like the following:
botConnection.postActivity({
from: { id: 'me' },
name: 'buttonClicked',
type: 'event',
value: ''
});
Then catch this on your bot code, but checking the Activity type which will be Event in this case.
You can have a look on how they throw this postActivity from a button click in the sample provided: samples here: https://github.com/Microsoft/BotFramework-WebChat/blob/master/samples/backchannel/index.html
Or in this other sample that I made (available on Github, both client web page and bot code): the bot's controller looks like the following:
[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
// Process each activity
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
}
// Webchat: getting an "event" activity for our js code
else if (activity.Type == ActivityTypes.Event && activity.ChannelId == "webchat")
{
var receivedEvent = activity.AsEventActivity();
if ("localeSelectionEvent".Equals(receivedEvent.Name, StringComparison.InvariantCultureIgnoreCase))
{
await EchoLocaleAsync(activity, activity.Locale);
}
}
// Sample for Skype: locale is provided in ContactRelationUpdate event
else if (activity.Type == ActivityTypes.ContactRelationUpdate && activity.ChannelId == "skype")
{
await EchoLocaleAsync(activity, activity.Entities[0].Properties["locale"].ToString());
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
private async Task EchoLocaleAsync(Activity activity, string inputLocale)
{
Activity reply = activity.CreateReply($"User locale is {inputLocale}, you should use this language for further treatment");
var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
await connector.Conversations.SendToConversationAsync(reply);
}
}