Chat ChatEngine ChatEngine Plugins JavaScript ReactJS Tech Tutorials and Demos

How to Use Open Graph to Unfurl URLs into Rich Objects in Chat Apps

Open Graph Comparison

Chat apps have transcended easy 1:1 and group messaging, and chat builders are all the time on the lookout for methods to take a dialog to the subsequent degree, making it extra immersive and interesting. Interactive emojis, language translation, and even integrating an AI-enabled chatbot are just some options driving the next-generation of chat.

At this level, customers anticipate that a few of these options must be a local a part of the appliance. And a type of options is wealthy playing cards/wealthy objects, the unfurling of straightforward URLs into interactive messages. It’s a function you don’t know you’re keen on till it’s not there.

On this weblog publish, we’ll stroll you thru integrating wealthy objects in a ChatEngine app utilizing our Open Graph plugin.

Open Graph Comparison

Creating the Preliminary React Undertaking

Let’s begin off by creating our React venture utilizing the create-react-app in our terminal/command-line.

npx create-react-app open-graph-project
cd open-graph-project
npm begin

The above strains of code create our venture, then change our listing into the undertaking that we simply created. Then the subsequent command will run your undertaking on http://localhost:3000.

Creating the Frontend with Materials Design

That is an elective step and you may create the frontend nevertheless you want, however for now, we’ll create a easy chat element that permits everybody to chat and exhibits the chat feed. For those who really feel such as you’ve already acquired this nailed down, I’ve posted the bottom code on my GitHub so you possibly can pull from the “base” department and transfer on to the subsequent step.

Let’s start by deleting the App.js file. We don’t actually need it and we’ll give you the option to do all the things in our index.js for this instance.

We’ll create a card element which can home our chat messages and have an enter field which permits the consumer to ship messages. Utilizing the material-UI library for React, our index.js file will one thing like this:

import React, Element from ‘react’;
import ReactDOM from ‘react-dom’;
import ‘./index.css’;
import withStyles from ‘@material-ui/core/types’;
import Card from ‘@material-ui/core/Card’;
import CardActions from ‘@material-ui/core/CardActions’;
import CardContent from ‘@material-ui/core/CardContent’;
import Listing from ‘@material-ui/core/Listing’;
import ListItem from ‘@material-ui/core/ListItem’;
import Button from ‘@material-ui/core/Button’;
import Typography from ‘@material-ui/core/Typography’;
import Enter from ‘@material-ui/core/Enter’;

const types =
card:
maxWidth: 345
,
openCard:
maxWidth: 200
,
openMedia:
peak: 80,
,
media:
objectFit: ‘cowl’,
,
container:
show: ‘flex’,
flexWrap: ‘wrap’,
,
;

class App extends Element

constructor(props)
tremendous(props);
this.state =
messages: [],
chatInput: ”
;

sendChat = () =>
// Logic for sending chat

setChatInput = (occasion) =>
this.setState( chatInput: occasion.goal.worth )

componentDidMount()

handleKeyPress = (e) =>
if (e.key === ‘Enter’)
this.sendChat();

render()
const courses = this.props;
return(
<Card className=courses.card >
<CardContent>
<Typography gutterBottom variant=”headline” element=”h2″>
Messages
</Typography>
<div className=courses.root>
<Listing element=”nav”>
<ListItem>
<Typography element=”div”>
messages will go right here
</Typography>
</ListItem>
</Record>
</div>
</CardContent>
<CardActions>
<Enter
placeholder=”Enter a message”
worth=this.state.chatInput
className=courses.enter
onKeyDown=this.handleKeyPress
onChange=this.setChatInput
inputProps=
‘aria-label’: ‘Description’,

/>
</CardActions>
</Card>
);

const ChatComponent = withStyles(types)(App);

Earlier than we will get the bottom challenge operating, we’ll want to set up material-ui:

npm set up @material-ui/core

Getting Your API Key from OpenGraph.io

This ChatEngine plugin makes use of OpenGraph.io, a service constructed on the Open Graph protocol. Merely signup for the service, and get your keys out of your dashboard.

Configuring ChatEngine

Moreover, you’ll want to configure ChatEngine and get your pub/sub keys. You are able to do this immediately in the shape under.

Your browser doesn’t help iframes.

As soon as your keys are generated, you’ll be able to start by initializing the shopper. Set up the associated packages to begin creating.

npm i chat-engine chat-engine-open-graph

Subsequent, edit the index.js file to combine ChatEngine.

import ChatEngineCore from ‘chat-engine’;
import opengraph from ‘chat-engine-open-graph’;

const now = new Date().getTime();
const username = [‘user’, now].be a part of(‘-‘);

