Giter Club home page Giter Club logo

fchatbot-kotlin's Introduction

fchatbot-Kotlin

Facebook Chatbot dengan Kotlin dan Spark framework, dengan ngrok

REQUIREMENT

* Kotlin
* Spark Framework
* Ngrok
* Facebook page
* Graddle
* JDK

Install

  1. Instal Download and Instal JDK URL: https://www.oracle.com/technetwork/java/javase/downloads/index.html

  2. Install gradle here : https://gradle.org/install/

  3. Install ngrok : https://ngrok.com/download

  4. 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
  5. make build.graddle inside fchatbot-kotlin dir

  6. go inside directory fchatbot-kotlin then install gradlewrap

    • gradle wrapper --gradle-version = 5.5.1
  7. make build.graddle like this.

    /*

// 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 }

  1. 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" })
     }
     }
    
  2. 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

  3. open 2 terminal, 1 for "./gradlew run" and 1 for "./ngrok http 4567"

  4. create a facebook page

  5. 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

  6. choosee messenger . From the Messenger settings for your Facebook App, You can connect your app with the facebook page to get access token.

  7. Then we need to setup our webhook like the following:

  8. 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.

  1. 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/

fchatbot-kotlin's People

Contributors

aravikapra avatar baihaqilp avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.