how to save entire conversation from bot into stoarge? - botframework

I have made a bot in v4 framework using c#. I want to save the entire conversation into a storage , in a readable format . Our requirement is to save the bot conversation in a readable format or plain text. In my case only user info is getting saved not the conversation between user and the bot.

You can use a middleware for that: TranscriptLoggerMiddleware
More info on middlewares
The middleware will handle saving transcript for you in a storage.

you can use below code
I have worked on nodejs but it should be similar to C#.
For each step call the logActivity
const { preserveService } = require('../../../Service/dbService');
await preserveService.logActivity(step.context, userData,Any param);
logActivity : async function (turnContext, userData,Any param){
try{
let userInfo = await userDataUtil.getUserInfo(turnContext,userData);
colNameAndValueArray = [
{
[PROPERTY_NAME.COLUMN_NAME] : 'response_from',
[PROPERTY_NAME.VALUE] : responsefrom,
[PROPERTY_NAME.DATATYPE] : DATATYPE.STRING
},
{
[PROPERTY_NAME.COLUMN_NAME] : 'user_session_id',
[PROPERTY_NAME.VALUE] : userInfo.userId,
[PROPERTY_NAME.DATATYPE] : DATATYPE.STRING
},
{
//conversation_id
[PROPERTY_NAME.COLUMN_NAME] : 'conversation_id',
[PROPERTY_NAME.VALUE] : turnContext._activity.conversation.id,
[PROPERTY_NAME.DATATYPE] : DATATYPE.STRING
},
{
[PROPERTY_NAME.COLUMN_NAME] : 'is_answered',
[PROPERTY_NAME.VALUE] : isAnswered,
[PROPERTY_NAME.DATATYPE] : DATATYPE.BOOLEAN
}
]
await this.insert(CONFIG.DB.AUDIT_TABLE, colNameAndValueArray);
}catch(err){
console.log(`------------------------`);
console.log(`Error occurred while inserting audit logs`);
console.log(err);
console.log(`------------------------`);
}}
insert : async function(tableName, colNameAndValueArray, returnColumnName){
let query = null;
try{
if(util.isNotEmptyString(tableName) && util.isNotEmptyArray(colNameAndValueArray)){
let columnNames = dbUtil.getColNames(colNameAndValueArray);
let columnValues = dbUtil.getColValues(colNameAndValueArray);
if(columnNames == null || columnValues == null){
throw new Error('Invalid column name or value. Kindly check the value you have passed');
}
query = `INSERT INTO ${tableName} (${columnNames}) VALUES (${columnValues}) ${util.isNotEmptyString(returnColumnName)? ` RETURNING ${returnColumnName}`: ''}`;
console.log(`------------------------`);
console.log(`Query : ${query}`);
console.log(`------------------------`);
return this.executeQuery(query);
}else{
return Promise.reject(REQUIRED_PARAMETER_MISSING);
}
}catch(err){
console.log(`------------------------`);
console.log(`Error occurred while executing insert query : ${ query != null ? query : '' }`);
console.log(err);
console.log(`------------------------`);
return Promise.reject(err);
}}
Hope this helps
Sanjeev Guatam

Related

Strapi, use find to check if an object type field has a match in one of the properties