const ChatClient = ChatEngineCore.create(
publishKey: ‘pub-c-3f89be1a-7cca-4307-8884-80b5b4855b23’,
subscribeKey: ‘sub-c-83c785b0-b219-11e8-acd6-a622109c830d’
,
globalChannel: ‘chatting’
);

ChatClient.join(username,
signedOnTime: now
, ‘auth-key’);

Then regulate your App element in index.js your  file to ship and obtain messages.

class App extends Element

constructor(props)
tremendous(props);
this.chat = new ChatClient.Chat(`openGraph`);
this.chat.plugin(opengraph(
api: (url) => `https://opengraph.io/api/1.1/site/$encodeURI(url)?app_id=$apiKey`,
));

this.state =
messages: [],
chatInput: ”
;

// … Extra code

Within the constructor, we’ll create a brand new chat with the identify “openGraph” then add the Open Graph plugin which we put in and imported earlier. In right here we’ll outline the endpoint which may have our API key which we grabbed earlier and the URL of the web site.

class App extends Element
// … Code as proven above
sendChat = () =>
if (this.state.chatInput)
this.chat.emit(‘message’,
textual content: this.state.chatInput,
uuid: username
);
this.setState( chatInput: ” )

setChatInput = (occasion) =>
this.setState( chatInput: occasion.goal.worth )

componentDidMount()
this.chat.on(‘message’, (payload) =>
const knowledge = payload;
console.log(knowledge);

let messages = this.state.messages;
if(knowledge.img != null)
messages.push(
<div key=this.state.messages.size fashion=border: “1px solid grey”> knowledge.uuid :
<img src=knowledge.img alt=knowledge.title/>
<h3> knowledge.title </h3>
<a href= knowledge.url > hyperlink </a>
<p> knowledge.desc </p>
</div>
);
else
messages.push(
<Message key= this.state.messages.size uuid= payload.knowledge.uuid textual content= payload.knowledge.textual content />
);

this.setState(
messages: messages
);

);

handleKeyPress = (e) =>
if (e.key === ‘Enter’)
this.sendChat();

The sendChat perform was empty earlier however now it can emit a message with the textual content we enter in the enter and in addition ship the username, which we created earlier, with the date.

Within the componentDidMount perform, we’ll pay attention for brand spanking new messages and as soon as we get the brand new message we’ll verify if that message has a picture property. If it does then we’ll render it as a wealthy message that has the properties from Open Graph. In any other case, present the message as regular.

class Message extends Element

render ()
return (
<div > this.props.uuid : this.props.textual content
</div>
);

;

class App extends Element
// … Code from element as discuessed above
render()
const courses = this.props;
return(
<Card className=courses.card >
<CardContent>
<Typography gutterBottom variant=”headline” element=”h2″>
Messages
</Typography>
<div className=courses.root>
<Listing element=”nav”>
<ListItem>
<Typography element=”div”>
this.state.messages
</Typography>
</ListItem>
</Record>
</div>
</CardContent>
<CardActions>
<Enter
placeholder=”Enter a message”
worth=this.state.chatInput
className=courses.enter
onKeyDown=this.handleKeyPress
onChange=this.setChatInput
inputProps=
‘aria-label’: ‘Description’,

/>
<Button measurement=”small” shade=”primary”>
Github
</Button>
<Button measurement=”small” colour=”primary”>
Article
</Button>
</CardActions>
</Card>
);

const ChatComponent = withStyles(types)(App);

ChatClient.on(‘$.prepared’, () =>
ReactDOM.render(<ChatComponent />, doc.getElementById(‘root’));
);

Within the render perform, we’ll have the logic to populate new messages. We additionally want to be sure that earlier than we render the element we verify for the $.prepared occasion.

Working example open graph

Nice! now we now have our ChatEngine app operating with Open Graph!

If for some cause the code above doesn’t be just right for you, obtain the grasp department and get it operating with the next instructions:

mkdir open-graph-demo
cd open-graph-demo
git init
git pull https://github.com/nxsyed/Chat-Engine-OpenGraph.git grasp
npm i
npm begin

Wrapping Up

We hope you loved our tutorial on unfurling and enriching URLs in the chat feed. For all our plugins, and a ton of different ChatEngine tutorials and demos, take a look at our docs and tutorials.

!perform (f, b, e, v, n, t, s) if (f.fbq)return;n = f.fbq = perform () n.callMethod ?
n.callMethod.apply(n, arguments) : n.queue.push(arguments)
;if (!f._fbq)f._fbq = n;n.push = n;n.loaded = !zero;n.model = ‘2.zero’;n.queue = [];t = b.createElement(e);t.async = !zero;t.src = v;s = b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t, s)
(window,doc, ‘script’, ‘https://connect.facebook.net/en_US/fbevents.js’);
fbq(‘init’, ‘1736515043250868’); // Insert your pixel ID right here.
fbq(‘monitor’, ‘PageView’);