0% found this document useful (0 votes)
7 views

Final Report Major Project

The document presents a project report on 'PSYBOT – A Mental Health Telegram Chatbot' developed by students at Anna University, aimed at providing emotional support and resources for mental health through a user-friendly interface. The chatbot utilizes Python, sentiment analysis, and various libraries to tailor responses and offer self-help tools, while emphasizing that it is not a replacement for professional therapy. The project highlights the importance of accessible mental health support and the potential of AI-driven solutions in this field.

Uploaded by

epr17833
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Final Report Major Project

The document presents a project report on 'PSYBOT – A Mental Health Telegram Chatbot' developed by students at Anna University, aimed at providing emotional support and resources for mental health through a user-friendly interface. The chatbot utilizes Python, sentiment analysis, and various libraries to tailor responses and offer self-help tools, while emphasizing that it is not a replacement for professional therapy. The project highlights the importance of accessible mental health support and the potential of AI-driven solutions in this field.

Uploaded by

epr17833
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

PSYBOT

MENTAL HEALTH TELEGRAM CHATBOT

A PROJECT REPORT
Submitted by

ASHOK RAJARAM S (950020104008)


RAMAJEYAM R (950020104033)
VENKATESAN M (950020104045)
ABDUL FARIS A (950020104301)

in partial fulfillment for the award of the degree of

BACHELOR OF ENGINEERING
In

COMPUTER SCIENCE AND ENGINEERING

ANNA UNIVERSITY REGIONAL CAMPUS – TIRUNELVELI

ANNA UNIVERSITY : CHENNAI 600 025

MAY 2024
ANNA UNIVERSITY : CHENNAI 600 025

BONAFIDE CERTIFICATE

Certified that this project report titled “PSYBOT – A MENTAL HEALTH


TELEGRAM CHATBOT” is the bonafide work of ASHOK RAJARAM S
(950020104008), RAMAJEYAM R (950020104033), VENKATESAN M
(950020104045), ABDUL FARIS A (950020104301) who carried out the project
work under my supervision.

SIGNATURE SIGNATURE
Dr. C. AKILA Dr. J. JESU VEDHA NAYAHI
HEAD OF THE DEPARTMENT SUPERVISOR
Assistant Professor, Senior Assistant Professor,
Dept. of Computer Science Dept. of Computer Science
and Engineering, and Engineering,
Anna University Regional Anna University Regional
Campus - Tirunelveli, Campus - Tirunelveli,
Tirunelveli – 627007. Tirunelveli – 627007.

Submitted for the CS8811 Viva–Voce examination held on / / 2024

INTERNAL EXAMINER EXTERNAL EXAMINER

ii
ACKNOWLEDGEMENT

We wish to express our deep sense of gratitude and sincere indebtedness to


Dr. N. SHENBAGA VINAYAGA MOORTHI, Professor and Dean, Anna
University Regional Campus - Tirunelveli, for his support and encouragement
throughout this project work.

We wish to express our sincere gratitude to our Head of the Department and
Project coordinator Dr. C. AKILA, Assistant Professor, Department of Computer
Science and Engineering, for her motivation, inspiration and encouragement to
undertake this work.

We wish to express our special thanks and our deepest gratitude to our guide
Dr. J. JESU VEDHA NAYAHI, Senior Assistant Professor, Department of
Computer Science and Engineering, for her suggestions and supports during the
course of our project.

We are also indebted to all the teaching and non-teaching staff members of
our college for helping us directly or indirectly by all means throughout the course
of our study and project work.

ASHOK RAJARAM S

RAMAJEYAM R

VENKATESAN M

ABDUL FARIS A

iii
ABSTRACT

This project aimed to develop a mental health chatbot using Python to provide
emotional support, resources, and tools to users. The chatbot leverages Telegram's
messaging platform for user interaction and integrates various functionalities to
promote mental well-being.

The chatbot employs sentiment analysis to understand the emotional tone of a


user's message (positive, negative, or neutral). This sentiment information is then
used to tailor responses and provide targeted support. It acts as a resource hub,
offering users access to a variety of mental health resources. This includes links to
websites, hotlines, and support groups categorized based on specific needs (e.g.,
anxiety, depression).

The chatbot provides users with options for relaxation techniques and self-help
tools. This may include guided breathing exercises, etc. Additionally, the chatbot
offers short meditation guides to help users manage stress and improve focus.

It is built using Python and leverages several libraries for its functionalities.
Sentiment analysis is performed using the FLAIR library. Text generation and
response tailoring are achieved through a fine-tuned Large Language Model (LLM)
integrated via HuggingFace and LangChain libraries. The Telegram Bot API allows
for user interaction within the Telegram messaging platform.

This project demonstrates the potential of chatbots in promoting mental health


awareness and providing accessible support tools. By offering emotional support,
relevant resources, and self-help techniques, the chatbot can empower users to
manage their mental well-being and connect with necessary resources.

iv
TABLE OF CONTENTS

CHAPTER NO. TITLE PAGE NO.

ABSTRACT iv

LIST OF FIGURES viii

LIST OF TABLES ix

LIST OF ABBREVIATIONS x

1 INTRODUCTION 1

1.1 OBJECTIVE 2

1.2 SCOPE 3

