How to delete user from channel - getstream-io

When trying to delete a user, an error message is displayed:
Error removing user from conversation: Error: StreamChat error code 4: UpdateChannel failed with error: "cannot add or remove members in a distinct channel, please create a new distinct channel with the desired members"
Below is a sample code to delete a user:
try {
const response = await conversation.removeMembers(
[user.id],
{ text: `${user.name} was removed from conversation`}
);
console.log('Response: ', response);
console.log(`${user.name} was removed from conversation`);
} catch (e) {
console.log(`Error removing user from conversation: ${e}`);
}
Conversation:
On deletion, the first request returns OK status with the conversation

We ran into this issue also. Had to change the way that were creating channels. The docs make this really hard to find but on this page it says You cannot add/remove members for channels created this way.
Meaning if you want to create a channel in which members can be added and removed you have to create it like shown here where you assign the channel a unique ID that you create (we are using a UUID). Once it's been created you can add your desired members to it... and then later add or remove them.

Related

Discord.js creating channel error - Invalid Form Body

I've been trying to create a ticket bot and create channels that have tickets within them. However, when I try and create them it returns an error
Code:
const channel = await interaction.guild.channels.create(`ticket-${interaction.user.username}`, {
parent: '929135588949512232',
topic: interaction.user.id,
type: 'GUILD_TEXT',
})
Error:
DiscordAPIError[50035]: Invalid Form Body
name[BASE_TYPE_REQUIRED]: This field is required
Any help would be appreaciated
If you look at the documentation, only one parameter is required for the channel create method, therefore the code should look like this:
const channel = await interaction.guild.channels.create({
name: `ticket-${message.interaction.username}`,
parent: "929135588949512232",
topic: interaction.user.id,
type: Discord.ChannelType.GuildText,
});
Refer to the docs here
https://discord.js.org/#/docs/discord.js/main/class/GuildChannelManager?scrollTo=create
The error is caused, because you passed in information, such as the type, in the second parameter, not the first.

Is it possible to get a detailed query when delete operation fails?

I am doing a delete operation with a filter of 2 fields:
const query = await Flow.deleteOne({
_id: flowId,
permissions: currentUser!.id,
});
Then I check the query object that returns from this operation to determine whether the operation was successful or not:
if (!query.deletedCount) {
throw new BadRequestError("Flow not found");
}
The problem is that I cant know if the operation failed because the flowId is wrong (first filter field) or the user don't have permissions (second filter field).
Is there an option to get a more detailed query result in mongoose?
As you can see from the official docs, deleteOne returns an object with three properties:
ok 1 if no errors
deletedCount number of docs deleted
n number of docs deleted
If you need to investigate the reasons for the failure you could query the database in case of error, something like:
if (!query.deletedCount) {
const flow = await Flow.findById(flowId);
// wrong `flowId`
if (!flow) throw new BadRequestError("Flow not found");
// otherwise, user don't have permission
throw new BadRequestError("Unauthorized");
}

Google Datastore can't update an entity

