Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added counter logics to upload counts to DB #3

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.env
40 changes: 33 additions & 7 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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)

3 changes: 2 additions & 1 deletion env-sample
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
DISCORD_TOKEN=''
CHANNELID=''
APIURL='' // Example: 'http://127.0.0.1:8000/chatbot'
APIURL=''
MONGODB_URI=''