1.3 LITERATURE REVIEW 3

1.4 PROBLEM DEFINITION 5

2 SYSTEM DESCRIPTION 6

2.1 SYSTEM REQUIREMENTS 6

2.1.1 Hardware Requirements 6

2.1.2 Software Requirements 6

2.1.3 Python 7

2.1.4 Python-telegram-bot 7

2.1.5 NLP and ML Libraries 8

2.2 SYSTEM ANALYSIS 8

2.2.1 Existing System 8

2.2.2 Proposed Work 11

v
3 SYSTEM DESIGN 12

3.1 ARCHITECTURE DIAGRAM 12

3.2 DATA FLOW DIAGRAM 12

3.2.1 DFD Level 0 12

3.2.2 DFD Level 1 13

3.2.3 DFD Level 2 14

3.3 USE CASE DIAGRAM 15

4 SYSTEM DEVELOPMENT 16

4.1 MODULES 16

4.1.1 User Interaction Module 16


4.1.2 Processing and Understanding
16
Module
4.1.3 Response Generation and Resource
17
Management Module
5 SYSTEM IMPLEMENTATION AND TESTING 18

5.1 IMPLEMENTATION 18

5.1.1 User Integration 18

5.1.2 Processing and Understanding 20

5.1.3 Response Generation and Resource


22
Management

5.2 TESTING 26

5.2.1 TEST CASE 26

5.2.1.1 User Interaction Module 26

5.2.1.2 Processing and


27
Understanding Module

vi
5.2.1.3 Response Generation and
28
Resource Management Module

6 CONCLUSION 29

APPENDIX 30

REFERENCES 40

vii
LIST OF FIGURES

FIG NO. FIGURE NAME PAGE NO.

3.1 Architecture Diagram 12

3.2 DFD Level 0 13

3.3 DFD Level 1 13

3.4 DFD Level 2 14

3.5 Use case Diagram 15

3.6 Entity Relationship Diagram 16

5.1 User Integration with Telegram 19

5.2 Command list in the telegram bot 20

5.3 Starting the bot 21

5.4 Response generated and delivered to the user 22

5.5 Guided meditation session 23

5.6 Bot suggesting techniques and meditation 24

5.7 Bot generating random quotes 25

5.8 Bot generating affirmations 26

viii
LIST OF TABLES

TABLE NO. TABLE NAME PAGE NO.

5.1 User Interaction Module 28

5.2 Processing and Understanding Module 28

Response Generation and Resource


5.3 29
Management Module

ix
LIST OF ABBREVIATIONS

AI ARTIFICIAL INTELLIGENCE

NLP NATURAL LANGUAGE PROCESSING

ML MACHINE LEARNING

RAM RANDOM ACCESS MEMORY

API APPLICATION PROGRAMMING INTERFACE

CBT COGNITIVE BEHAVIORAL THERAPY

LLM LARGE LANGUAGE MODEL

DFD DATA FLOW DIAGRAM

UML UNIFIED MODELING LANGUAGE

UI USER INTERFACE

LSTM LONG SHORT-TERM MEMORY

RNN RECURRENT NEURAL NETWORK

x
CHAPTER 1

INTRODUCTION

In a world where mental health support is crucial yet often inaccessible, our
chatbot serves as a beacon of hope and understanding. Powered by advanced
technology and crafted with empathy, our chat-bot is designed to provide a safe space
for you to express your thoughts, feelings, and concerns without judgment. Whether
you are struggling with anxiety, depression, stress, or simply need someone to talk to,
our chatbot is here to lend a compassionate ear 24/7. Through thoughtful
conversation and personalized guidance, it aims to empower you on your path to
mental wellness.

Our chatbot doesn't replace professional therapy, but it complements it by


offering immediate support and resources whenever you need them. It can provide
coping strategies, mindfulness exercises, and helpful insights to assist you in
managing your mental health. Above all, our chatbot is here to remind you that you
are not alone. No matter what challenges you are facing, there's always someone here
to listen, support, and guide you towards a brighter tomorrow.

Statistics show that 1 in every 5 individuals suffers from some form of mental
health illness symptoms. 50% of mental health conditions begin by age 14 and 75%
of mental health conditions develop by age 24. This project contributes to the
growing field of mental health chatbots by demonstrating the potential of AI to create
accessible and user-friendly support tools. By offering emotional support, relevant
resources, and self-help techniques, the chatbot empowers users to take charge of
their mental well-being and connect with necessary resources.

1
1.1 OBJECTIVE

This project aimed to develop a mental health chatbot using Python to bridge
the gap in accessible mental health support tools. The specific objectives focused on
creating a user-friendly and informative platform that prioritizes user safety and
emotional well-being.

It is centered on equipping the chatbot with the ability to understand the


emotional tone of user interactions. By leveraging this sentiment information, the
chatbot could tailor its responses to provide targeted support. For example, in cases of
negative sentiment, the chatbot could offer words of encouragement or suggest
coping mechanisms. Conversely, for positive sentiment, the chatbot could celebrate
the user's progress and offer continued support.

It involves creating a comprehensive resource hub within the chatbot interface.