I'm having issues retrieving an entity from Google Datastore. Here's my code:
async function pushTaskIdToCurrentSession(taskId){
console.log(`Attempting to add ${taskId} to current Session: ${cloudDataStoreCurrentSession}`);
const transaction = datastore.transaction();
const taskKey = datastore.key(['Session', cloudDataStoreCurrentSession]);
try {
await transaction.run();
const [task] = await transaction.get(taskKey);
let sessionTasks = task.session_tasks;
sessionTasks.push(taskId);
task.session_tasks = sessionTasks;
transaction.save({
key: taskKey,
data: task,
});
transaction.commit();
console.log(`Task ${taskId} added to current Session successfully.`);
} catch (err) {
console.error('ERROR:', err);
transaction.rollback();
}
}
taskId is a string id of another entity that I want to store in an array of a property called session_tasks.
But it doesn't get that far. After this line:
const [task] = await transaction.get(taskKey);
The error is that task is undefined:
ERROR: TypeError: Cannot read property 'session_tasks' of undefined
at pushTaskIdToCurrentSession
Anything immediately obvious from this code?
UPDATE:
Using this instead:
const task = await transaction.get(taskKey).catch(console.error);
Gets me a task object, but it seems to be creating a new entity on the datastore:
I also get this error:
(node:19936) UnhandledPromiseRejectionWarning: Error: Unsupported field value, undefined, was provided.
at Object.encodeValue (/Users/.../node_modules/#google-cloud/datastore/build/src/entity.js:387:15)
This suggests the array is unsupported?
The issue here is that Datastore supports two kinds of IDs.
IDs that start with name= are custom IDs. And they are treated as strings
IDs that start with id= are numeric auto-generated IDs and are treated as integers
When you tried to updated the value in the Datastore, the cloudDataStoreCurrentSession was treated as a string. Since Datastore couldn't find an already created entity key with that custom name, it created it and added name= to specify that it is a custom name. So you have to pass cloudDataStoreCurrentSession as integer to save the data properly.
If I understand correctly, you are trying to load an Array List of Strings from Datastore, using a specific Entity Kind and Entity Key. Then you add one more Task and updated the value of the Datastore for the specific Entity Kind and Entity Key.
I have create the same case scenario as yours and done a little bit of coding myself. In this GitHub code you will find my example that does the following:
Goes to Datastore Entity Kind Session.
Retrieves all the data from Entity Key id=5639456635748352 (e.g.).
Get's the Array List from key: session_tasks.
Adds the new task that passed from the function's arguments.
Performs the transaction to Datastore and updates the values.
All steps are logged in the code and there are a lot of comments explaining exactly how the code works. Also there are two examples of currentSessionID. One for custom names and other one for automatically generated IDs. You can test the code to understand the usage of it and modify it according to your needs.

Unable to change the user password after cognito authentication

I created the user using adminCreateUser. On trying to authenticate using adminInitiateAuth, a challenge NEW_PASSWORD_REQUIRED is returned. How do I change the password?
I am trying to reset the user password for a user with status FORCE_CHANGE_PASSWORD, using the following snippet:
cognitoidentityserviceprovider.respondToAuthChallenge({
ChallengeName: 'NEW_PASSWORD_REQUIRED',
ClientId:'XXXXXXXXXXXXXXXXXXXX',
ChallengeResponses: {
NEW_PASSWORD: 'T.YpkKu487',
USERNAME: 'XXXXX'
},
Session: "cMcKC5ymFvZG2D10lJMRArpfmLZvnQE25P1XjwkHtl47g4kW-LAjOgB4CAjIgv1CurDmfRHpxzvYgYE61BBrp5-TNyVQcXXX"
}, (err, data) => {
if(err) console.log(err);
else console.log(data);
});
When I run the above code, I get the following error:
InvalidParameterException: Invalid attributes given, name is missing
I do not understand this. Why am I getting this error? Reference doc
Also, is there a way I could disable this challenge altogether?
Found A solution: When I created the user pool I added name and email as required attributes, creating it without requiring attribute name solved it.
Please add the 'name' attribute in your "userattributes" which you will pass for changing the password
.

Hoodie - Update a CouchDB document (Node.js)

I'm handling charges and customers' subscriptions with Stripe, and I want to use these handlings as a Hoodie plugin.
Payments and customer's registrations and subscriptions appear normally in Stripe Dashboard, but what I want to do is update my _users database in CouchDB, to make sure customer's information are saved somewhere.
What I want to do is updating the stripeCustomerId field in org.couchdb.user:user/bill document, from my _users database which creates when logging with Hoodie. And if it is possible, to create this field if it does not exist.
In hoodie-plugin's document, the update function seems pretty ambiguous to me.
// update a document in db
db.update(type, id, changed_attrs, callback)
I assume that type is the one which is mentioned in CouchDB's document, or the one we specify when we add a document with db.add(type, attrs, callback) for example.
id seems to be the doc id in couchdb. In my case it is org.couchdb.user:user/bill. But I'm not sure that it is this id I'm supposed to pass in my update function.
I assume that changed_attrs is a Javascript object with updated or new attributes in it, but here again I have my doubts.
So I tried this in my worker.js:
function handleCustomersCreate(originDb, task) {
var customer = {
card: task.card
};
if (task.plan) {
customer.plan = task.plan;
}
stripe.customers.create(customer, function(error, response) {
var db = hoodie.database(originDb);
var o = {
id: 'bill',
stripeCustomerId: 'updatedId'
};
hoodie.database('_users').update('user', 'bill', o, function(error) {
console.log('Error when updating');
addPaymentCallback(error, originDb, task);
});
db.add('customers.create', {
id: task.id,
stripeType: 'customers.create',
response: response,
}, function(error) {
addPaymentCallback(error, originDb, task);
});
});
}
And between other messages, I got this error log:
TypeError: Converting circular structure to JSON
And my file is not updated : stripeCustomerId field stays null.
I tried to JSON.stringify my o object, but It doesn't change a thing.
I hope than some of you is better informed than I am on this db.update function.
Finally, I decided to join the Hoodie official IRC channel, and they solved my problem quickly.
Actually user.docs need an extra API, and to update them you have to use hoodie.account instead of hoodie.database(name)
The full syntax is:
hoodie.account.update('user', user.id, changedAttrs, callback)
where user.id is actually the account name set in Hoodie sign-up form, and changedAttrs an actual JS object as I thought.
Kudos to gr2m for the fix; ;)

Resources