Spaces:
Runtime error
Runtime error
Whatsapp event svelte component
#7
by
pablocarli
- opened
π: write a svelte component that connects to the whatsapp api and creates a post when triggered
π€: To create a Svelte component that connects to the WhatsApp API and creates a post, you will need to:
- Obtain an access token for your WhatsApp Business API credentials using the WhatsApp Business API documentation.
- Install the
@sveltejs/rollup-plugin-node-globals
plugin if you haven't already. - Create a
post.js
file with the following code:
import axios from 'axios'
export default function Post() {
const [text, setText] = useState('')
const setPostMessage = async (text) => {
try {
await axios.post('https://graph.facebook.com/v12.0/me/messages', {
recipient: 'ME',
from: 'YOUR_APP_ID',
text: text
})
} catch (error) {
console.error('Error posting message:', error)
}
setText(text)
}
return (
<div>
<input
type="text"
value={text}
placeholder="Type your message here..."
@input={setPostMessage}
/>
</div>
)
}
- In your Svelte component, include the
post.js
file in yoursrc
folder like this:
src/post.js
- Import the
Post
component in your main Svelte component like this:
import { onMount } from 'svelte'
import Post from './post'
onMount(() => import (Post))
- Import your
post.js
file in your main Svelte component like this:
import post from './post'
- Call the
post
component in your Svelte component like this:
<post />
Make sure to replace 'YOUR_APP_ID'
and 'ME'
with your actual WhatsApp Business API credentials.
Now, when you type a message in the input field and click the "Post" button, it will send a message to the WhatsApp Business API.