This resource hub would act as a central location for users to access curated
information and support related to a specific healthcare domain. The resources could
include links to websites offering relevant information, hotlines for immediate
assistance in crisis situations, and support group information to connect users with
others facing similar challenges. Also focused on empowering users by providing
them with self-help tools directly within the chatbot platform. These tools could
encompass various techniques aimed at promoting self-care and managing
well-being. Examples might include guided relaxation exercises, short meditation
guides, etc.

Additionally, the chatbot would acknowledge its limitations by emphasizing


that it is a supportive tool but cannot replace professional help. By achieving these
overarching objectives, the project aimed to create a valuable and accessible chatbot
application that empowers users to manage their well-being, access relevant
resources, and utilize self-help tools – all within a safe and user-friendly platform.

2
1.2 SCOPE

This project focuses on creating a mental health chatbot application using


Python. The core functionalities include sentiment analysis for understanding user
emotions, tailored responses based on sentiment, and a curated mental health resource
hub. Users will also have access to self-help tools like relaxation exercises and
meditation guides.

It will initially focus on supporting a specific mental health area with resources
and tools tailored accordingly. The chatbot is intended as a supportive tool, not a
replacement for professional help. Complex features and functionalities like
personalized therapy plans are outside the scope of this initial version.

It will be designed to identify users in crisis and provide appropriate resources.


This defined scope allows for a focused and achievable project, with future iterations
potentially expanding functionalities based on evaluation and user feedback.

1.3 LITERATURE REVIEW

[1]AI Applications in Mental Health Care (2020)

The authors explore the diverse applications of Artificial Intelligence (AI) in


mental health care, focusing on the development and evaluation of AI-driven tools
and interventions. The survey reviews existing literature on AI-based approaches for
screening, diagnosis, treatment, and monitoring of various mental health conditions,
including depression, anxiety, schizophrenia, and bipolar disorder. It examines the
effectiveness, feasibility, and ethical considerations associated with AI technologies
in mental health care.

3
[2]NLP Techniques for Sentiment Analysis in Mental Health (2019)

This literature review examines the use of Natural Language Processing (NLP)
techniques for sentiment analysis in the context of mental health. The survey provides
an overview of existing research on sentiment analysis methods applied to textual
data from individuals with mental health conditions, such as social media posts,
online forums, and electronic health records. It discusses the challenges and
opportunities of using NLP for sentiment analysis in mental health care, including
data privacy concerns, linguistic variability, and model interpretability issues.

[3]Machine Learning Algorithms for Mood Detection and Emotional Analysis


(2021)

This survey explores the landscape of machine learning algorithms used for
mood detection and emotional analysis in mental health research and applications.
The survey reviews various machine learning techniques, including supervised,
unsupervised, and deep learning approaches, employed for mood classification,
emotion recognition, and affective computing tasks. It assesses the strengths,
limitations, and computational complexities of different machine learning algorithms
in capturing and analyzing emotional states from diverse data sources, such as text,
speech, and physiological signals. The survey also discusses the implications of using
machine learning for mood detection in clinical settings and potential avenues for
future research in this field.

4
1.3 PROBLEM DEFINITION

Limited access to mental health services due to geographical, financial, or


social barriers. Fear of judgement or discrimination prevents individuals from seeking
help or disclosing their mental health concerns. Insufficient availability of mental
health professionals and support services to meet the growing demand. Delays in
receiving mental health support can exacerbate symptoms and lead to worsening
mental health outcomes.

The problem definition extends to the integration of mental health support


services across multiple digital platforms, including WhatsApp, Telegram, Instagram,
and websites. While traditional mental health care services primarily operate through
conventional channels such as clinics and hotlines, there is a growing need to expand
the reach and accessibility of support through popular digital platforms that
individuals frequently use in their daily lives.

Integrating mental health services into platforms like WhatsApp, Telegram and
Instagram offers several advantages. Firstly, it meets individuals where they are most
comfortable and active online, reducing barriers to seeking help and support.
Secondly, it enables real-time and asynchronous communication, allowing users to
access support whenever they need it, regardless of time or location. Thirdly, it
facilitates personalized and interactive experiences, leveraging the unique features of
each platform to deliver tailored interventions and engage users in meaningful ways.

5
CHAPTER 2

SYSTEM DESCRIPTION

2.1 SYSTEM REQUIREMENTS

System requirements are the configuration that a system must have in order for
a hardware or software application to run smoothly and efficiently. Failure to meet
these requirements can result in installation problems or performance problems. The
former may prevent a device or application from getting installed, whereas the latter
may cause a product to malfunction or perform below expectation or even to hang or
crash.

2.1.1 Hardware Requirements


● Processor : Intel Core™ i3 or equivalent.

● Memory : 8 GB RAM or higher.

● Hard Disk : up to 200MB of available space may be required.

● Network : Reliable internet connection with good bandwidth.

2.1.2 Software Requirements


● Operating System : Windows

● Architecture : Client Server

● Programming Language : Python

● Libraries required : Flair, Python-telegram-bot, Huggingface


transformers, Langchain, Torch

6
2.1.3 PYTHON

Python, a versatile and high-level programming language, is celebrated for its


