how to initiate one-to-one chat with getstream.io? - javascript

I'm trying to create slack like application using getstream.io chat SDK. In the documentation we can find out, how to initiate a channel to start group chat. But there is no any information about one-to-one chat. Does anyone knows how to initiate a one-to-one chat?
code sample to create new channel for group chat
const client = new StreamChat('t5v25xyujjjq');
await client.setUser(
{
id: 'jlahey',
name: 'Jim Lahey',
image: 'https://i.imgur.com/fR9Jz14.png',
},
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiamxhaGV5In0.sFe9WvuHIKgQmgtEWFh708Nu_a2wy8Zj3Q8BJz7fDRY',
);
const channel = chatClient.channel('messaging', 'groupname', {
name: 'Founder Chat',
image: 'profile image url',
members: ['user1', 'user2'],
});
const response = await channel.sendMessage({
text: 'Josh I told them I was pesca-pescatarian'
});

If you want to have the guarantee that only one channel exists between N users you can instantiate the Channel without ID and the list of its members.
When you do that, the API will ensure that only one channel with the list of members exists (order of the members does not matter).
const distinctChannel = conversation.channel("messaging","", {
members: [user1.id, user2.id],
});
await distinctChannel.create();
Since the channel data is going to be the same for both members; I suggest to not store the image field the way you do in your code example. It is easier to use the "other" member profile image as the channel image when you render the conversation.
For example:
let channelImage = "https://path/to/fallback/image";
otherMembers = channel.members.filter(member => member.user.id != currentUser.id);
if otherMembers.length > 0 {
channelImage = otherMembers[0].image;
}

Check the docs securely, it's in there:
check under channel initialization
const conversation = authClient.channel('messaging', 'thierry-tommaso-1', {
name: 'Founder Chat',
image: 'bit.ly/2O35mws',
members: ['thierry', 'tommaso'],
});

Related

How to get a notification when a tweet is deleted via the twitter API?

How can I get a notice when a tweet was deleted using the twitter API?
In version 1.0 of the API, I was able to get the notification in a stream using this:
var Twit = require("twit");
var T = new Twit({
consumer_key: "555",
consumer_secret: "555",
access_token: "555",
access_token_secret: "555",
timeout_ms: 60 * 1000,
strictSSL: true
});
var userIds = [ "123", "456" ];
var stream = T.stream("statuses/filter", { follow: userIds.join(",") });
stream.on("delete", (x) => console.log("Tweet was deleted", x));
However, without notice. The deleted events stopped being streamed.
So now I'm trying to do it with v2 of the twitter API like this:
const BEARER_TOKEN = "555";
const { ETwitterStreamEvent, TweetStream, TwitterApi, ETwitterApiError } = require("twitter-api-v2");
const appClient = new TwitterApi(BEARER_TOKEN);
const stream = await appClient.v2.getStream("tweets/compliance/stream", { partition: 1 });
stream.on(ETwitterStreamEvent.Data, (x) => console.log("Got data", x));
The call to getStream() throws the following error:
data: {
client_id: '555',
detail: 'When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.',
registration_url: 'https://developer.twitter.com/en/docs/projects/overview',
title: 'Client Forbidden',
required_enrollment: 'Standard Basic',
reason: 'client-not-enrolled',
type: 'https://api.twitter.com/2/problems/client-forbidden'
}
I also tried using an app only login such as this:
const TWITTER_CLIENT = new TwitterApi({
appKey: CONSUMER_KEY,
appSecret: CONSUMER_SECRET,
accessToken: ACCESS_TOKEN,
accessSecret: ACCESS_TOKEN_SECRET
});
var appClient = await TWITTER_CLIENT.appLogin();
That throws the same error as above.
Using 2.0's getStream() with /tweets/search/stream/ does return an event a tweet is created, but not when it is deleted. It also has a limited query with only 5 rules per stream and rules are only 512 characters in length. Which won't cover all the screen names I currently track in the 1.0 version of the API.
I also tried using compliance jobs, but it takes a very long time and ends up returning an empty array anyways instead of any info about the tweet ids I provided:
var job = await appClient.v2.sendComplianceJob({
type: "tweets",
ids:[
// the ids are not from my dev account or from
// a account that authed my app
"555", // id of tweet I deleted
"123", // id of tweet I deleted
"456", // id of tweet I didn't delete
]
});
// takes 5-10 minutes to say its complete
var jobResults = await appClient.v2.complianceJobResult(job.data);
// echos: jobResults: []
console.log("jobResults", jobResults);
How can I get a stream event of when a tweet is deleted (of any specific user I choose) using the v2 API of twitter?
Unfortunately, Twitter have deprecated User deletes a Tweet event type.
The Only other option is to save all tweets for the accounts you are tracking on your database then compare them to current tweets using lookup API.
but you can only check 100 tweets on every request, so you will need to make a job that loops to check every 100 tweet, then to inform you if a tweet was deleted.
ids: A comma separated list of Tweet IDs. Up to 100 are allowed in a single request. Make sure to not include a space between commas and fields.
source: https://developer.twitter.com/en/docs/twitter-api/tweets/lookup/api-reference/get-tweets#tab0

