Skip to content

Commit

Permalink
Merge pull request #19 from kamikazebr/dev
Browse files Browse the repository at this point in the history
discord bot
  • Loading branch information
kamikazebr authored Nov 2, 2023
2 parents f22fe35 + 2837042 commit 2bf16c8
Show file tree
Hide file tree
Showing 13 changed files with 783 additions and 1 deletion.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
.idea/
**/.idea/
packages/discord/
.github/workflows/.secrets
.github/workflows/.pull-request.json
19 changes: 19 additions & 0 deletions packages/discord/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
*.env
coverage/*
.pytest_cache
__pycache__
pdm.Dockerfile
poetry.Dockerfile
*.Dockerfile
Dockerfile

docker-compose*.yml
*docker-compose*.yml
docker-compose.yml

.pdm-python
.pdm-build
.venv
.python-version
vector_store
tasks/tasks.env
23 changes: 23 additions & 0 deletions packages/discord/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
__pycache__/
*.py[cod]
*.pyc
*$py.class

*.env
env/
.venv
venv/

.vscode/
.idea/

agent_data/

*.lock
!pdm.lock
vector_store/
report*.md
temp/
.pdm-python
.pdm-build
.python-version
34 changes: 34 additions & 0 deletions packages/discord/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
FROM python:3.10-slim-bullseye as prod

# Set environment variables
ENV ENV_FILE="docker" \
PYTHONFAULTHANDLER=1 \
PYTHONUNBUFFERED=1 \
PYTHONHASHSEED=random

# Install PDM
RUN pip install -U pip setuptools wheel && \
pip install pdm

# Set the working directory
WORKDIR /project

# Copy project files to the working directory
COPY . /project/

# Install dependencies and the project in the local directory
RUN mkdir __pypackages__ && pdm sync --prod --no-editable --fail-fast

# Set the PYTHONPATH environment variable
ENV PYTHONPATH=/project/pkgs

RUN mkdir -p /project/pkgs

# Move files and executables from the dependencies directory
RUN mv __pypackages__/3.10/lib/* /project/pkgs && \
mv __pypackages__/3.10/bin/* /bin/

WORKDIR /project

# Default command to be executed when the container starts
CMD ["python", "main.py"]
60 changes: 60 additions & 0 deletions packages/discord/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Makefile for running Docker Compose commands with conditional -f option

# Default Docker Compose file
COMPOSE_FILE = docker-compose.dev.yml

# Check if the 'prod' option is set
ifdef prod
COMPOSE_FILE = docker-compose.yml
endif

# Default service name
SERVICE = discord_bot_dev

# Check if the 'service' option is set
ifdef s
SERVICE = $(service)
endif

# Default target (when you run just "make" without specifying a target)
default: up

# Target to start the specified service using Docker Compose
up:
docker compose -f $(COMPOSE_FILE) up -d $(SERVICE)

# Target to view the logs of the specified service using Docker Compose
logs-full:
docker compose -f $(COMPOSE_FILE) logs $(SERVICE) -f

logs:
docker compose -f $(COMPOSE_FILE) logs $(SERVICE) -f -n 50 -t

# Target to stop and remove the specified service using Docker Compose
down:
docker compose -f $(COMPOSE_FILE) down $(SERVICE)

# Target to stop the specified service using Docker Compose (without removing it)
stop:
docker compose -f $(COMPOSE_FILE) stop $(SERVICE)

# Target to restart the specified service using Docker Compose
restart:
docker compose -f $(COMPOSE_FILE) restart $(SERVICE)

# Target to rebuild the specified service using Docker Compose
build:
docker compose -f $(COMPOSE_FILE) up -d --build $(SERVICE)

# Target to show help message (list available targets)
help:
@echo "Available targets:"
@echo " up - Start the specified service using Docker Compose"
@echo " logs - View the logs of the specified service using Docker Compose"
@echo " down - Stop and remove the specified service using Docker Compose"
@echo " stop - Stop the specified service using Docker Compose (without removing it)"
@echo " restart - Restart the specified service using Docker Compose"
@echo " build - Rebuild the specified service using Docker Compose"
@echo " help - Show this help message"

.PHONY: up logs down stop restart build help
33 changes: 33 additions & 0 deletions packages/discord/dev.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
FROM python:3.10-slim-bullseye AS local

# Set environment variables
ENV PYTHONFAULTHANDLER=1 \
PYTHONUNBUFFERED=1 \
PYTHONHASHSEED=random

# Install PDM
RUN pip install -U pip setuptools wheel && \
pip install pdm

# Set the working directory
WORKDIR /project

# copy files
COPY pyproject.toml pdm.lock /project/

# Install dependencies and the project in the local directory
RUN mkdir __pypackages__ && pdm sync --prod --no-editable --fail-fast

# Set the PYTHONPATH environment variable
ENV PYTHONPATH=/project/pkgs

RUN mkdir -p /project/pkgs

# Move files and executables from the dependencies directory
RUN mv __pypackages__/3.10/lib/* /project/pkgs && \
mv __pypackages__/3.10/bin/* /bin/

WORKDIR /project

# Default command to be executed when the container starts
CMD ["python", "main.py"]
11 changes: 11 additions & 0 deletions packages/discord/docker-compose.dev.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
version: "3"
services:
discord_bot_dev:
build:
context: .
dockerfile: dev.Dockerfile
env_file:
- .env
volumes:
- ./:/project/src
command: ["python","/project/src/main.py"]
7 changes: 7 additions & 0 deletions packages/discord/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
version: "3"
services:
discord_bot:
# image: ghcr.io/kamikazebr/qabot:main-vector_server
env_file:
- .env

Empty file.
12 changes: 12 additions & 0 deletions packages/discord/logs/discord_logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import logging

logging.basicConfig(level=logging.INFO)


def get_logger(name="DISCORD"):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
return logger


logger = get_logger()
105 changes: 105 additions & 0 deletions packages/discord/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import os
import time

import aiohttp
import discord
from discord.ext import commands
from discord import app_commands
from dotenv import load_dotenv

from logs.discord_logger import logger

load_dotenv()

intents = discord.Intents.default()
intents.members = True
intents.message_content = True

client = discord.Client(intents=intents)

bot = commands.Bot(
command_prefix='/',
intents=intents,
case_insensitive=True # Commands aren't case-sensitive
)

bot.author_id = os.environ.get("AUTHOR_ID")
assert bot.author_id, "AUTHOR_ID not set"


@bot.event
async def on_ready(): # When the bot is ready
logger.debug("I'm in")
logger.debug(bot.user) # Prints the bot's username and identifier
try:
synced = await bot.tree.sync()
logger.debug(f"Commands Synced {len(synced)}")
except Exception as e:
logger.debug(e)


def log_event(msg: str, queue_name: str, event_name: str):
logger.info(f"{queue_name}->{event_name}::{msg}")


class FinishAction(Exception):
pass


@bot.tree.command(name="ask")
@app_commands.describe(question="Ask anything to Hivemind")
async def ask(inter: discord.Interaction, question: str):
start_time = time.monotonic()
await inter.response.send_message("Searching...", ephemeral=True)

url = os.environ.get("HIVEMIND_URL", 'http://localhost:3333/ask')

if not url:
logger.error(f"Error on ask: Without URL")
await inter.edit_original_response(content='We have a problem, try again later')
return
initial_question = f"Your question: {question}\n"
logger.debug(initial_question)
last_message = None

try:
async with aiohttp.ClientSession() as session:
async with session.post(url, json={'question': question}) as response:
logger.debug(response)
start = time.time()
# response.raise_for_status()
async for chunk in response.content.iter_any():
answer = chunk.decode()
last_message = f"{initial_question}\n{answer}\n"
logger.debug(f"Answer: {round(time.time() - start, 1)}s after start: '{answer}'")
logger.debug(f"Msg sent: {last_message}")
await inter.edit_original_response(content=last_message)
# Write some code as if last_message start with 'Final Answer:'
if answer and answer.startswith('Final Answer:'):
raise FinishAction()

except FinishAction:
logger.info(f"FinishException")
pass
except Exception as e:
logger.error(f"Error on ask {e}")
last_message = 'We have a problem, try again later'
import traceback
traceback.print_exc()
finally:
if session:
await session.close()

elapsed_time = time.monotonic() - start_time
if elapsed_time > 60:
elapsed_time = elapsed_time / 60
time_unit = "minutes"
else:
time_unit = "seconds"

result_message = f"{last_message}\nAnswer took about {elapsed_time:.2f} {time_unit}!"

await inter.edit_original_response(content=result_message)

token = os.environ.get("DISCORD_BOT_SECRET")
bot.run(token) # Starts the bot
Loading

0 comments on commit 2bf16c8

Please sign in to comment.