simplicity, readability, and extensive libraries. It's widely used across various
domains, including web development, data analysis, scientific computing, and
artificial intelligence. Python's clean syntax and dynamic typing make it ideal for
both beginners and experienced developers, fostering quick prototyping and scalable
solutions. Its vibrant community continually enriches the ecosystem, ensuring Python
remains a go-to choice for diverse projects and industries.

2.1.4 PYTHON-TELEGRAM-BOT

The python-telegram-bot library is a powerful and user-friendly Python


interface for the Telegram Bot API. It allows developers to create Telegram bots
using Python, enabling them to interact with users, send messages, receive updates,
and perform various other actions. The library provides comprehensive support for
the Telegram Bot API, allowing developers to interact with Telegram's messaging
platform. This includes sending and receiving messages, managing conversations,
handling callbacks, and accessing bot-related data. It supports asynchronous
programming using the async.io framework, making it easy to create efficient and
scalable bots that can handle multiple concurrent requests and events asynchronously.

7
2.1.5 NLP AND ML LIBRARIES

Flair and Hugging Face are leading libraries in Natural Language Processing
(NLP), offering powerful tools and resources for developers. Flair, developed by
Zalando Research, provides state-of-the-art NLP models and embeddings, along with
an easy-to-use framework for training custom models. Hugging Face's Transformers
library is renowned for its vast collection of pre-trained models and APIs, enabling
seamless integration of cutting-edge NLP capabilities into applications. Langchain,
another notable project, focuses on multilingual NLP research and development,
contributing to the advancement of language understanding across diverse linguistic
contexts. PyTorch, the underlying framework for both Flair and Transformers,
provides efficient tensor computation with Graphics Processing Unit (GPU)
acceleration, making it a cornerstone of modern deep learning research and
application.

2.2 SYSTEM ANALYSIS

2.2.1 Existing System

Woebot[4]

Developed by Stanford University researchers, Woebot utilizes techniques


from Cognitive Behavioral Therapy (CBT) to help users manage negative emotions
and develop coping skills. It focuses on providing anonymous support through
text-based interactions.

Advantages

● Woebot's structured approach based on CBT can be effective for users


experiencing anxiety, depression, or stress.

● The anonymous nature encourages open communication without fear of


judgment.
8
Disadvantages

● Might not be suitable for addressing complex mental health conditions


requiring more specialized interventions.

● The text-based format limits the ability to convey empathy and nuance
compared to human interaction.
Youper[5]
Youper combines elements of CBT with techniques from positive psychology
to promote emotional well-being. It personalizes recommendations and support
strategies based on user data collected through questionnaires and interaction
patterns.
Advantages

● Youper's personalized approach tailors support to individual needs,


potentially leading to more effective interventions.

● The integration of positive psychology techniques can help users build


resilience and cultivate positive emotions.
Disadvantages

● Youper requires user registration, which might deter users seeking complete
anonymity.

● The reliance on user data raises privacy concerns, and the effectiveness of
personalization algorithms might vary depending on the amount and quality
of data collected.

9
Wysa[6]
Wysa takes a conversational AI approach, utilizing a friendly virtual
companion persona to engage with users. It offers emotional coaching, mindfulness
exercises, and mood tracking functionalities.

Advantages:

● Wysa's conversational approach can be engaging and appealing to users,


fostering a sense of connection and support.

● The integration of mindfulness exercises and mood tracking tools empowers


users to develop self-management skills.
Disadvantages

● Wysa's availability might be limited in certain regions. Data collection


practices for user interactions and potential emotional profiling raise privacy
concerns.

● The effectiveness of the conversational AI may vary depending on user


expectations and the complexity of their mental health needs.

10
2.2.2 Proposed Work
Building upon the functionalities of existing mental health chatbots and
acknowledging their limitations, this project proposes a novel mental health chatbot
designed to address limitations found in existing systems. We will focus on a specific
mental health domain (e.g., anxiety, stress) to provide more targeted support and
resources. A sentiment analysis model, trained using the FLAIR library, will
categorize user messages to understand their emotional tone. A fine-tuned Large
Language Model (LLM) from HuggingFace Transformers will generate tailored
responses that consider the sentiment tone of the user. This ensures responses are
empathetic and supportive, addressing the user's specific state.
To prioritize user privacy, conversations will be confidential and not stored.
The chatbot will be transparent about data collection practices, if any, and offer users
control over their data. Accessibility is also a priority, So, the chatbot is integrated
with the telegram platform to be accessed by anyone who has a telegram account.

11
CHAPTER 3
SYSTEM DESIGN
3.1 ARCHITECTURE DIAGRAM

Fig 3.1 Architecture Diagram

Fig 3.1 shows the mental health chatbot system. Users interact via a messaging
platform (i.e., Telegram). The system analyzes messages to understand emotions,
then generates tailored responses using a large language model. An optional data
management module can store anonymized data.

3.2 DATA FLOW DIAGRAM

3.2.1 DFD Level 0

DFD Level 0 is also called a Context Diagram. It’s a basic overview of the
whole system or process being analysed or modelled. It’s designed to be an
at-a-glance view, showing the system as a single high-level process.

12
Fig 3.2 DFD Level 0

Fig 3.2 shows the entire chatbot application as a single entity interacting with
two external entities: the User and the Mental Health Resources database.

3.2.2 DFD Level 1

