Skip to content

Instantly share code, notes, and snippets.

@andersonba
Created July 1, 2019 23:48
Show Gist options
  • Save andersonba/2cb079cd5a17432f0ce6fd9252e5d3a1 to your computer and use it in GitHub Desktop.
Save andersonba/2cb079cd5a17432f0ce6fd9252e5d3a1 to your computer and use it in GitHub Desktop.
YveBot + Gifted Chat + React Native
import YveBot from 'yve-bot/core'
import { GiftedChat } from 'react-native-gifted-chat'
class ChatBot extends Component {
constructor(rules) {
this.bot = new YveBot(rules)
this.bot
.on('typing', this.handleTyping)
.on('typed', this.handleTyped)
.on('talk', this.handleTalk)
}
componentDidMount() {
this.bot.start()
}
componentWillUnmount() {
this.bot.end()
}
onSend(messages) {
this.addMessages(
messages.map(msg => {
this.bot.hear(msg.text)
return this.createMessage({
from: 'USER',
...msg
})
})
)
}
createMessage({ from, text, rule }) {
return {
_id: Date.now(),
createdAt: Date.now(),
user: { _id: from },
text,
rule,
}
};
addMessages(messages) {
this.setState(prevState => ({
messages: GiftedChat.append(prevState.messages, messages),
}))
}
handleTyping() {
this.setState({ typing: true })
}
handleTyped() {
this.setState({ typing: false })
}
handleTalk(message, rule) {
this.addMessages([
this.createMessage({
from: 'BOT',
text: message,
rule,
}),
]);
};
render() {
return (
<GiftedChat
messages={this.state.messages}
onSend={messages => this.onSend(messages)}
loadEarlier={this.state.loading}
user={{ _id: 'USER' }}
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment