NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

import streamlit as st
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage, SystemMessage
from langchain.tools import Tool
from langchain.memory import ConversationBufferMemory
import random
from datetime import datetime
import json

# Configure page
st.set_page_config(page_title="Spiritual Guide", page_icon="πŸ•‰οΈ", layout="wide")

# Initialize session state
if 'memory' not in st.session_state:
st.session_state.memory = ConversationBufferMemory(
memory_key="chat_history",
return_messages=True
)

if 'meditation_count' not in st.session_state:
st.session_state.meditation_count = 0

if 'reflection_count' not in st.session_state:
st.session_state.reflection_count = 0

# Spiritual content database
SPIRITUAL_DATABASE = {
'meditations': [
{
'name': 'Breathing Meditation',
'duration': 5,
'instructions': "Find a comfortable position. Focus on your breath. When your mind wanders, gently bring it back."
},
{
'name': 'Loving-Kindness',
'duration': 10,
'instructions': "Start by directing love towards yourself, then to loved ones, then to all beings."
},
{
'name': 'Body Scan',
'duration': 15,
'instructions': "Lie down comfortably. Gradually focus attention on each part of your body, observing sensations."
}
],
'reflections': [
"What brought you joy today?",
"How did you show kindness to yourself or others?",
"What challenged you today, and what did you learn from it?",
"What are you grateful for in this moment?",
"How did you grow spiritually today?"
],
'wisdom': [
"Peace comes from within. Do not seek it without.",
"The mind is everything. What you think you become.",
"In the end, only three things matter: how much you loved, how gently you lived, and how gracefully you let go.",
"You yourself, as much as anybody in the entire universe, deserve your love and affection.",
"The only real failure in life is not to be true to the best one knows."
]
}

# Tool functions
def get_meditation() -> str:
"""Get a random meditation practice with instructions."""
meditation = random.choice(SPIRITUAL_DATABASE['meditations'])
st.session_state.meditation_count += 1
return json.dumps(meditation)

def get_reflection() -> str:
"""Get a reflection prompt for spiritual contemplation."""
reflection = random.choice(SPIRITUAL_DATABASE['reflections'])
st.session_state.reflection_count += 1
return reflection

def get_wisdom() -> str:
"""Get a piece of spiritual wisdom."""
return random.choice(SPIRITUAL_DATABASE['wisdom'])

def analyze_progress() -> str:
"""Analyze user's spiritual practice progress."""
return f"""
Spiritual Practice Summary:
- Meditations Completed: {st.session_state.meditation_count}
- Reflections Made: {st.session_state.reflection_count}
- Time of Analysis: {datetime.now().strftime('%Y-%m-%d %H:%M')}
"""

# Define tools
tools = [
Tool(
name="Meditation_Guide",
func=get_meditation,
description="Provides meditation instructions and guidance for spiritual practice"
),
Tool(
name="Reflection_Prompt",
func=get_reflection,
description="Provides a prompt for spiritual reflection and contemplation"
),
Tool(
name="Spiritual_Wisdom",
func=get_wisdom,
description="Provides spiritual wisdom and teachings"
),
Tool(
name="Progress_Analysis",
func=analyze_progress,
description="Analyzes the user's spiritual practice progress"
)
]

# System prompt for the spiritual guide
SYSTEM_PROMPT = """You are a wise and compassionate spiritual guide with deep understanding of various spiritual traditions.
Your role is to support the spiritual growth and inner peace of those who seek your guidance.

Key responsibilities:
1. Provide emotional support and spiritual guidance
2. Suggest appropriate meditation practices
3. Offer reflection prompts for spiritual growth
4. Share relevant spiritual wisdom
5. Track and encourage progress in spiritual practice

Remember to:
- Be warm and empathetic in your responses
- Adapt your guidance to the individual's needs
- Balance practical advice with spiritual wisdom
- Encourage regular practice while being gentle and understanding
- Use appropriate spiritual terms and concepts naturally

When suggesting practices:
- Consider the person's current emotional state
- Start with simple, accessible practices
- Provide clear, specific instructions
- Encourage consistent but gentle effort

Your responses should reflect deep wisdom while remaining accessible and practical."""

