diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4c49bd7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.env diff --git a/bot.py b/bot.py index 49303f9..7e5249d 100644 --- a/bot.py +++ b/bot.py @@ -5,15 +5,22 @@ from dotenv import load_dotenv import os import logging +from pymongo import MongoClient # Load environment variables from .env file load_dotenv() -# Retrieve the bot token and channel ID from the environment variables +# Retrieve the bot token, channel ID, and MongoDB URI from the environment variables DISCORD_TOKEN = os.getenv('DISCORD_TOKEN') CHANNELID = int(os.getenv('CHANNELID')) +MONGO_URI = os.getenv('MONGODB_URI') -# Load the JSON +# Connect to MongoDB +client = MongoClient(MONGO_URI) +db = client['FAQ-bot-Cluster'] # Assuming you want to use the same name as the cluster +collection = db['ChatBotCounts'] + +# Load the JSON (assuming it's located in the same directory) with open('menu_structure.json', 'r', encoding='utf-8') as file: menu_data = json.load(file) @@ -23,10 +30,10 @@ bot = commands.Bot(command_prefix="!", intents=intents) # Your target channel ID -TARGET_CHANNEL_ID = CHANNELID # Replace with your channel ID +TARGET_CHANNEL_ID = CHANNELID # Use the environment variable value class DynamicView(discord.ui.View): - def __init__(self, options, user=None, previous_selection=None,**disable): + def __init__(self, options, user=None, previous_selection=None, **disable): super().__init__(timeout=None) self.options = options self.user = user @@ -52,13 +59,17 @@ async def callback(interaction: discord.Interaction): return next_options = menu_data.get(option) + + # Update MongoDB for question count + self.log_question(option, interaction.user) + if isinstance(next_options, list): # Show the next set of options with numbers options_text = "\n".join([f"{i}. {opt}" for i, opt in enumerate(next_options, start=1)]) embed = discord.Embed(title=f"Select an option from:\n\n", description=options_text, color=discord.Color.blue()) if self.user is None: # Initial interaction, send DM to user await interaction.user.send(embed=embed, view=DynamicView(next_options, interaction.user)) - await interaction.response.send_message("Check your DMs for the next options.",ephemeral=True) + await interaction.response.send_message("Check your DMs for the next options.", ephemeral=True) else: # Continue interaction in DMs await interaction.response.send_message(embed=embed, view=DynamicView(next_options, interaction.user)) else: @@ -86,6 +97,22 @@ async def back_to_main_menu(self, interaction: discord.Interaction): logging.error(f"Error in back_to_main_menu: {e}") await interaction.response.send_message("An error occurred while processing your request.", ephemeral=True) + def log_question(self, question, user): + """Log the question and update counts in MongoDB.""" + try: + # Increment the overall bot usage count + collection.update_one({}, {'$inc': {'no_of_times_bot_used': 1}}, upsert=True) + + # Increment the question count + collection.update_one({}, {'$inc': {f'QuestionsAsked.{question}': 1}}, upsert=True) + + # Add user to unique users if not already present + if not collection.find_one({"unique_users": user.id}): + collection.update_one({}, {'$addToSet': {'unique_users': user.id}}, upsert=True) + collection.update_one({}, {'$inc': {'no_of_unique_users': 1}}, upsert=True) + except Exception as e: + logging.error(f"Error logging question: {e}") + @bot.event async def on_ready(): try: @@ -97,11 +124,10 @@ async def on_ready(): # Show initial options options_text = "\n".join([f"{i}. {opt}" for i, opt in enumerate(menu_data['menu'], start=1)]) embed = discord.Embed(title=f"Hey I'm happy to assist you...\nPlease choose an option below:\n\n", description=options_text, color=discord.Color.blue()) - await channel.send(embed=embed, view=DynamicView(menu_data['menu'],disable=True)) + await channel.send(embed=embed, view=DynamicView(menu_data['menu'], disable=True)) else: logging.info(f"Channel with ID {TARGET_CHANNEL_ID} not found") except Exception as e: logging.error(f"Error in on_ready: {e}") bot.run(DISCORD_TOKEN) - diff --git a/env-sample b/env-sample index b05d01b..c0aa4a9 100644 --- a/env-sample +++ b/env-sample @@ -1,3 +1,4 @@ DISCORD_TOKEN='' CHANNELID='' -APIURL='' // Example: 'http://127.0.0.1:8000/chatbot' \ No newline at end of file +APIURL='' +MONGODB_URI='' \ No newline at end of file