0% found this document useful (0 votes)
5 views4 pages

Dialogflow Chatbot Code Empowerherwellness

Uploaded by

prachipingale001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Dialogflow Chatbot Code Empowerherwellness

Uploaded by

prachipingale001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Dialogflow

package com.example.empowerherwellness;
import android.content.Context;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.SessionsSettings;
import java.io.InputStream;

public class Dialogflow {

public static SessionsClient getDialogflowSession(Context context) {


try {
InputStream stream = context.getAssets().open("empowerherbot-wcib-62a9a7bb39b0.json");
GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
SessionsSettings sessionsSettings = SessionsSettings.newBuilder()
.setCredentialsProvider(() -> credentials)
.build();
return SessionsClient.create(sessionsSettings);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

DialogflowHelper

package com.example.empowerherwellness
import android.content.Context
import android.util.Log
import com.google.auth.oauth2.GoogleCredentials
import com.google.cloud.dialogflow.v2.*
import java.io.InputStream
import java.util.concurrent.Executors

object DialogflowHelper {
fun getDialogflowSession(context: Context): SessionsClient? {
return try {
val stream: InputStream = context.assets.open("empowerherbot-wcib-62a9a7bb39b0.json")
val credentials = GoogleCredentials.fromStream(stream)
val sessionsSettings = SessionsSettings.newBuilder()
.setCredentialsProvider { credentials }
.build()
SessionsClient.create(sessionsSettings)
} catch (e: Exception) {
e.printStackTrace()
null
}
}

fun sendMessageToDialogflow(context: Context, sessionId: String, userMessage: String, callback:


(String) -> Unit) {
Executors.newSingleThreadExecutor().execute {
try {
val sessionClient = getDialogflowSession(context)
if (sessionClient == null) {
callback("Error: Could not create session")
return@execute
}

val session = SessionName.of("empowerherbot-wcib", sessionId)


val textInput = TextInput.newBuilder().setText(userMessage).setLanguageCode("en").build()
val queryInput = QueryInput.newBuilder().setText(textInput).build()

val request = DetectIntentRequest.newBuilder()


.setSession(session.toString())
.setQueryInput(queryInput)
.build()

val response = sessionClient.detectIntent(request)


val botReply = response.queryResult.fulfillmentText

Log.d("Dialogflow Response", botReply)


callback(botReply)
} catch (e: Exception) {
e.printStackTrace()
callback("Error: ${e.message}")
}
}
}
}

MainActivity.kt

package com.example.empowerherwellness

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {

// Declare variables at class level (not inside onCreate)


private lateinit var userInput: EditText
private lateinit var sendButton: Button
private lateinit var botResponse: TextView
private lateinit var startButton: Button // Added here

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Initialize views
userInput = findViewById(R.id.userInput)
sendButton = findViewById(R.id.sendButton)
botResponse = findViewById(R.id.botResponse)
startButton = findViewById(R.id.start_button) // Initialize here

// Set up click listener for the send button


sendButton.setOnClickListener {
val message = userInput.text.toString()
if (message.isNotEmpty()) {
sendMessage(message)
}
}

// Set up click listener for the start button


startButton.setOnClickListener {
val intent = Intent(this, ContentActivity::class.java)
startActivity(intent)
}

// Check Dialogflow session once, not in sendMessage()


val sessionClient = DialogflowHelper.getDialogflowSession(this)
if (sessionClient != null) {
Log.d("Dialogflow", "Session created successfully!")
} else {
Log.e("Dialogflow", "Failed to create session.")
}
}

// Function to send user input to Dialogflow and get a response


private fun sendMessage(message: String) {
DialogflowHelper.sendMessageToDialogflow(this, "123456", message) { response ->
runOnUiThread {
botResponse.text = response
}
}
}
}

activity.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<EditText
android:id="@+id/userInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="48dp"
android:padding="12dp"
android:hint="Type your message..."
android:textSize="16sp"/>

<Button
android:id="@+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:layout_gravity="center"
android:padding="10dp"
android:marginTop="10dp"/>

<TextView
android:id="@+id/botResponse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bot Response will appear here..."
android:textSize="16sp"
android:padding="10dp"
android:layout_marginTop="10dp"/>

</LinearLayout>

You might also like