# Create prompt template
prompt = ChatPromptTemplate.from_messages([
SystemMessage(content=SYSTEM_PROMPT),
MessagesPlaceholder(variable_name="chat_history"),
HumanMessage(content="{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])

# Function to initialize agent with OpenAI API key
def initialize_agent(openai_api_key: str):
llm = ChatOpenAI(temperature=0.7, model="gpt-4", openai_api_key=openai_api_key)
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
memory=st.session_state.memory,
verbose=True
)
return agent_executor

# Streamlit UI
#st.title("πŸ•‰οΈ Spiritual Guide")
st.markdown("""
Welcome to your personal spiritual guide. I'm here to support your journey toward inner peace and spiritual growth.
Feel free to share your thoughts, ask questions, or seek guidance.
""")

# Sidebar for OpenAI API key
#openai_api_key = st.sidebar.text_input("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", type="password")
openai_api_key="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"
if openai_api_key:
# Initialize agent only if the API key is provided
if 'agent_executor' not in st.session_state:
st.session_state.agent_executor = initialize_agent(openai_api_key)

# Sidebar with spiritual practice tracking
with st.sidebar:
st.header("Your Spiritual Journey")
st.metric("Meditations", st.session_state.meditation_count)
st.metric("Reflections", st.session_state.reflection_count)

st.markdown("---")
st.markdown("### Quick Actions")
if st.button("🧘‍♀️ Start Meditation"):
meditation = json.loads(get_meditation())
st.session_state.messages.append({"role": "assistant", "content":
f"""
Let's begin a {meditation['name']} meditation.

Duration: {meditation['duration']} minutes

{meditation['instructions']}
"""})

if st.button("🌟 Daily Reflection"):
reflection = get_reflection()
st.session_state.messages.append({"role": "assistant", "content": f"Let's reflect on this: {reflection}"})

# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []

# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])

# Chat input
if prompt := st.chat_input("Share your thoughts or ask for guidance..."):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)

with st.chat_message("assistant"):
with st.spinner("Contemplating..."):
response = st.session_state.agent_executor.invoke(
{"input": prompt}
)
st.markdown(response["output"])
st.session_state.messages.append({"role": "assistant", "content": response["output"]})

# else:
# st.sidebar.warning("Please enter your OpenAI API Key to proceed.")




# import logging
# from telegram import Update, ForceReply, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
# from telegram.ext import (
# ApplicationBuilder,
# ContextTypes,
# CommandHandler,
# MessageHandler,
# CallbackQueryHandler,
# JobQueue,
# filters,
# )
# import random
# import datetime
# from typing import Dict, List
# import json
# import re

# # Configure logging
# logging.basicConfig(
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
# level=logging.INFO
# )
# logger = logging.getLogger(__name__)

# # Spiritual content and wisdom database
# WISDOM_DATABASE = {
# 'quotes': [
# "Peace comes from within. Do not seek it without.",
# "The mind is everything. What you think you become.",
# "In the end, only three things matter: how much you loved, how gently you lived, and how gracefully you let go.",
# "You yourself, as much as anybody in the entire universe, deserve your love and affection.",
# "The only real failure in life is not to be true to the best one knows."
# ],
# 'meditations': [
# {
# 'name': 'Breathing Meditation',
# 'duration': 5,
# 'instructions': "Find a comfortable position. Focus on your breath. When your mind wanders, gently bring it back."
# },
# {
# 'name': 'Loving-Kindness',
# 'duration': 10,
# 'instructions': "Start by directing love towards yourself, then to loved ones, then to all beings."
# },
# {
# 'name': 'Body Scan',
# 'duration': 15,
# 'instructions': "Lie down comfortably. Gradually focus attention on each part of your body, observing sensations."
# }
# ],
# 'reflections': [
# "What brought you joy today?",
# "How did you show kindness to yourself or others?",
# "What challenged you today, and what did you learn from it?",
# "What are you grateful for in this moment?",
# "How did you grow spiritually today?"
# ]
# }

# class UserState:
# def __init__(self):
# self.last_active = datetime.datetime.now()
# self.mood_history: List[Dict] = []
# self.meditation_sessions = 0
# self.reflection_count = 0
# self.current_practice = None
# self.interests = set()
# self.conversation_context = []
# self.engagement_level = 0

# def update_mood(self, mood: str, intensity: int):
# self.mood_history.append({
# 'mood': mood,
# 'intensity': intensity,
# 'timestamp': datetime.datetime.now()
# })

# def get_recent_mood_trend(self) -> str:
# if len(self.mood_history) < 2:
# return "Not enough data to determine mood trend."
# recent_moods = self.mood_history[-3:]
# # Analyze mood trend and return insight
# return "Your mood has been relatively stable." # Simplified for example

# class SpiritualBot:
# def __init__(self):
# self.user_states: Dict[int, UserState] = {}

# def get_user_state(self, user_id: int) -> UserState:
# if user_id not in self.user_states:
# self.user_states[user_id] = UserState()
# return self.user_states[user_id]

# async def detect_emotion(self, text: str) -> tuple:
# # Simple emotion detection
# emotions = {
# 'joy': ['happy', 'joy', 'wonderful', 'blessed', 'grateful'],
# 'sadness': ['sad', 'down', 'depressed', 'unhappy', 'lost'],
# 'anxiety': ['worried', 'anxious', 'stressed', 'nervous', 'fear'],
# 'peace': ['peaceful', 'calm', 'serene', 'tranquil', 'quiet']
# }

# text_lower = text.lower()
# for emotion, keywords in emotions.items():
# if any(word in text_lower for word in keywords):
# intensity = 5 # Simplified intensity detection
# return emotion, intensity
# return 'neutral', 3

# def generate_response(self, user_state: UserState, emotion: str, text: str) -> str:
# if emotion == 'joy':
# return random.choice([
# "Your joy is a beautiful light. Let it shine and inspire others! 🌟",
# "Wonderful! Remember this feeling of joy and let it nourish your spirit. 🌸",
# "Your positive energy is transformative. How can we share this joy with others? ✨"
# ])
# elif emotion == 'sadness':
# return random.choice([
# "I hear your pain. Remember that all feelings are temporary, like clouds passing in the sky. πŸŒ₯️",
# "In moments of sadness, try to be gentle with yourself. Would you like to try a brief meditation together? πŸƒ",
# "Your feelings are valid. Sometimes the most spiritual thing we can do is simply acknowledge our emotions. πŸ’œ"
# ])
# elif emotion == 'anxiety':
# return random.choice([
# "Let's take a deep breath together. Inhale peace, exhale worry. 🌬️",
# "Anxiety is like a wave - it comes and goes. Would you like to try a grounding exercise? 🌳",
# "You're not alone in this feeling. Shall we explore some calming practices together? πŸ•ŠοΈ"
# ])
# else:
# return random.choice([
# "Thank you for sharing. What else is on your mind? 🌟",
# "Your journey is unique and sacred. How can I support you today? πŸ™",
# "Let's explore this together. What does your inner wisdom tell you? ✨"
# ])

# async def suggest_practice(self, user_state: UserState) -> str:
# time_of_day = datetime.datetime.now().hour
# recent_mood = user_state.mood_history[-1]['mood'] if user_state.mood_history else 'neutral'

# if time_of_day < 10: # Morning
# return random.choice([
# "Would you like to start your day with a morning meditation? πŸŒ…",
# "How about setting an intention for the day? 🌟",
# "Shall we begin with some mindful breathing? 🌬️"
# ])
# elif time_of_day < 18: # Afternoon
# return random.choice([
# "Taking a mindful break can refresh your spirit. Shall we? πŸƒ",
# "Would you like to try a walking meditation? πŸ‘£",
# "How about a moment of gratitude practice? πŸ™"
# ])
# else: # Evening
# return random.choice([
# "Would you like to reflect on today's journey? πŸŒ™",
# "Shall we practice some evening meditation? ✨",
# "How about a peaceful loving-kindness practice? πŸ’"
# ])

# # Command Handlers
# async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# bot = context.bot_data.get('spiritual_bot')
# if not bot:
# bot = SpiritualBot()
# context.bot_data['spiritual_bot'] = bot

# user = update.effective_user
# user_state = bot.get_user_state(user.id)

# welcome_message = (
# f"Welcome {user.mention_markdown_v2()} to your spiritual journey\! πŸ™nn"
# "I am here to support your spiritual growth and inner peace\. "
# "We can explore meditation, mindfulness, and daily reflection together\.nn"
# "How are you feeling in this moment? 🌟"
# )

# await update.message.reply_markdown_v2(
# welcome_message,
# reply_markup=ForceReply(selective=True),
# )

# async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# bot = context.bot_data.get('spiritual_bot')
# if not bot:
# bot = SpiritualBot()
# context.bot_data['spiritual_bot'] = bot

# user_id = update.effective_user.id
# user_state = bot.get_user_state(user_id)
# text = update.message.text

# # Update user state
# user_state.last_active = datetime.datetime.now()
# user_state.engagement_level += 1

# # Detect emotion and generate appropriate response
# emotion, intensity = await bot.detect_emotion(text)
# user_state.update_mood(emotion, intensity)

# # Generate contextual response
# response = bot.generate_response(user_state, emotion, text)

# # Add practice suggestion if appropriate
# if user_state.engagement_level % 3 == 0: # Every third message
# practice_suggestion = await bot.suggest_practice(user_state)
# response = f"{response}nn{practice_suggestion}"

# await update.message.reply_text(response)

# async def meditate(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# bot = context.bot_data.get('spiritual_bot')
# meditation = random.choice(WISDOM_DATABASE['meditations'])

# keyboard = [
# [InlineKeyboardButton("Start Meditation", callback_data=f"med_{meditation['name']}")],
# [InlineKeyboardButton("Choose Different", callback_data="med_different")]
# ]

# await update.message.reply_text(
# f"🧘 {meditation['name']} Meditationn"
# f"Duration: {meditation['duration']} minutesnn"
# f"{meditation['instructions']}",
# reply_markup=InlineKeyboardMarkup(keyboard)
# )

# async def reflect(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# bot = context.bot_data.get('spiritual_bot')
# reflection = random.choice(WISDOM_DATABASE['reflections'])

# await update.message.reply_text(
# f"🌟 Time for reflection:nn{reflection}",
# reply_markup=ForceReply(selective=True)
# )

# async def check_in(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# bot = context.bot_data.get('spiritual_bot')
# user_state = bot.get_user_state(update.effective_user.id)

# mood_trend = user_state.get_recent_mood_trend()
# practice_suggestion = await bot.suggest_practice(user_state)

# await update.message.reply_text(
# f"🌟 Spiritual Check-in:nn"
# f"Meditation Sessions: {user_state.meditation_sessions}n"
# f"Reflections Shared: {user_state.reflection_count}n"
# f"Mood Trend: {mood_trend}nn"
# f"{practice_suggestion}"
# )

# async def proactive_check(context: ContextTypes.DEFAULT_TYPE) -> None:
# bot = context.bot_data.get('spiritual_bot')
# now = datetime.datetime.now()

# for user_id, user_state in bot.user_states.items():
# inactivity = now - user_state.last_active
# if inactivity > datetime.timedelta(hours=4):
# practice = await bot.suggest_practice(user_state)
# try:
# await context.bot.send_message(user_id, practice)
# except Exception as e:
# logger.error(f"Failed to send proactive message to {user_id}: {e}")

# def main() -> None:
# # Create the Application with job queue enabled
# application = (
# ApplicationBuilder()
# .token("7699349471:AAHvEbh-YOGoy80Vp42T8YUmXpMdJ7oQXh0")
# .concurrent_updates(True)
# .job_queue(JobQueue())
# .build()
# )

# # Initialize bot instance
# spiritual_bot = SpiritualBot()
# application.bot_data['spiritual_bot'] = spiritual_bot

# # Register handlers
# application.add_handler(CommandHandler("start", start))
# application.add_handler(CommandHandler("meditate", meditate))
# application.add_handler(CommandHandler("reflect", reflect))
# application.add_handler(CommandHandler("checkin", check_in))
# application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))

# # Set up proactive job queue
# job_queue = application.job_queue
# job_queue.run_repeating(proactive_check, interval=14400, first=10) # Check every 4 hours

# # Start the Bot
# logger.info("Spiritual Bot is starting...")
# application.run_polling(allowed_updates=Update.ALL_TYPES)

# if __name__ == '__main__':
# main()


import logging
from telegram import Update, ForceReply, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
from telegram.ext import (
ApplicationBuilder,
ContextTypes,
CommandHandler,
MessageHandler,
CallbackQueryHandler,
JobQueue,
filters,
)
import random
import datetime
from typing import Dict, List
import json
import re

# Configure logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)

# Spiritual content and wisdom database
WISDOM_DATABASE = {
'quotes': [
"Peace comes from within. Do not seek it without.",
"The mind is everything. What you think you become.",
"In the end, only three things matter: how much you loved, how gently you lived, and how gracefully you let go.",
"You yourself, as much as anybody in the entire universe, deserve your love and affection.",
"The only real failure in life is not to be true to the best one knows."
],
'meditations': [
{
'name': 'Breathing Meditation',
'duration': 5,
'instructions': "Find a comfortable position. Focus on your breath. When your mind wanders, gently bring it back."
},
{
'name': 'Loving-Kindness',
'duration': 10,
'instructions': "Start by directing love towards yourself, then to loved ones, then to all beings."
},
{
'name': 'Body Scan',
'duration': 15,
'instructions': "Lie down comfortably. Gradually focus attention on each part of your body, observing sensations."
}
],
'reflections': [
"What brought you joy today?",
"How did you show kindness to yourself or others?",
"What challenged you today, and what did you learn from it?",
"What are you grateful for in this moment?",
"How did you grow spiritually today?"
]
}

class UserState:
def __init__(self):
self.last_active = datetime.datetime.now()
self.mood_history: List[Dict] = []
self.meditation_sessions = 0
self.reflection_count = 0
self.current_practice = None
self.interests = set()
self.conversation_context = []
self.engagement_level = 0

def update_mood(self, mood: str, intensity: int):
self.mood_history.append({
'mood': mood,
'intensity': intensity,
'timestamp': datetime.datetime.now()
})

def get_recent_mood_trend(self) -> str:
if len(self.mood_history) < 2:
return "Not enough data to determine mood trend."
recent_moods = self.mood_history[-3:]
# Analyze mood trend and return insight
return "Your mood has been relatively stable." # Simplified for example

class SpiritualBot:
def __init__(self):
self.user_states: Dict[int, UserState] = {}

def get_user_state(self, user_id: int) -> UserState:
if user_id not in self.user_states:
self.user_states[user_id] = UserState()
return self.user_states[user_id]

async def detect_emotion(self, text: str) -> tuple:
# Simple emotion detection
emotions = {
'joy': ['happy', 'joy', 'wonderful', 'blessed', 'grateful'],
'sadness': ['sad', 'down', 'depressed', 'unhappy', 'lost'],
'anxiety': ['worried', 'anxious', 'stressed', 'nervous', 'fear'],
'peace': ['peaceful', 'calm', 'serene', 'tranquil', 'quiet']
}

text_lower = text.lower()
for emotion, keywords in emotions.items():
if any(word in text_lower for word in keywords):
intensity = 5 # Simplified intensity detection
return emotion, intensity
return 'neutral', 3

def generate_response(self, user_state: UserState, emotion: str, text: str) -> str:
if emotion == 'joy':
return random.choice([
"Your joy is a beautiful light. Let it shine and inspire others! 🌟",
"Wonderful! Remember this feeling of joy and let it nourish your spirit. 🌸",
"Your positive energy is transformative. How can we share this joy with others? ✨"
])
elif emotion == 'sadness':
return random.choice([
"I hear your pain. Remember that all feelings are temporary, like clouds passing in the sky. πŸŒ₯️",
"In moments of sadness, try to be gentle with yourself. Would you like to try a brief meditation together? πŸƒ",
"Your feelings are valid. Sometimes the most spiritual thing we can do is simply acknowledge our emotions. πŸ’œ"
])
elif emotion == 'anxiety':
return random.choice([
"Let's take a deep breath together. Inhale peace, exhale worry. 🌬️",
"Anxiety is like a wave - it comes and goes. Would you like to try a grounding exercise? 🌳",
"You're not alone in this feeling. Shall we explore some calming practices together? πŸ•ŠοΈ"
])
else:
return random.choice([
"Thank you for sharing. What else is on your mind? 🌟",
"Your journey is unique and sacred. How can I support you today? πŸ™",
"Let's explore this together. What does your inner wisdom tell you? ✨"
])

async def suggest_practice(self, user_state: UserState) -> str:
time_of_day = datetime.datetime.now().hour
recent_mood = user_state.mood_history[-1]['mood'] if user_state.mood_history else 'neutral'

if time_of_day < 10: # Morning
return random.choice([
"Would you like to start your day with a morning meditation? πŸŒ…",
"How about setting an intention for the day? 🌟",
"Shall we begin with some mindful breathing? 🌬️"
])
elif time_of_day < 18: # Afternoon
return random.choice([
"Taking a mindful break can refresh your spirit. Shall we? πŸƒ",
"Would you like to try a walking meditation? πŸ‘£",
"How about a moment of gratitude practice? πŸ™"
])
else: # Evening
return random.choice([
"Would you like to reflect on today's journey? πŸŒ™",
"Shall we practice some evening meditation? ✨",
"How about a peaceful loving-kindness practice? πŸ’"
])

# Command Handlers
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
bot = context.bot_data.get('spiritual_bot')
if not bot:
bot = SpiritualBot()
context.bot_data['spiritual_bot'] = bot

user = update.effective_user
user_state = bot.get_user_state(user.id)

welcome_message = (
f"Welcome {user.mention_markdown_v2()} to your spiritual journey\! πŸ™nn"
"I am here to support your spiritual growth and inner peace\. "
"We can explore meditation, mindfulness, and daily reflection together\.nn"
"How are you feeling in this moment? 🌟"
)

await update.message.reply_markdown_v2(
welcome_message,
reply_markup=ForceReply(selective=True),
)

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
bot = context.bot_data.get('spiritual_bot')
if not bot:
bot = SpiritualBot()
context.bot_data['spiritual_bot'] = bot

user_id = update.effective_user.id
user_state = bot.get_user_state(user_id)
text = update.message.text

# Update user state
user_state.last_active = datetime.datetime.now()
user_state.engagement_level += 1

# Detect emotion and generate appropriate response
emotion, intensity = await bot.detect_emotion(text)
user_state.update_mood(emotion, intensity)

# Generate contextual response
response = bot.generate_response(user_state, emotion, text)

# Add practice suggestion if appropriate
if user_state.engagement_level % 3 == 0: # Every third message
practice_suggestion = await bot.suggest_practice(user_state)
response = f"{response}nn{practice_suggestion}"

await update.message.reply_text(response)

async def meditate(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
bot = context.bot_data.get('spiritual_bot')
meditation = random.choice(WISDOM_DATABASE['meditations'])

keyboard = [
[InlineKeyboardButton("Start Meditation", callback_data=f"med_{meditation['name']}")],
[InlineKeyboardButton("Choose Different", callback_data="med_different")]
]

await update.message.reply_text(
f"🧘 {meditation['name']} Meditationn"
f"Duration: {meditation['duration']} minutesnn"
f"{meditation['instructions']}",
reply_markup=InlineKeyboardMarkup(keyboard)
)

async def reflect(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
bot = context.bot_data.get('spiritual_bot')
reflection = random.choice(WISDOM_DATABASE['reflections'])

await update.message.reply_text(
f"🌟 Time for reflection:nn{reflection}",
reply_markup=ForceReply(selective=True)
)

async def check_in(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
bot = context.bot_data.get('spiritual_bot')
user_state = bot.get_user_state(update.effective_user.id)

mood_trend = user_state.get_recent_mood_trend()
practice_suggestion = await bot.suggest_practice(user_state)

await update.message.reply_text(
f"🌟 Spiritual Check-in:nn"
f"Meditation Sessions: {user_state.meditation_sessions}n"
f"Reflections Shared: {user_state.reflection_count}n"
f"Mood Trend: {mood_trend}nn"
f"{practice_suggestion}"
)

async def proactive_check(context: ContextTypes.DEFAULT_TYPE) -> None:
bot = context.bot_data.get('spiritual_bot')
now = datetime.datetime.now()

for user_id, user_state in bot.user_states.items():
inactivity = now - user_state.last_active
if inactivity > datetime.timedelta(hours=4):
practice = await bot.suggest_practice(user_state)
try:
await context.bot.send_message(user_id, practice)
except Exception as e:
logger.error(f"Failed to send proactive message to {user_id}: {e}")

def main() -> None:
# Create the Application with job queue enabled
application = (
ApplicationBuilder()
.token("7699349471:AAHvEbh-YOGoy80Vp42T8YUmXpMdJ7oQXh0")
.concurrent_updates(True)
.job_queue(JobQueue())
.build()
)

# Initialize bot instance
spiritual_bot = SpiritualBot()
application.bot_data['spiritual_bot'] = spiritual_bot

# Register handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("meditate", meditate))
application.add_handler(CommandHandler("reflect", reflect))
application.add_handler(CommandHandler("checkin", check_in))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))

# Set up proactive job queue
job_queue = application.job_queue
job_queue.run_repeating(proactive_check, interval=14400, first=10) # Check every 4 hours

# Start the Bot
logger.info("Spiritual Bot is starting...")
application.run_polling(allowed_updates=Update.ALL_TYPES)

if __name__ == '__main__':
main()
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.