DFD Level 1 provides a more detailed breakout of pieces of the Context Level
Diagram. You will highlight the main functions carried out by the system, as you
break down the high-level process of the Context Diagram into its sub processes.

Fig 3.3 DFD Level 1

13
Fig 3.3 reveals the core processes within the application. It shows how user
input interacts with the Messaging Platform API, Sentiment Analysis, Response
Generation, and optional Data Management modules. It also emphasizes the
connection to the Mental Health Resources for retrieving relevant information

3.2.3 DFD Level 2

DFD Level 2 then goes one step deeper into parts of Level 1. It may require
more text to reach the necessary level of detail about the system’s functioning.

Fig 3.4 DFD Level 2

Fig 3.4 focuses specifically on the Response Generation Module. It dives


deeper into how sentiment analysis results and responses from the LLM (Large
Language Model) are combined to create the final tailored response delivered to the
user.

14
3.3 USE CASE DIAGRAM

A use case diagram is a graphic depiction of the interactions among the


elements of the system. A use case is a methodology used in system
analysis to identify, clarify and organize system requirements. Use case
diagrams are employed in UML, a standard notation for the modelling of

real-world objects and systems.

Fig 3.5 Use case Diagram

Fig 3.5 displays the use case diagram of the chatbot in real time scenarios.

15
CHAPTER 4

SYSTEM DEVELOPMENT

4.1 MODULES

4.1.1 User Interaction Module

This module provides the user with a seamless interaction point. The User
Interface (UI), integrated with messaging platform (I.e., Telegram messenger), allows
users to send text messages and receive responses from the chatbot. Usability is
prioritized, ensuring clear instructions and intuitive navigation for a user-friendly
experience. Also Telegram offers extensive customization features for resource
delivery through Telegram commands.

4.1.2 Processing and Understanding Module

This module focuses on analyzing user input and preparing it for response
generation. The Natural Language Processing (NLP) module plays a crucial role here.
Sentiment analysis, powered by a trained model (FLAIR), which uses Long
Short-Term Memory(LSTM) algorithm with Recurrent Neural Network(RNN) to
identify the emotional tone (positive, negative, neutral) in user messages,
understanding the user's state of mind. Additionally, Text Preprocessing cleans and
prepares the message for further processing by removing unnecessary elements and
ensuring a structured format.

16
4.1.3 Response Generation and Resource Management Module

The response generation and resource modules work in harmony to provide


users with personalized support. The core of response generation lies in a fine-tuned
large language model (LLM). This AI powerhouse, trained on massive amounts of
text, crafts informative and supportive messages tailored to the user's situation.
Sentiment analysis, potentially using Flair, plays a crucial role by helping the LLM
understand the user's emotional tone. This allows for adjusting responses, offering
encouragement for negativity or celebrating progress for positivity. Additionally, the
chatbot maintains conversation history, ensuring responses build upon past
interactions. The resource module complements this by offering relevant information
through a retrieval engine. This engine considers the user's message, sentiment, and
potentially even preferences to identify suitable resources. Curated resources might
include website links, hotlines for crisis situations, or support group details, all
empowering users with knowledge and connection opportunities. This integrated
approach fosters a safe space for emotional expression while equipping users with the
tools they need to manage their well-being

17
CHAPTER 5

SYSTEM IMPLEMENTATION AND TESTING

5.1 IMPLEMENTATION

Implementation planning is a process in project management that entails


creating step-by-step instructions for completing projects. The purpose of this process
is to inform members of a project team of the concrete actions and individual tasks
required to achieve the team’s strategic goals.

5.1.1 User Integration

Fig 5.1 User Integration with Telegram

18
Fig 5.1 shows the user interface of the telegram bot after creating the bot using
Bot Father. This is the first page which shows the description of the bot.

Fig 5.2 The commands list created in the telegram bot

Fig 5.2 shows the available commands the user can access to trigger various
action of the bot.(Resources, Techniques, Meditation, Quotes, Affirmation),

19
5.1.2 Processing and Understanding

Fig 5.3 Starting the bot

Fig 5.3 shows the initialization of the bot. The bot initiates the chat by
explaining about itself and asks the user to interact with it.

20
Fig 5.4 Response generated and delivered to the user

Fig 5.4 shows the bot responding to the user. The bot detected the emotion of
the user and tailored the response to encourage and cheer the user and also provides
the meditation command to start a short meditation session.

21
5.1.3 Response Generation and Resource Management

Fig 5.5 Guided meditation session

Fig 5.5 shows the chatbot displaying a guided meditation session message
when the meditation command is clicked. The user can also access the meditation
command by typing /meditation.

22
Fig 5.6 Bot suggesting techniques and meditation

Fig 5.6 shows the bot response with techniques command which takes us to the
available techniques or coping strategies to reduce stress or depression. By clicking
each technique, It takes you to an external link which contains a detailed explanation
of the technique.

23
Fig 5.7 Bot generating random quotes

Fig 5.7 shows the bot generating a quote each time the quotes command is
started or clicked. It is to motivate the user using a motivational or inspiration quote.

24
Fig 5.8 Bot generating affirmations

Fig 5.8 shows the bot generating random affirmations each time the affirmation
command is used to boost the mood of the user and to make his day

25
5.2 TESTING