Let's say I have a field called user with a data that looks something like this
{
"id": "abc123",
"name": "John Smith"
}
I want to make a route where I can find where user.id equals, say, abc123 and should return the blogs that has a user with the id above
I've tried doing
async findByUser(ctx) {
let blogs = await strapi.services.blogs.find({
user: {id:ctx.params.id},
return blogs;
},
but that doesn't seem to work as it returns an empty array and isn't searching specifically in the id property. How do I do this using strapi?
edit: User is not an relation, it is an individual JSON field.
Okay, for querying a JSON object property, you will need to write a custom query. Look at the example below.
Implementation for PostGreSQL
async findByUser(ctx) {
const response = await strapi
.query('blogs')
.model.query((qb) => {
qb.where('user', '#>', `{"id": "${ctx.params.id}" }`);
// qb.where('user', '#>', `{"name": "${ctx.params.name}" }`);
})
.fetch();
return response.toJSON();
},
Implementation for SQLite
async findByUser(ctx) {
const response = await strapi
.query('blogs')
.model.query((qb) => {
qb.where('user', 'LIKE', `%"id":"${ctx.params.id}"%`);
})
.fetch();
return response.toJSON();
},
P.S: Just use fetch instead of fetchAll for consistency.
Hi there thanks to Salvino's help I think i am able to find a solution
async findByUser(ctx) {
const response = await strapi
.query('blogs')
.model.query((qb) => {
qb.where('user', 'LIKE', `%"id":"${ctx.params.id}"%`);
})
.fetchAll();
return response.toJSON();
},

Spring - How to correctly show relationship data in view (table) using REST api

I have a User (id, username) entity which has many-to-many relationship with Roles (id, name) entity. I am trying to show the User data in a ajax Datatable. Now, if a User has six roles, it shows six [object Object] for all six roles. I dont know how to correctly show the role name instead of object Object.
This is what I have:
.DataTable(
{
"pagingType" : "full_numbers",
"sAjaxSource" : "/api/AppUser/all",
"sAjaxDataProp" : "",
"aoColumns" : [
{
"data" : "id"
},
{
"data" : "username"
},
{
"data" : "userenabled"
},
{
"data" : "useremail"
},
{
"data" : "userfirstname"
},
{
"data" : "userlastname"
},
{
"data" : "useraddress"
},
{
"data" : "roles"
}
This is how it looks like in Data Table:
Here is my REST Controller piece:
#RestController
#RequestMapping("/api/AppUser")
public class AppUserRestAPIs {
#GetMapping(value = "/all", produces = "application/json")
public List<AppUser> getResource() {
return appUserJPARepository.findAll();
}
}
I know it must be trivial but feeling lost and could not find a single example on how to represent relationship data in view (html) using REST api. Searched almost everywhere. What I am missing here? Will appreciate any pointers here.
Answering my own question:
Found it ! Here - https://editor.datatables.net/examples/advanced/joinArray.html
So instead of:
{
"data" : "roles"
}
I have to use:
{
"data" : "roles",
render : "[, ].name"
}
All worked perfectly but now I am clueless what if I don't use Datatable. Not sure if I have to put another question for it.
Use function to flat roles list:
Instead of
{
"data" : "roles"
}
Try this :
{
"data": null,
"render": function(data, type, row, meta) {
var flatrole = '';
//loop through all the roles to build output string
for (var role in data.roles) {
flatrole = flatrole + role.name + " ";
}
return flatrole;
}
}

spring jpa won't update new data

I would like to update new data from request.
Request JSON data looks like this.
[{"media_id : 1, "path" : "some path", ...}, {"media_id : 2, "path" : "some path", ...}]
These primary keys already exist in database
So It will update those rows and It should be updated
But update sql on debug log only update old data
I checked out media object that It contains new data from request
But jpa still try update with old data
What is my mistake?
private List<Media> upsertMedia(SquarePostDetailResource postToUpsert) {
List<Media> media = postToUpsert.getContent().getMedia();
media.forEach((item) -> {
item.setCreatedAt(item.getId() == null ? new Date() : item.getCreatedAt());
item.setModifiedAt(new Date());
item.setMember(Member.builder().id(postToUpsert.getMemberId()).build());
item.setSquare(Square.builder().id(postToUpsert.getSquareId()).build());
item.setSquarePost(SquarePost.builder().id(postToUpsert.getPostId()).build());
});
return (List<Media>) mediaRepo.save(media);
}
If you mean that updates inside foreach do not update the database, you can try the following.
private List<Media> upsertMedia(SquarePostDetailResource postToUpsert) {
List<Media> media = postToUpsert.getContent().getMedia();
List<Media> updatedMedia = new ArrayList<>();
media.forEach((item) -> {
item.setCreatedAt(item.getId() == null ? new Date() : item.getCreatedAt());
item.setModifiedAt(new Date());
item.setMember(Member.builder().id(postToUpsert.getMemberId()).build());
item.setSquare(Square.builder().id(postToUpsert.getSquareId()).build());
item.setSquarePost(SquarePost.builder().id(postToUpsert.getPostId()).build());
updatedMedia.add(item);
});
return (List<Media>) mediaRepo.save(updatedMedia);
}

Invalid Resource Id when batch inserting

I am doing a batch insert into the Google Calendar using the .NET API. I have the following code.
var request = new BatchRequest(calendarService);
request.Queue<Event>(
calendarService.Events.Insert(
new Event
{
Id = String.Format("yot-{0}", item.AppointmentId),
Summary = item.Title,
Description = item.Description,
Start = new EventDateTime() { DateTime = item.Date },
End = new EventDateTime() { DateTime = item.Date.AddHours(item.Length) }
}, calendar.Id),
(content, error, i, message) =>
{
//Log error
});
request.ExecuteAsync();
When I execute and try and insert I get the error "Invalid resource id". What does this error mean?
You have to follow the guidelines defined here : https://developers.google.com/google-apps/calendar/v3/reference/events/insert
Basically, the id has to be between 5 and 1024 characters long and consist solely from characters in this alphabet : 0123456789abcdefghijklmnopqrstuv.
Try with a simple Guid.NewGuid() or use a Base32 Encoder if you don't want random IDs

dataSource.data() doesn't return the datas

I'm currently testing kendoUI and developping a little webapp.
For some reason I need to pass my dataSource.datas from a view to another. In order to do this I use sessionStorage and when I try to put my dataSource.data() in sessionStorage, the return is empty.
See here when I put a log to test if my dataSource.data() is correctly inserted/returned
However, when I put a log to test ma dataSource I can clearly see that _data is not empty as it is showed in the follow picture :
Did someone know the origin of my problem ?
EDIT
here is the code that shows how I add my dataSource to sessionStorage :
var qui = (e.view.params.qui) ? e.view.params.qui : "";
var quoi = (e.view.params.quoi) ? e.view.params.quoi : "";
dataSourceFournisseurs = new kendo.data.DataSource({
transport : {
read : {
url:"annuaire.json",
dataType:"json"
}
},
schema : {
data : "data",
model : {
DISTANCE: function() {
var lat = this.get("LATITUDE");
var lng = this.get("LONGITUDE");
var distance = APP.distanceBetweenCoords(lat, lng);
return "à " + distance + "km";
}
}
},
sort : {
field : "LIBELLE",
dir : "asc"
},
filter: [
{ field: "LIBELLE", operator: "contains", value: qui },
{ field: "NAFLIBELLE", operator: "contains", value: quoi }
]
});
console.log(dataSourceFournisseurs);
session.setValueObject("liste", dataSourceFournisseurs.data());
And here is how I retrieve it :
var datas = session.getValueObject("liste");
console.log(datas);
PS :
setValueObject and getValueObject are two methods I wrote in order to Stringify the datas I set and Parse the retrieved datas (there are fully functionnal I use them for over a year)
the two console.log are those that represent the picture above (picture 1 with second log and picture 2 with first log)
EDIT END
Try using dataSourceFournisseurs.view(). This should give you the all of the data. Using data is meant for initial configuration, and is not meant to be used as a method for retrieving data.
Bonne chance!

Resources