Give roles permission to interact with newly created channel Discord.JS

I'm using Node.JS to create a discord bot in which a new role and channel are created with the same command. For the sake of simplicity, both the name of the role and the name of the channel are the first argument of the command:
let chanName = args[0];
let roleName = args[0];
Following the name of the role/channel is a list of mentions - these are the users that receive the new role. The role is created just fine, the channel is created just fine, and the members are added to the role just fine, but I'm having trouble setting up permissions where only users with the new role OR the 'administrator' role are able to see the channel.
The channel is created like so:
message.guild.channels.create(chanName, {
type: "text"
})
.then((channel) => {
//Each new channel is created under the same category
const categoryID = '18-digit-category-id';
channel.setParent(categoryID);
})
.catch(console.error);
It appears as though the channel is not added to the guild cache
let chan = message.guild.channels.cache.find(channel => channel.name === chanName);
because this code returns 'undefined' to the console.
Is there any way I can allow the mentioned users to interact (view, send messages, add reactions...) with this new channel?
Permissions are very simple to set up upon creating a channel!
Thanks to the multiple options GuildChannelManager#create() gives us, we're very simply able to add permission overwrites to our desired roles and members.
We could very simply take your code and add a permissionOverwrites section to set the channel's permissions, as follows:
message.guild.channels.create(chanName, {
type: "text",
permissionOverwrites: [
// keep in mind permissionOverwrites work off id's!
{
id: role.id, // "role" obviously resembles the role object you've just created
allow: ['VIEW_CHANNEL']
},
{
id: administratorRole.id, // "administratorRole" obviously resembles your Administrator Role object
allow: ['VIEW_CHANNEL']
},
{
id: message.guild.id,
deny: ['VIEW_CHANNEL']
}
]
})
.then((channel) => {
//Each new channel is created under the same category
const categoryID = '18-digit-category-id';
channel.setParent(categoryID);
})

Disord js bot user-info issue

I'm trying to create a bot, and one of its commands is user-info
for eg. !user-info #<username>
and i want it to display username, id and the avatar
like:
username:<username>
Id:<User Id>
Avatar:<the avatar >
Below is the code i used:
else if (message.content.startsWith(`${prefix}user-info`)) {
var member = message.mentions.users.first();
message.channel.send(`Username: ${member.username}\n ID:${member.id}\n Avatar:${member.displayAvatarURL()}` );
}
However it doesn't work, when i remove the avatar part the output comes out as :
Username:undefined
Id:<the id>
When I add the avatar part I just get a huge error on the command module when I use the bot command. What's the right way and what did I get wrong?
I'd suggest you use an Embed for this, as those can display images in a better way, the code for your request would be:
var user = message.mentions.users.first();
message.channel.send({
embed: {
title: `Profile of ${user.tag}`,
thumbnail: {
url: user.displayAvatarURL(),
},
fields: [
{
title: "ID:",
value: user.id
}
]
}
});
You can find more on this here

How to make a list of a "#role"