Testing is an important aspect of the Software Development Life Cycle. This is


the stage where we confirm whether the project has achieved the ultimate goal or not
testing encompasses a set of activities that were conducted systematically. This
begins at the module level and works towards the integration of the entire system.
The purpose of testing the system is to identify various bugs and to fix them. It
provides a way to check the functionality. It is the process of exercising software with
the intent of ensuring that the software system meets its requirements and user
expectations and does not fail in an unacceptable manner.

5.2.1 TEST CASE

A test case is a document, which has a set of test data, preconditions, expected
results and post conditions, developed for a particular test scenario in order to verify
compliance against a specific requirement.

5.2.1.1 User Interaction Module


S. No Input Desired Output Obtained Output Test case result
1 /start command The chatbot sends The chatbot Pass
a welcome initiates the chat
message introducing itself
introducing itself and its
and its functionalities
functionalities
2 /help command The chatbot sends The chatbot Pass
a comprehensive displays a message
manual of how to on how to use the
use the bot bot and about its
limitations
3 /resources The chatbot sends The chatbot Pass
command a list of relevant displays a message
mental health resources to support
resources the user

26
4 /techniques The chatbot sends The chatbot Pass
command a list of coping displays techniques
strategies or to support the user
techniques
5 /meditation The chatbot The chatbot Pass
command displays a displays a message
message with a with a guided
guided meditation meditation session
session
6 /quotes Generates a Generates a random Pass
command random quote to inspiration quote
motivate the user each time
7 /affirmation Generates a Generates a random Pass
command random affirmation
affirmation message each time
message to boost
the user mood

Table 5.1 User Interaction Module

5.2.1.2 Processing and Understanding Module


S. No Input Desired Output Obtained Output Test case result
1 User sends the Sentiment analysis Sentiment analysis Pass
message "I'm identifies the identifies the
feeling emotional tone as emotional tone as
exhausted negative negative
today."
2 User sends the Sentiment analysis Sentiment analysis Pass
message "I'm identifies the identifies the
feeling emotional tone as emotional tone as
grateful for the positive positive
support!"

Table 5.2 Processing and Understanding Module

27
5.2.1.3 Response Generation and Resource Management Module
S. No Input Desired Output Obtained Output Test case result
1 User sends the The LLM The LLM generates Pass
message "I'm generates a a supportive and
feeling supportive encouraging
anxious." response response
acknowledging understanding the
the user's anxiety user’s anxiety
2 User sends the The LLM The LLM generates Pass
message "I'm generates a a cheerful and
feeling response motivating response
motivated acknowledging understanding the
today!" the user's positive user’s positive tone
mood
3 User sends the The LLM The LLM provides Pass
message "How generates a a response with the
can I cope response relevant resources
with stress?" providing on coping up with
information on stress
coping with stress

Table 5.3 Response Generation and Resource Management Module

28
CHAPTER 6

CONCLUSION

In conclusion, the development of this mental health chatbot application holds


significant promise for promoting accessibility to mental health support and
resources. By integrating seamlessly with Telegram, the application offers a
user-friendly and convenient platform for users to engage in supportive conversations
and access relevant information.

The positive impact of this project extends beyond the individual user. By
offering a safe and anonymous platform for expression, it can help reduce stigma
surrounding mental health issues. Furthermore, the potential for scalability allows this
technology to reach a wider population, fostering a more open and supportive
conversation about mental well-being on a global scale.

Looking towards the future, this project presents exciting possibilities for
further development. Advanced personalization features that incorporate user context
from past interactions can be implemented to provide even more tailored support.
Additionally, exploring the integration of more advanced language models with larger
datasets could enable the chatbot to engage in deeper and more nuanced
conversations, fostering a deeper level of understanding and support for users.

29
APPENDIX

Telegram_bot.py

from typing import Final

from telegram.ext import Application, CommandHandler, MessageHandler, filters

from telegram.constants import ParseMode

from resources import quotes, affirmations, articles, techniques, meditation

# Replace with your Telegram bot token

TOKEN: Final = "6910056596:AAFzsuVDigtGcynh_cTvfdS21wTK5d2_bEo"

BOT_USRENAME: Final = "@ashok_psy_bot"

from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

from langchain_community.llms import HuggingFacePipeline

import torch

from flair.data import Sentence

from flair.models import TextClassifier # Import FLAIR for sentiment analysis

ment_model = TextClassifier.load('en-sentiment') # Load pre-trained sentiment


model

checkpoint = "./model/" # Replace with path to your fine-tuned model

tokenizer = AutoTokenizer.from_pretrained(checkpoint)

base_model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint,

device_map='auto',

torch_dtype=torch.float32)
30
llm = HuggingFacePipeline.from_model_id(model_id=checkpoint,

task='text2text-generation',

model_kwargs={"min_length": 30, "max_length": 600,


"repetition_penalty": 5.0})

from langchain.chains import LLMChain

from langchain_core.prompts import PromptTemplate

template = """{text}"""

prompt = PromptTemplate(template=template, input_variables=["text"])

chat = LLMChain(prompt=prompt, llm=llm)

def get_sentiment(text):

"""Analyzes sentiment of the user's message using FLAIR"""

sentence = Sentence(text)

