Facebook Chatbot dengan Kotlin dan Spark framework, dengan ngrok
* Kotlin
* Spark Framework
* Ngrok
* Facebook page
* Graddle
* JDK
Install
-
Instal Download and Instal JDK URL: https://www.oracle.com/technetwork/java/javase/downloads/index.html
-
Install gradle here : https://gradle.org/install/
-
Install ngrok : https://ngrok.com/download
-
make directory whatever u want, in here fchatbot-kotlin then go inside and make directory again
- src/main/kotlin/com/baihaqilp/fchatbot (this for package name so in the program will be "package com.baihaqilp.fchatbot") -src/main/kotlin/resources
-
make build.graddle inside fchatbot-kotlin dir
-
go inside directory fchatbot-kotlin then install gradlewrap
- gradle wrapper --gradle-version = 5.5.1
-
make build.graddle like this.
/*
- This build file was generated by the Gradle 'init' task.
- This generated file contains a sample Java Library project to get you started.
- For more details take a look at the Java Libraries chapter in the Gradle
- user guide available at https://docs.gradle.org/4.0/userguide/java_library_plugin.html */
// Apply the java-library plugin to add support for Java Library apply plugin: 'java-library' apply plugin: 'kotlin' apply plugin: 'application'
group 'com.baiahqilp.fchatbot'
archivesBaseName = "fchatbot" version = '1.0.0' mainClassName = "com.baihaqilp.fchatbot.Main"
// In this section you declare where to find the dependencies of your project repositories { // Use jcenter for resolving your dependencies. // You can declare any Maven/Ivy/file repository here. jcenter() mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots" } }
buildscript { ext.kotlin_version = '1.3.10' repositories { google() jcenter() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' classpath "com.github.dcendents:android-maven-gradle-plugin:2.0" classpath 'com.google.gms:google-services:4.0.1' } }
dependencies { compile 'com.sparkjava:spark-kotlin:1.0.0-alpha' compile 'com.sparkjava:spark-core:2.6.0' compile 'org.slf4j:slf4j-api:1.7.13' compile 'org.slf4j:slf4j-simple:1.7.13' compile 'com.clivern:racter:1.0.2' }
//create a single Jar with all dependencies task fatJar(type: Jar) { manifest { attributes 'Implementation-Title': 'Dunk ChatBot', 'Implementation-Version': version, 'Main-Class': mainClassName } baseName = archivesBaseName + '_fat' from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } with jar }
-
make Main.kt inside src/main/kotlin/com/baihaqilp/fchatbot, and then fill it with this code;
package com.baihaqilp.fchatbot import spark.Spark.* import com.clivern.racter.BotPlatform import com.clivern.racter.receivers.webhook.* import com.clivern.racter.senders.* import com.clivern.racter.senders.templates.* import java.util.HashMap import java.io.IOException object Main { @Throws(IOException::class) @JvmStatic fun main(args:Array<String>) { // Verify Token Route get("/", { request, response-> val platform = BotPlatform("src/main/java/resources/config.properties") platform.getVerifyWebhook().setHubMode(if ((request.queryParams("hub.mode") != null)) request.queryParams("hub.mode") else "") platform.getVerifyWebhook().setHubVerifyToken(if ((request.queryParams("hub.verify_token") != null)) request.queryParams("hub.verify_token") else "") platform.getVerifyWebhook().setHubChallenge(if ((request.queryParams("hub.challenge") != null)) request.queryParams("hub.challenge") else "") if (platform.getVerifyWebhook().challenge()) { platform.finish() response.status(200) return@get if ((request.queryParams("hub.challenge") != null)) request.queryParams("hub.challenge") else "" } platform.finish() response.status(403) "Verification token mismatch" }) post("/", { request, response-> val body = request.body() val platform = BotPlatform("src/main/java/resources/config.properties") platform.getBaseReceiver().set(body).parse() val messages = platform.getBaseReceiver().getMessages() as HashMap<String, MessageReceivedWebhook> for (message in messages.values) { val user_id = if ((message.hasUserId())) message.getUserId() else "" val page_id = if ((message.hasPageId())) message.getPageId() else "" val message_id = if ((message.hasMessageId())) message.getMessageId() else "" val message_text = if ((message.hasMessageText())) message.getMessageText() else "" val quick_reply_payload = if ((message.hasQuickReplyPayload())) message.getQuickReplyPayload() else "" val timestamp = (if ((message.hasTimestamp())) message.getTimestamp() else 0).toLong() val attachments = if ((message.hasAttachment())) message.getAttachment() as HashMap<String, String> else HashMap<String, String>() platform.getLogger().info("User ID#:" + user_id) platform.getLogger().info("Page ID#:" + page_id) platform.getLogger().info("Message ID#:" + message_id) platform.getLogger().info("Message Text#:" + message_text) platform.getLogger().info("Quick Reply Payload#:" + quick_reply_payload) for (attachment in attachments.values) { platform.getLogger().info("Attachment#:" + attachment) } val text = message.getMessageText() val message_tpl = platform.getBaseSender().getMessageTemplate() val button_message_tpl = platform.getBaseSender().getButtonTemplate() val list_message_tpl = platform.getBaseSender().getListTemplate() val generic_message_tpl = platform.getBaseSender().getGenericTemplate() val receipt_message_tpl = platform.getBaseSender().getReceiptTemplate() if (text == "text") { message_tpl.setRecipientId(message.getUserId()) message_tpl.setMessageText("Hello World") message_tpl.setNotificationType("REGULAR") platform.getBaseSender().send(message_tpl) } else if (text == "image") { message_tpl.setRecipientId(message.getUserId()) message_tpl.setAttachment("image", "http://techslides.com/demos/samples/sample.jpg", false) message_tpl.setNotificationType("SILENT_PUSH") platform.getBaseSender().send(message_tpl) } else if (text == "file") { message_tpl.setRecipientId(message.getUserId()) message_tpl.setAttachment("file", "http://techslides.com/demos/samples/sample.pdf", false) message_tpl.setNotificationType("NO_PUSH") platform.getBaseSender().send(message_tpl) } else if (text == "video") { message_tpl.setRecipientId(message.getUserId()) message_tpl.setAttachment("video", "http://techslides.com/demos/samples/sample.mp4", false) platform.getBaseSender().send(message_tpl) } else if (text == "audio") { message_tpl.setRecipientId(message.getUserId()) message_tpl.setAttachment("audio", "http://techslides.com/demos/samples/sample.mp3", false) platform.getBaseSender().send(message_tpl) } return@post "ok" } "bla" }) } }
-
make config.properties inside src/main/com/resources app_id=app id here verify_token=verify token here page_access_token=access token here log_console_status=false log_console_level=ALL log_file_status=false log_file_level=ALL log_file_path=src/main/java/resources/app.log log_file_limit=1 log_file_count=200000 log_file_append=true
-
open 2 terminal, 1 for "./gradlew run" and 1 for "./ngrok http 4567"
-
create a facebook page
-
create a facebook app Go to the Facebook Developer Page and click “Skip and Create App ID” at the top right. Then create a new Facebook App for your chat bot and give your app a name and contact email.
You can get the app id and insert that id in config.properties file you created
-
choosee messenger . From the Messenger settings for your Facebook App, You can connect your app with the facebook page to get access token.
-
Then we need to setup our webhook like the following:
-
Please note that, You can set Verify Token to be any value and pass that value to our config.properties file and restart our app (Just stop it and run ./gradlew run).
Then click Verify and Save.
- After you’ve configured your webhook, Just subscribe to the specific page you want to receive message notifications for.
Berdasarkan : http://clivern.com/how-to-create-a-facebook-messenger-bot-with-java/