I want to make a command where, if someone types "?role #testrole", the bot will send an embed with a list of users who have the aforementioned role.
An example response would be:
List of #testrole
- #Adam
- #Drago
- #Santiago
Here's my code:
if (message.content.toLowerCase() == 'teamone') {
let team1 = message.guild.member(
message.member.roles.cache.has('750579457953234994')
);
message.channel.send({
embed: {
title: 'Team 1 composition!',
description: `${team1}`,
},
});
}
I tried but it does not work, it only sends null. Any ideas?
Try this:
if (message.content.toLowerCase() == 'teamone') {
let team1 = message.guild.roles.cache
.get('750579457953234994') // get the role in question
.members.map((member) => `<#${member.id}>`) // map the results in mention format (<#${user.id}>)
.join('\n'); // join by a line break
message.channel.send({
embed: {
title: 'Team 1 composition!',
description: `${team1}`,
},
});
}
Every Role has a members property, which is a collection of all (cached) members that have the given role.
You can then use the Collection.prototype.map function to format each member to a mention. Here's an example from my server:
(I used the mod role as an example, this is my mod team)

Bot doesn't add message member to the channel - Discord.JS

So, I'm currently working on a "temporary channels" module for my bot. When a user with a certain rank does !newvc, the bot creates a private voice channel that they can use, add people, and when everyone leaves, it gets automatically deleted after some time.
Everything was working fine, but I've noticed a bug that I can't find the reason behind why it happens. Basically, when you first use the command all works fine, the channel is made, you get added and it's moved to the category. But if you use it again, let's say a minute later you don't get added. The channel is made, set as private but you message.member doesn't get added. Then it again does and doesn't, You get the point right?
I honestly can't find a reason why it does it and the only thing I can think of is something to do with Discord's API.
Here's my code
let member = message.member
user = member.user
message.delete()
message.guild.createChannel(`⭐${member.user.username}'s Room`, 'voice', [{
id: message.guild.id,
deny: ['CONNECT', 'SPEAK', 'PRIORITY_SPEAKER']
}]).then(channel => {
channel.overwritePermissions(member, {
CONNECT: true,
USE_VAD: true,
PRIORITY_SPEAKER: true
})
channel.setParent('567718414454358026')
})
let privatevc = new Discord.RichEmbed()
.setDescription(':white_check_mark: Successfully created a voice channel!')
.setColor(config.green)
message.channel.send({ embed: privatevc }).then(msg => msg.delete(10000))
FYI: My Discord.JS version is 11.4 (didn't had time to update it, due to work)
Firstly, the first 2 lines should be changed to:
let member = message.member,
user = message.author;
// or
const { member, author: user } = message;
as whilst this isn't a problem, in strict mode it will cause an error as you technically do not have a variable keyword in front of user = member.user. You should try and use const if you aren't going to be changing the value of the variables. Note that message.author is the same as message.member.user.
Secondly, using the permissionOverwrites arg in Guild#createChannel is deprecated (see https://discord.js.org/#/docs/main/v11/class/Guild?scrollTo=createChannel). I am aware that Discord.JS has abolished many things despite them saying "deprecated". Try using the typeOrOptions argument to create the channel with the appropriate overrides instead.
Here's my suggested code:
(async () => {
message.delete();
message.guild.createChannel(`⭐ ${message.author.username}'s Room`, {
type: 'voice',
parent: '567718414454358026',
permissionOverwrites: [{
id: message.guild.id, // #everyone has the ID of the guild
deny: ['VIEW_CHANNEL', 'CONNECT'],
}, {
id: message.author.id, // attach the permission overrides for the user directly here
allow: ['VIEW_CHANNEL', 'CONNECT', 'USE_VAD', 'PRIORITY_SPEAKER']
}]
});
const embed = new Discord.RichEmbed()
.setDescription(':white_check_mark: Successfully created a voice channel!')
.setColor(config.green);
const sentMessage = await message.channel.send(embed);
sentMessage.delete(10 * 1000);
})();
I found the issue. Basically, because the user was added after the channel is created, Discord API was losing it (or something, these are only my guess atm).
After changing it to this:
message.guild.createChannel(`⭐${member.user.username}'s Room`, 'voice', [{
id: message.guild.id,
deny: ['CONNECT', 'SPEAK', 'PRIORITY_SPEAKER']
}, {
id: message.author.id,
allow: ['CONNECT', 'SPEAK', 'PRIORITY_SPEAKER']
}])
Everything works again. Thank you PiggyPlex.

Categories