sentiment_model.predict(sentence)

sentiment = sentence.labels[0].value

return sentiment

def handle_resources(sentiment, text):

"""Suggests resources based on sentiment and keywords"""

resource_suggestion = ""

if sentiment == 'NEGATIVE':

resource_suggestion = 'Sample suggestion text'

return resource_suggestion

31
#start command

async def start_command(update, context):

await update.message.reply_text("""Hi there! I'm your mental health companion


bot. I can't replace a therapist, but I offer a safe space to talk, suggest resources, and
help you explore ways to manage stress, anxiety, or low moods. Let me know what's
on your mind or ask me anything!

How can I support you today?""")

#help command

async def help_command(update, context):

await update.message.reply_text("""Hi there! I'm here to support your mental


well-being.

What I can do:

* Listen without judgment and offer emotional support.

* Suggest resources like websites, hotlines, and self-help materials.

* Provide simple coping mechanisms for stress, anxiety, or low moods.

* Analyze your messages to understand your emotions and offer relevant advice.

How to interact with me:

* Just type and let's chat!

* You can use keywords like "stressed," "anxious," or "low mood" to get targeted
support.

* Feel free to ask questions or share what's on your mind.

* Remember: I'm here for support, but I cannot replace a therapist.""")

32
#resources command

async def resources_command(update, context):

message = articles.articles_list

await update.message.reply_text(message, parse_mode = ParseMode.HTML)

#resources command

async def techniques_command(update, context):

message = techniques.techniques_list

await update.message.reply_text(message, parse_mode = ParseMode.HTML)

#meditation command

async def meditation_command(update, context):

message = meditation.guide

await update.message.reply_text(message, parse_mode = ParseMode.HTML)

#quotes command

async def quotes_command(update, context):

message = f"""Here is a quote for the day

<b><i>{quotes.generate_quote()}</i></b>

"""

await update.message.reply_text(message, parse_mode = ParseMode.HTML)

#affirmation command

async def affirmation_command(update, context):

message = f"""Need a confidence boost? Here is an affirmation to boost your mood


33
<b><i>{affirmations.generate_affirmation()}</i></b>

"""

await update.message.reply_text(message, parse_mode = ParseMode.HTML)

#message handler

async def handle_message(update, context):

message_type = update.message.chat.type

text = update.message.text

print(f'User ({update.message.chat.id}) in {message_type} says: {text}')

sentiment = get_sentiment(text)

print(sentiment)

if sentiment == "NEGATIVE":

