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:

  1. Obtain an access token for your WhatsApp Business API credentials using the WhatsApp Business API documentation.
  2. Install the @sveltejs/rollup-plugin-node-globals plugin if you haven't already.
  3. 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>
    )
}
  1. In your Svelte component, include the post.js file in your src folder like this:
src/post.js
  1. Import the Post component in your main Svelte component like this:
import { onMount } from 'svelte'
import Post from './post'

onMount(() => import (Post))
  1. Import your post.js file in your main Svelte component like this:
import post from './post'
  1. 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.

Sign up or log in to comment