reply = chat.run("My mental health is negative" + text + ". Can you give me
some advice to motivate me")

check = ['breath', 'support', 'depressed', 'stress', 'manage']

if any(word in reply for word in check):

reply += "\n\nType /techniques to know more about coping strategies and


techniques"

if 'meditate' or 'meditation' in reply:

reply += "\n\nClick /meditation to start a short meditation session if you are


interested"

else:

reply = chat.run("I feel positive" + text + "Cheer me up")

34
reply = "User emotion: " + sentiment + "\n" + reply

print(f'Bot response: {reply}')

await update.message.reply_text(reply)

async def error(update, context):

print(f"Update {update} caused error {context.error}")

if __name__ == "__main__":

print("Starting the bot...")

app = Application.builder().token(TOKEN).build()

# Command handlers

app.add_handler(CommandHandler("start", start_command))

app.add_handler(CommandHandler("help", help_command))

app.add_handler(CommandHandler("resources", resources_command))

app.add_handler(CommandHandler("techniques", techniques_command))

app.add_handler(CommandHandler("meditation", meditation_command))

app.add_handler(CommandHandler("quotes", quotes_command))

app.add_handler(CommandHandler("affirmation", affirmation_command))

# Message handler

app.add_handler(MessageHandler(filters.TEXT, handle_message))

# Error handler

app.add_error_handler(error)

35
# Polling

print("Bot is running...")

app.run_polling(poll_interval=3)

meditation.py

guide = """Feeling stressed? Take a moment to relax with this short mindfulness
meditation.

Mindfulness meditation helps you focus on the present moment and reduce stress.
Here's a simple exercise you can try:

1. <b>Find a comfortable position:</b> Sit or lie down in a way that allows you to
relax.

2. <b>Close your eyes gently:</b> If you prefer, you can soften your gaze instead.

3. <b>Focus on your breath:</b> Notice the sensation of your breath entering and
leaving your body. Don't try to control your breath, just observe it naturally.

4. <b>Thoughts will wander:</b> This is normal. When you notice your mind
wandering, gently bring your attention back to your breath.

5. <b>Continue for a few minutes:</b> Start with a few minutes and gradually
increase the duration as you become more comfortable.

6. <b>Notice how you feel:</b> After the meditation, take a moment to observe
how you feel. You might feel calmer and more focused.

Remember, practice makes perfect. The more you meditate, the easier it becomes to
manage stress and improve your well-being.

For longer or more detailed meditations, you can explore guided meditation apps or
online resources. eg: <a
href="https://www.headspace.com/meditation/techniques">HeadSpace</a>"""

36
techniques.py

techniques_list = """Feeling overwhelmed or stressed? Here are some self-care


techniques that can help you manage difficult emotions and improve your overall
well-being:

* <a
href="https://connect.mayoclinic.org/blog/living-with-mild-cognitive-impairment-mc
i/newsfeed-post/stress-relief-is-only-a-few-breaths-away/">Deep Breathing
Exercises</a> - Inhale deeply, hold, then exhale slowly to reduce stress and promote
relaxation.

* <a
href="https://www.webmd.com/sleep-disorders/muscle-relaxation-for-stress-insomnia
">Progressive Muscle Relaxation (PMR)</a> - Tense and relax muscle groups to
release tension and induce relaxation.

* <a
href="https://www.mindful.org/meditation/mindfulness-getting-started/">Mindfulnes
s Meditation</a> - Focus on the present moment without judgment to reduce stress
and increase awareness.

* <a
href="https://www.verywellmind.com/writing-in-a-gratitude-journal-for-stress-relief-
3144887">Gratitude Journaling</a> - Write down things you're thankful for to
cultivate positivity and shift focus away from negativity.

* <a
href="https://www.verywellmind.com/what-is-cognitive-behavior-therapy-2795747"
>Cognitive Behavioral Therapy (CBT)</a> - Challenge negative thoughts and
replace them with more balanced ones to improve mood.

* <a href="https://www.healthline.com/health/grounding-techniques">Grounding
Techniques</a> - Focus on sensory experiences to stay present and reduce anxiety or
dissociation.

* <a
href="https://self-compassion.org/self-compassion-practices/">Self-Compassion
Exercises</a> - Treat yourself with kindness and understanding to build resilience
and self-acceptance.

37
* <a
href="https://adaa.org/understanding-anxiety/obsessive-compulsive-disorder/social-s
upport-strategies">Social Support Strategies</a> - Seek connections with others for
emotional support and companionship.

* <a
href="https://www.betterhealth.vic.gov.au/health/healthyliving/exercise-and-mental-h
ealth">Physical Activity</a> - Engage in exercise to improve mood, reduce stress,
and enhance overall well-being.

* <a
href="https://www.verywellmind.com/forty-healthy-coping-skills-4586742">Healthy
Coping Skills</a> - Use positive strategies like hobbies and relaxation techniques to
manage stress effectively.

* <a href="https://www.healthline.com/health/sleep-hygiene">Sleep Hygiene


Tips</a> - Adopt habits that promote quality sleep, such as a consistent sleep
schedule and relaxing bedtime routine.

* <a
href="https://www.mayoclinic.org/healthy-lifestyle/stress-management/in-depth/relax
ation-technique/art-20045368">Relaxation Techniques</a> - Practice techniques like
visualization and deep breathing to calm the body and mind and reduce stress."""

articles.py

articles_list = """Here are some useful resources for mental health support

* The National Institute of Mental Health and Neuro Sciences<a


href="https://nimhans.ac.in/pssmhs-helpline/">(NIMHANS)</a> is a 24 * 7 toll-free
helpline for anyone experiencing mental health distress during the COVID 19 crisis.
They will provide psychological support and mental health services from mental
health professionals.

* The <a href="https://www.lifelinefoundation.in/">Lifeline Foundation</a> is a


government-registered non-profit organization located in Kolkata for over
twenty-four years. They provide free and anonymous emotional support to people
who are in despair, depressed or suicidal. The services are handled by meticulously
trained volunteers.

38
* National Alliance on Mental Illness <a
href="https://www.nami.org/">(NAMI)</a> - Provides information, education,
support, and advocacy for people with mental illness.

* The <a href="https://www.jedfoundation.org/">Jed Foundation</a> - Protects


emotional health and prevents suicide among teens and young adults.

* The Trevor Project - Provides crisis intervention and suicide prevention for
LGBTQ youth. Call their helpline at 1-866-488-7386 or visit The <a
href="https://www.thetrevorproject.org/">Trevor Project</a>

Articles on Mental health

* <a
href="https://www.thelancet.com/journals/lansea/article/PIIS2772-3682(23)00160-9/f
ulltext">Mental health in India: evolving strategies, initiatives, and prospects</a> -
The Lancet Regional Health - Southeast Asia

* <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5479084/">Mental health


awareness: The Indian scenario</a> - National Library of Medicine"""

39
REFERENCES

1. AI Applications in Mental Health Care (2020) -


https://www.sciencedirect.com/science/article/abs/pii/S245190222100046X

2. NLP Techniques for Sentiment Analysis in Mental Health (2019) -


https://www.sciencedirect.com/science/article/abs/pii/B9780128190432000034

3. Machine Learning Algorithms for Mood Detection and Emotional Analysis -


https://www.frontiersin.org/journals/psychology/articles/10.3389/fpsyg.2023.1
190326/full

4. Woebot - https://woebothealth.com/

5. Youper - https://www.youper.ai/

6. Wysa - https://www.wysa.com/

7. Flair Documentation - https://github.com/flairNLP/flair

8. Long Short-Term Memory Networks with Recurrent Neural Networks -


https://colah.github.io/posts/2015-08-Understanding-LSTMs/

9. A Primer on Neural Language Models -


https://hai.stanford.edu/news/how-trustworthy-are-large-language-models-gpt

LangChain Documentation -
https://python.langchain.com/docs/integrations/platforms/huggingface/

40

You might also like