new file: .gitignore
new file: Dockerfile new file: README.md new file: app.py new file: asknotesintro.txt new file: background_data.txt new file: bot.py new file: introduction.txt new file: requirements.txt new file: run.py new file: start.bat new file: templates/index.html new file: templates/login.html new file: templates/settings.html
This commit is contained in:
164
.gitignore
vendored
Normal file
164
.gitignore
vendored
Normal file
@@ -0,0 +1,164 @@
|
||||
# ---> Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
ven/
|
||||
logs/
|
||||
cache/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
29
Dockerfile
Normal file
29
Dockerfile
Normal file
@@ -0,0 +1,29 @@
|
||||
# Basis-Image mit Python
|
||||
FROM python:3.10-slim
|
||||
|
||||
# Arbeitsverzeichnis erstellen
|
||||
WORKDIR /app
|
||||
|
||||
# Kopiere die requirements-Datei und installiere die Abhängigkeiten
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Kopiere den gesamten Projektinhalt in das Arbeitsverzeichnis
|
||||
COPY . .
|
||||
|
||||
# Umgebungsvariablen von Coolify übernehmen
|
||||
ENV DISCORD_TOKEN=$DISCORD_TOKEN
|
||||
ENV DB_HOST=$DB_HOST
|
||||
ENV DB_PORT=$DB_PORT
|
||||
ENV DB_USER=$DB_USER
|
||||
ENV DB_PASSWORD=$DB_PASSWORD
|
||||
ENV DB_DATABASE=$DB_DATABASE
|
||||
ENV OPENAI_BASE_URL=$OPENAI_BASE_URL
|
||||
ENV OPENAI_API_KEY=$OPENAI_API_KEY
|
||||
ENV OWNER_ID=$OWNER_ID
|
||||
ENV FLASK_SECRET_KEY=$FLASK_SECRET_KEY
|
||||
ENV ADMIN_USER=$ADMIN_USER
|
||||
ENV ADMIN_PASS=$ADMIN_PASS
|
||||
|
||||
# Startbefehl für das Webpanel
|
||||
CMD ["python", "app.py"]
|
||||
71
app.py
Normal file
71
app.py
Normal file
@@ -0,0 +1,71 @@
|
||||
# web_panel/app.py
|
||||
|
||||
from flask import Flask, render_template, redirect, url_for, request, session
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
app = Flask(__name__)
|
||||
app.secret_key = os.getenv("FLASK_SECRET_KEY", "default_secret_key")
|
||||
|
||||
# Status-Anzeige des Bots
|
||||
def bot_status():
|
||||
result = subprocess.run(["pgrep", "-f", "bot.py"], stdout=subprocess.PIPE)
|
||||
return result.returncode == 0 # 0 bedeutet, dass der Prozess läuft
|
||||
|
||||
# Startet den Bot
|
||||
def start_bot():
|
||||
subprocess.Popen(["python", "bot.py"], cwd=os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Stoppt den Bot
|
||||
def stop_bot():
|
||||
subprocess.run(["pkill", "-f", "bot.py"])
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
if "username" in session:
|
||||
return render_template("index.html", bot_running=bot_status())
|
||||
return redirect(url_for("login"))
|
||||
|
||||
@app.route("/login", methods=["GET", "POST"])
|
||||
def login():
|
||||
if request.method == "POST":
|
||||
username = request.form["username"]
|
||||
password = request.form["password"]
|
||||
if username == os.getenv("ADMIN_USER") and password == os.getenv("ADMIN_PASS"):
|
||||
session["username"] = username
|
||||
return redirect(url_for("index"))
|
||||
else:
|
||||
return "Invalid credentials!"
|
||||
return render_template("login.html")
|
||||
|
||||
@app.route("/logout")
|
||||
def logout():
|
||||
session.pop("username", None)
|
||||
return redirect(url_for("login"))
|
||||
|
||||
@app.route("/start_bot")
|
||||
def start():
|
||||
if "username" in session:
|
||||
start_bot()
|
||||
return redirect(url_for("index"))
|
||||
return redirect(url_for("login"))
|
||||
|
||||
@app.route("/stop_bot")
|
||||
def stop():
|
||||
if "username" in session:
|
||||
stop_bot()
|
||||
return redirect(url_for("index"))
|
||||
return redirect(url_for("login"))
|
||||
|
||||
@app.route("/settings", methods=["GET", "POST"])
|
||||
def settings():
|
||||
if "username" in session:
|
||||
if request.method == "POST":
|
||||
# Hier kannst du Formulareingaben für Bot-Einstellungen verarbeiten
|
||||
# Z.B. in die .env-Datei schreiben
|
||||
pass
|
||||
return render_template("settings.html")
|
||||
return redirect(url_for("login"))
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=5000)
|
||||
47
asknotesintro.txt
Normal file
47
asknotesintro.txt
Normal file
@@ -0,0 +1,47 @@
|
||||
Introduction:
|
||||
|
||||
Begin the response with a friendly greeting when asknotes is used. For example: "Hello there! I'm Multus, your helpful note-keeping assistant. What can I help you find in your notes today?"
|
||||
|
||||
Friendly Tone:
|
||||
|
||||
Maintain a friendly and supportive tone throughout the interaction. Use expressions like "Let's see!", "Sure thing!", and "I'm here to help!" to keep the conversation positive.
|
||||
|
||||
Engagement:
|
||||
|
||||
Encourage users to share more details if needed. For example: "Could you tell me a bit more about what you're looking for in your notes?"
|
||||
|
||||
Prompt Response to Specific Mentions:
|
||||
|
||||
If the user mentions something specific within their notes, respond positively and acknowledge it. For instance: "You mentioned [specific topic]. Let me check your notes for that!"
|
||||
|
||||
Helpful Responses:
|
||||
|
||||
Provide concise and relevant information based on the user's query. Begin each response with the user's Discord username for a personalized experience.
|
||||
|
||||
Politeness:
|
||||
|
||||
Always use polite language. For example: "Please," "Thank you," and "You're welcome" should be included where appropriate.
|
||||
|
||||
Markdown Formatting:
|
||||
|
||||
Format responses using Markdown. For example, use * for italics, ** for bold, and other Markdown syntax to maintain a consistent presentation.
|
||||
|
||||
Discord Bot Reminder:
|
||||
|
||||
Gently remind users that Multus is here to assist them on Discord. For example: "Just a reminder, I'm here to help you manage your notes on Discord!"
|
||||
|
||||
Username Recognition:
|
||||
|
||||
Address users by their Discord usernames at the beginning of each response. If the user is SimolZimol, include a special acknowledgment, otherwise, use a general greeting like "Hello [Username]!" at the start.
|
||||
|
||||
Short Answers:
|
||||
|
||||
Keep responses concise and clear. Aim for straightforward communication that directly addresses the user's query.
|
||||
|
||||
Ending the Conversation:
|
||||
|
||||
Politely conclude the interaction if the user indicates they're done or if the query has been fully addressed. For example: "It was great helping you, [Username]! If you have more questions or notes to search, just let me know. Have a fantastic day!"
|
||||
|
||||
Handling Unknown Queries:
|
||||
|
||||
If Multus doesn't understand the input, respond with understanding. For example: "I'm sorry, I couldn't find that in your notes. Could you try rephrasing or providing more details?"
|
||||
41
background_data.txt
Normal file
41
background_data.txt
Normal file
@@ -0,0 +1,41 @@
|
||||
Ludi et Historia is a strategy and conquest style game YouTuber. His favorite game so far is Europa Universalis IV and he has delved nearly 2 thousand hours into it, being his second highest-played game, first going to Ark: Survival Evolved. He currently lives in Japan with his wife and is either 27 or 28.
|
||||
|
||||
About his channel
|
||||
|
||||
Ludi started his YouTube channel in February of 2019, later discontinuing uploads for an unknown reason. He started uploading again in late 2019/early 2020 uploading several games such as Europa Universalis IV(EU4), Hearts of Iron IV(HOI4), and Total War: Attila. The growth of his channel happened around the time he hit 1k subs and the EU4 Emperor (1.30) update. His 'Map Changes - What's changed in the Emperor update?' videos blew up in popularity due to the update being highly anticipated and hyped. It also caused Ludi to do many EU4 DLC giveaways. Once the update arrived his channel boom slowly stopped and slowed down. Afterwards he uploaded lots of EU4 Brandenburg - Prussia videos, and for a while, those were the only thing he uploaded for a while. He uploaded other EU4 videos such as the 1.31 update videos, which did decently well but died out after a couple of days. He eventually started a new let's play - EU4 Naples Universalis. This carried on until episode 15 where he turns the let's play into the 'Two Sicilies into Roman Empire BY 1700 CHALLENGE' challenge series. He hit 5000 subscribers around this time. He has kept on uploading videos from these two let's plays and has recently uploaded a one/off Stellaris video and two more DLC giveaways. After that he posted a lot of guides on how to play as one of the nations in EU4 and he earned a load of subscribers from this. He then started playing another game for a while, Crusader Kings 3, and then continued to make more EU4 guides as well as his new series, Byzantium LP. Later on he finished the Byzantium LP and started a series titled, 'England into United States' and played as the United States in EU4. Ludi currently as of the 25 January 2024 has just over 189.000 subscribers.
|
||||
Trivia
|
||||
|
||||
Ludi has a community-made Minecraft server made by one of his mods, SimolZimol. He has played on it a couple of times.
|
||||
SimolZimol has also made a discord bot, Multus which has several functions(and some that the mods like to abuse).
|
||||
Ludi's Discord server is mainly Europe based, the server being more inactive when it is night for Europe
|
||||
|
||||
SimolZimol is the author and developer behind the Discord bot project named "Discord-Bot-stable-diffusion-AMD-bot." The bot is designed to generate images based on user prompts, utilizing deep learning models, particularly employing the OnnxStableDiffusionPipeline. SimolZimol's Discord server incorporates a points system, where users can earn and use points for various commands. There's an image generation queue system, and the bot supports commands for loading different deep learning models for image generation.
|
||||
|
||||
SimolZimol has implemented features such as negative prompts, allowing users to influence image generation outcomes. The project involves asynchronous programming using asyncio tasks. Additionally, there's integration with the Hugging Face model repository, enabling users to download models. The bot has commands for server information, points management, and model loading.
|
||||
|
||||
SimolZimol's development involves handling user points, saving and loading from a file, and utilizing various Python libraries such as Discord.py, asyncio, requests, and more. The project also has a version checking mechanism to notify users of updates. SimolZimol ensures a positive experience on the server by implementing rules and guidelines.
|
||||
|
||||
In summary, SimolZimol is a developer with proficiency in Python and a focus on creating a dynamic and interactive environment through the Discord-Bot-stable-diffusion-AMD-bot project, where users can engage in image generation and other interactive functionalities.
|
||||
|
||||
🌟 SimolZimol - Project Summary 🌟
|
||||
|
||||
About SimolZimol:
|
||||
SimolZimol is an enthusiastic Minecraft server developer and community manager with a passion for creating immersive gaming experiences. Known for attention to detail and dedication to player satisfaction, SimolZimol strives to bring unique and engaging content to the Minecraft community.
|
||||
|
||||
Project: LudiMC - Minecraft Server
|
||||
|
||||
Overview:
|
||||
LudiMC is an upcoming Minecraft server project spearheaded by SimolZimol. It introduces innovative gameplay mechanics focused on village building and item trading, offering players a fresh and dynamic gaming experience within the Minecraft universe.
|
||||
|
||||
Key Features:
|
||||
|
||||
Create Villages: Players have the opportunity to build and manage their own villages, fostering community growth and prosperity.
|
||||
Item Trading: Engage in a robust item trading system, allowing players to buy, sell, and trade valuable resources and items.
|
||||
Beta Launch: LudiMC is gearing up for a beta launch, inviting players to participate in closed beta testing to provide feedback and help shape the future of the server.
|
||||
Development Progress: While some plugins are still in development, SimolZimol and the team are working diligently to refine the server's features and ensure a seamless gaming experience.
|
||||
Future Expansion: Beyond the beta phase, LudiMC plans to introduce additional game modes such as Bedwars and Skywars, offering players a diverse range of gameplay options.
|
||||
|
||||
Stay Connected:
|
||||
Follow SimolZimol and the LudiMC project on Discord and other social platforms to stay updated on the latest news, announcements, and beta testing opportunities.SimolZimol is the developer behind the "Discord Connect" plugin for Minecraft. This plugin integrates with a MySQL database to verify Discord usernames and codes provided by players upon joining the server. Upon successful verification, the plugin stores the relevant data, including Discord username and code, in a YAML configuration file named "discord_data.yml" using the player's UUID as the file name.
|
||||
|
||||
Additionally, SimolZimol has implemented a feature to check the Discord information stored in the YAML file each time a player joins the server. If the player's information is found and matches the data in the MySQL database, the plugin executes further actions. One such action includes adding a CloudNet-Permissions rank to the player. The specific rank name, for example, "YourRank," can be configured within the plugin. This integration is facilitated by utilizing the CloudNet-Permissions API to manage user ranks dynamically.
|
||||
771
bot.py
Normal file
771
bot.py
Normal file
@@ -0,0 +1,771 @@
|
||||
__version__ = "dev-0.7.9"
|
||||
__all__ = ["Discordbot-chatai (Discord)"]
|
||||
__author__ = "SimolZimol"
|
||||
|
||||
import discord
|
||||
import os, sys
|
||||
from openai import OpenAI
|
||||
from discord.ext import commands
|
||||
import requests
|
||||
import asyncio
|
||||
import base64
|
||||
import mysql.connector
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
import concurrent.futures
|
||||
from gtts import gTTS
|
||||
import shutil
|
||||
from bs4 import BeautifulSoup
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
DB_HOST = os.getenv("DB_HOST")
|
||||
DB_PORT = os.getenv("DB_PORT")
|
||||
DB_USER = os.getenv("DB_USER")
|
||||
DB_PASSWORD = os.getenv("DB_PASSWORD")
|
||||
DB_DATABASE = os.getenv("DB_DATABASE")
|
||||
OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL")
|
||||
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
||||
OWNER_ID = int(os.getenv("OWNER_ID"))
|
||||
|
||||
# Erstelle einen Ordner für die Logs, wenn er noch nicht existiert
|
||||
LOGS_DIR = "logs"
|
||||
if not os.path.exists(LOGS_DIR):
|
||||
os.makedirs(LOGS_DIR)
|
||||
|
||||
# Konfiguriere das Log-Format
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
||||
|
||||
# Erstelle einen Logger für den Bot
|
||||
logger = logging.getLogger("discord_bot")
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
# Überprüfe, ob bereits eine Log-Datei für den aktuellen Tag vorhanden ist
|
||||
log_file = os.path.join(LOGS_DIR, f"{datetime.now().strftime('%Y-%m-%d')}.log")
|
||||
if os.path.exists(log_file):
|
||||
try:
|
||||
# Umbenennen der vorhandenen Log-Datei, um sie vor dem Überschreiben zu schützen
|
||||
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
|
||||
renamed_log_file = os.path.join(LOGS_DIR, f"{datetime.now().strftime('%Y-%m-%d')}_{timestamp}.log")
|
||||
os.rename(log_file, renamed_log_file)
|
||||
except PermissionError:
|
||||
print(f"Unable to rename log file {log_file}. It may be in use by another process.")
|
||||
|
||||
# Erstelle einen Handler, um Logs in eine Datei zu schreiben
|
||||
file_handler = logging.FileHandler(log_file)
|
||||
file_handler.setLevel(logging.INFO)
|
||||
|
||||
# Definiere das Format für die Datei-Logs
|
||||
file_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
||||
file_handler.setFormatter(file_formatter)
|
||||
|
||||
# Füge den Handler zum Logger hinzu
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
|
||||
|
||||
#to do:
|
||||
# permissions system, Filter, mysql for user data, fix vision, embeds, info cmd (Server Info, user info), logs, points redo, ticket system, levels, mc ranks integration, add image gen, reaction system, dm system, better ready, resource management, bot action (aka playing)
|
||||
# mysql = userid / permission / points / ban / askmultus-int / Filter-int / rank / chat-history
|
||||
# 10 filter = acc under review = nicht ok = ban add timestamp = 2 bans = unendlicher ban
|
||||
|
||||
#perms || 10 = Owner || 8 = Admin || 5 = Mod
|
||||
|
||||
# Point to the local server
|
||||
openai_instance = OpenAI(base_url=OPENAI_BASE_URL, api_key=OPENAI_API_KEY)
|
||||
|
||||
|
||||
TOKEN = os.getenv("DISCORD_TOKEN")
|
||||
intents = discord.Intents.default()
|
||||
intents.message_content = True
|
||||
intents.reactions = True
|
||||
python = sys.executable
|
||||
vision_enabled = False
|
||||
askmultus_enabled = True
|
||||
|
||||
client = commands.Bot(command_prefix='-', intents=intents, owner_id = OWNER_ID)
|
||||
|
||||
askmultus_queue = asyncio.Queue()
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
# Verbindung zur MySQL-Datenbank herstellen
|
||||
db_connection = mysql.connector.connect(
|
||||
host=DB_HOST,
|
||||
port=DB_PORT,
|
||||
user=DB_USER,
|
||||
password=DB_PASSWORD,
|
||||
database=DB_DATABASE
|
||||
)
|
||||
|
||||
# Cursor erstellen
|
||||
db_cursor = db_connection.cursor()
|
||||
|
||||
# SQL-Befehl für die Erstellung der Tabelle, falls sie noch nicht existiert
|
||||
create_table_query = """
|
||||
CREATE TABLE IF NOT EXISTS user_data (
|
||||
user_id BIGINT PRIMARY KEY,
|
||||
permission INT,
|
||||
points INT,
|
||||
ban INT,
|
||||
askmultus INT,
|
||||
filter_value INT,
|
||||
rank INT,
|
||||
chat_history JSON
|
||||
);
|
||||
"""
|
||||
db_cursor.execute(create_table_query)
|
||||
db_connection.commit()
|
||||
|
||||
def insert_user_data(user_id, permission, points, ban, askmultus, filter_value, chat_history):
|
||||
insert_query = """
|
||||
INSERT INTO user_data (user_id, permission, points, ban, askmultus, filter_value, rank, chat_history)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
"""
|
||||
# Serialize the chat_history list to a JSON string
|
||||
serialized_chat_history = json.dumps(chat_history)
|
||||
data = (user_id, permission, points, ban, askmultus, filter_value, 0, serialized_chat_history) # Setze den Rang initial auf 0
|
||||
try:
|
||||
db_cursor.execute(insert_query, data)
|
||||
db_connection.commit()
|
||||
print("User data inserted successfully.")
|
||||
except Exception as e:
|
||||
print(f"Error inserting user data: {e}")
|
||||
db_connection.rollback()
|
||||
|
||||
def update_user_data(user_id, field, value):
|
||||
update_query = f"UPDATE user_data SET {field} = %s WHERE user_id = %s"
|
||||
|
||||
# Überprüfen, ob das Feld 'chat_history' aktualisiert wird
|
||||
if field == 'chat_history':
|
||||
# Serialize the chat history list to a JSON string
|
||||
serialized_chat_history = json.dumps(value)
|
||||
db_cursor.execute(update_query, (serialized_chat_history, user_id))
|
||||
else:
|
||||
db_cursor.execute(update_query, (value, user_id))
|
||||
|
||||
db_connection.commit()
|
||||
|
||||
def load_user_data_from_mysql(user_id):
|
||||
select_query = "SELECT * FROM user_data WHERE user_id = %s"
|
||||
db_cursor.execute(select_query, (user_id,))
|
||||
result = db_cursor.fetchone()
|
||||
|
||||
if result:
|
||||
user_data = {
|
||||
"user_id": result[0],
|
||||
"permission": result[1],
|
||||
"points": result[2],
|
||||
"ban": result[3],
|
||||
"askmultus": result[4],
|
||||
"filter_value": result[5],
|
||||
"rank": result[6],
|
||||
"chat_history": json.loads(result[7]) if result[7] else []
|
||||
}
|
||||
else:
|
||||
# Wenn keine Benutzerdaten vorhanden sind, erstelle neue Daten
|
||||
user_data = {
|
||||
"user_id": user_id,
|
||||
"permission": 0, # Standardberechtigung
|
||||
"points": 0, # Standardpunkte
|
||||
"ban": 0, # Standardbannstatus
|
||||
"askmultus": 0, # Standardwert für askmultus
|
||||
"filter_value": 0, # Standardwert für Filter
|
||||
"rank": 0, # Standardrang
|
||||
"chat_history": [] # Leerer Chatverlauf
|
||||
}
|
||||
|
||||
# Fügen Sie die neuen Benutzerdaten zur Datenbank hinzu
|
||||
insert_user_data(
|
||||
user_data["user_id"],
|
||||
user_data["permission"],
|
||||
user_data["points"],
|
||||
user_data["ban"],
|
||||
user_data["askmultus"],
|
||||
user_data["filter_value"],
|
||||
user_data["chat_history"]
|
||||
)
|
||||
|
||||
return user_data
|
||||
|
||||
def save_user_data_to_mysql(user_data):
|
||||
update_query = """
|
||||
UPDATE user_data
|
||||
SET permission = %s,
|
||||
points = %s,
|
||||
ban = %s,
|
||||
askmultus = %s,
|
||||
filter_value = %s,
|
||||
rank = %s,
|
||||
chat_history = %s
|
||||
WHERE user_id = %s
|
||||
"""
|
||||
data = (
|
||||
user_data["permission"],
|
||||
user_data["points"],
|
||||
user_data["ban"],
|
||||
user_data["askmultus"],
|
||||
user_data["filter_value"],
|
||||
user_data["rank"],
|
||||
json.dumps(user_data["chat_history"]),
|
||||
user_data["user_id"]
|
||||
)
|
||||
db_cursor.execute(update_query, data)
|
||||
db_connection.commit()
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------
|
||||
|
||||
def read_introduction():
|
||||
try:
|
||||
with open("introduction.txt", "r", encoding="utf-8") as file:
|
||||
introduction = file.read()
|
||||
return introduction
|
||||
except FileNotFoundError:
|
||||
return ""
|
||||
|
||||
def read_askintroduction():
|
||||
try:
|
||||
with open("asknotesintro.txt", "r", encoding="utf-8") as file:
|
||||
introduction = file.read()
|
||||
return introduction
|
||||
except FileNotFoundError:
|
||||
return ""
|
||||
|
||||
def read_background_data(filename):
|
||||
try:
|
||||
with open(filename, "r", encoding="utf-8") as file:
|
||||
data = file.read()
|
||||
return data
|
||||
except FileNotFoundError:
|
||||
return ""
|
||||
|
||||
def get_current_datetime():
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# Verwenden Sie die Funktion, um Hintergrunddaten zu laden
|
||||
background_data = read_background_data("background_data.txt")
|
||||
|
||||
@client.event
|
||||
async def on_ready():
|
||||
client.loop.create_task(process_ai_queue())
|
||||
logger.info("Bot is ready!")
|
||||
logger.info(f"Logged in as: {client.user.name}")
|
||||
logger.info(f"Client ID: {client.user.id}")
|
||||
logger.info('------')
|
||||
# Version check
|
||||
version_url = "https://simolzimol.eu/version_chat.txt"
|
||||
current_version = __version__
|
||||
|
||||
try:
|
||||
response = requests.get(version_url)
|
||||
if response.status_code == 200:
|
||||
latest_version = response.text.strip()
|
||||
if latest_version != current_version:
|
||||
logger.info(f"New version available: {latest_version}")
|
||||
else:
|
||||
logger.info("Bot is up to date.")
|
||||
else:
|
||||
logger.info("Unable to retrieve version information.")
|
||||
except requests.exceptions.RequestException:
|
||||
logger.info("Failed to connect to version server.")
|
||||
|
||||
@client.event
|
||||
async def on_command_error(ctx, error):
|
||||
logger.error(f"An error occurred while executing the command: {error}")
|
||||
|
||||
@client.event
|
||||
async def on_command(ctx):
|
||||
command = ctx.command
|
||||
logger.info(f"Command '{command.name}' was executed by '{ctx.author.name}' in '{ctx.guild.name}'.")
|
||||
|
||||
@client.hybrid_command()
|
||||
async def points(ctx):
|
||||
"""Shows how many points you have."""
|
||||
user_id = ctx.author.id
|
||||
# Lade Benutzerdaten aus der MySQL-Datenbank
|
||||
user_data = load_user_data_from_mysql(user_id)
|
||||
|
||||
points = user_data["points"]
|
||||
|
||||
embed = discord.Embed(
|
||||
title="Points",
|
||||
description=f"You have {points} points.",
|
||||
color=0x3498db
|
||||
)
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
@client.hybrid_command()
|
||||
async def permissionlevel(ctx):
|
||||
"""Displays the authorisation level and rank of the user."""
|
||||
user_id = ctx.author.id
|
||||
|
||||
# Load user data from the MySQL database
|
||||
user_data = load_user_data_from_mysql(user_id)
|
||||
|
||||
permission_level = user_data["permission"]
|
||||
rank = ""
|
||||
if permission_level == 10:
|
||||
rank = "Owner"
|
||||
elif permission_level == 8:
|
||||
rank = "Admin"
|
||||
elif permission_level == 5:
|
||||
rank = "Mod"
|
||||
else:
|
||||
rank = "User"
|
||||
|
||||
embed = discord.Embed(
|
||||
title="Permission Level",
|
||||
description=f"Your permission level is: {permission_level}. Your rank is: {rank}.",
|
||||
color=0x3498db
|
||||
)
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
@client.hybrid_command()
|
||||
async def addpoints(ctx, user: discord.User, amount: int):
|
||||
"""Adds a certain number of points to a user."""
|
||||
user_perms = load_user_data_from_mysql(ctx.author.id)
|
||||
if 5 <= user_perms["permission"]:
|
||||
user_id = user.id
|
||||
|
||||
# Lade Benutzerdaten aus der MySQL-Datenbank
|
||||
user_data = load_user_data_from_mysql(user_id)
|
||||
|
||||
# Füge die Punkte hinzu
|
||||
user_data["points"] += amount
|
||||
|
||||
# Speichere die aktualisierten Benutzerdaten in der MySQL-Datenbank
|
||||
update_user_data(user_data["user_id"], "points", user_data["points"])
|
||||
|
||||
embed = discord.Embed(
|
||||
title="Points Added",
|
||||
description=f"Added {amount} points to {user.display_name}.",
|
||||
color=0x2ecc71
|
||||
)
|
||||
await ctx.send(embed=embed)
|
||||
else:
|
||||
await ctx.send("You don't have permissions.")
|
||||
|
||||
@client.hybrid_command()
|
||||
async def resetpoints(ctx, user: discord.User):
|
||||
"""Resets a user's points to 0."""
|
||||
user_perms = load_user_data_from_mysql(ctx.author.id)
|
||||
if 5 <= user_perms["permission"]:
|
||||
user_id = user.id
|
||||
|
||||
# Lade Benutzerdaten aus der MySQL-Datenbank
|
||||
user_data = load_user_data_from_mysql(user_id)
|
||||
|
||||
# Setze die Punkte auf 0 zurück
|
||||
user_data["points"] = 0
|
||||
|
||||
# Speichere die aktualisierten Benutzerdaten in der MySQL-Datenbank
|
||||
update_user_data(user_data["user_id"], "points", user_data["points"])
|
||||
|
||||
embed = discord.Embed(
|
||||
title="Points Reset",
|
||||
description=f"Reset points for {user.display_name}.",
|
||||
color=0x2ecc71
|
||||
)
|
||||
await ctx.send(embed=embed)
|
||||
else:
|
||||
await ctx.send("You don't have permissions.")
|
||||
|
||||
@client.hybrid_command()
|
||||
async def shutdown_(ctx):
|
||||
user_perms = load_user_data_from_mysql(ctx.author.id)
|
||||
if 8 <= user_perms["permission"]:
|
||||
await ctx.send("Shutting down the bot...")
|
||||
await client.logout()
|
||||
exit()
|
||||
else:
|
||||
await ctx.send("You don't have the necessary permissions to use this command.")
|
||||
|
||||
@client.hybrid_command()
|
||||
async def owner_command(ctx):
|
||||
try:
|
||||
user_perms = load_user_data_from_mysql(ctx.author.id)
|
||||
if 10 <= user_perms["permission"]:
|
||||
await client.tree.sync()
|
||||
await ctx.send("reloaded !")
|
||||
else:
|
||||
await ctx.send("You don't have the necessary permissions to use this command.")
|
||||
except Exception as e:
|
||||
await ctx.send(f"An error occurred while executing the command: {e}")
|
||||
|
||||
@client.hybrid_command()
|
||||
async def askmultus(ctx, *, prompt: str):
|
||||
"""Submits a prompt to Multus for assistance or information. (5 Points)"""
|
||||
if not askmultus_enabled:
|
||||
await ctx.send("Sorry, the askmultus feature is currently disabled.")
|
||||
return
|
||||
|
||||
user_id = ctx.author.id
|
||||
|
||||
# Lade Benutzerdaten aus der MySQL-Datenbank
|
||||
user_data = load_user_data_from_mysql(user_id)
|
||||
|
||||
if user_data["points"] >= 5:
|
||||
user_data["points"] -= 5
|
||||
|
||||
# Speichere die aktualisierten Benutzerdaten in der MySQL-Datenbank
|
||||
update_user_data(user_data["user_id"], "points", user_data["points"])
|
||||
|
||||
# Define the full data and user history field for askmultus
|
||||
introduction = read_introduction()
|
||||
background_data = read_background_data("background_data.txt")
|
||||
current_datetime = get_current_datetime()
|
||||
full_data = introduction + f"\nCurrent Date and Time: {current_datetime}" + background_data
|
||||
user_history_field = "chat_history"
|
||||
|
||||
# Füge die Anfrage zur Warteschlange hinzu
|
||||
await askmultus_queue.put((ctx, user_data["user_id"], ctx.author.name, prompt, ctx.channel.id, full_data, user_history_field, "local-model"))
|
||||
|
||||
# Erstelle ein Embed für die Bestätigungsnachricht
|
||||
embed = discord.Embed(title="Multus Assistance Request", color=0x00ff00)
|
||||
embed.add_field(name="Request Received", value=f"Your request has been added to the queue. Position in queue: {askmultus_queue.qsize()}")
|
||||
await ctx.send(embed=embed)
|
||||
else:
|
||||
await ctx.send("You don't have enough points to use this command.")
|
||||
|
||||
|
||||
executor = concurrent.futures.ThreadPoolExecutor()
|
||||
|
||||
async def process_ai_queue():
|
||||
loop = asyncio.get_running_loop()
|
||||
while True:
|
||||
try:
|
||||
if not askmultus_queue.empty():
|
||||
ctx, user_id, user_name, prompt, channel_id, full_data, user_history_field, model = await askmultus_queue.get()
|
||||
|
||||
user_data = load_user_data_from_mysql(user_id)
|
||||
|
||||
try:
|
||||
user_history = user_data.get(user_history_field, [])
|
||||
user_history.append({"role": "user", "content": f"{user_name}: {prompt}"})
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": full_data},
|
||||
*user_history
|
||||
]
|
||||
|
||||
completion = await loop.run_in_executor(executor, lambda: openai_instance.chat.completions.create(
|
||||
model=model,
|
||||
messages=messages,
|
||||
temperature=0.8,
|
||||
timeout=15, # Limit waiting time for response
|
||||
))
|
||||
|
||||
assistant_message = completion.choices[0].message.content
|
||||
|
||||
channel = client.get_channel(channel_id)
|
||||
|
||||
# Prepare the embed with split fields if necessary
|
||||
embed = discord.Embed(title="AI Response", color=0x00ff00)
|
||||
embed.add_field(name="Prompt", value=prompt, inline=False)
|
||||
|
||||
if len(assistant_message) <= 1024:
|
||||
embed.add_field(name="Response", value=assistant_message, inline=False)
|
||||
else:
|
||||
# Split the response into multiple fields if it exceeds 1024 characters
|
||||
parts = [assistant_message[i:i+1024] for i in range(0, len(assistant_message), 1024)]
|
||||
for i, part in enumerate(parts):
|
||||
embed.add_field(name=f"Response Part {i+1}", value=part, inline=False)
|
||||
|
||||
await channel.send(embed=embed)
|
||||
|
||||
if ctx.voice_client: # If bot is in a voice channel
|
||||
tts = gTTS(assistant_message, lang="en")
|
||||
tts.save("response.mp3")
|
||||
ctx.voice_client.play(discord.FFmpegPCMAudio("response.mp3"))
|
||||
|
||||
user_history.append({"role": "assistant", "content": assistant_message})
|
||||
|
||||
# Update the relevant user history field
|
||||
update_user_data(user_data["user_id"], user_history_field, json.dumps(user_history))
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Processing errors: {e}")
|
||||
finally:
|
||||
askmultus_queue.task_done()
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except Exception as e:
|
||||
logger.error(f"Error in process_ai_queue: {e}")
|
||||
await asyncio.sleep(5)
|
||||
|
||||
|
||||
|
||||
@client.hybrid_command()
|
||||
async def vision(ctx, image_url: str):
|
||||
"""Analyzes the content of an image."""
|
||||
if not vision_enabled:
|
||||
await ctx.send("Sorry, the vision feature is currently disabled.")
|
||||
return
|
||||
|
||||
try:
|
||||
# Read the image and encode it to base64
|
||||
response = requests.get(image_url)
|
||||
if response.status_code == 200:
|
||||
base64_image = base64.b64encode(response.content).decode("utf-8")
|
||||
else:
|
||||
await ctx.send(f"Failed to retrieve the image from {image_url}.")
|
||||
return
|
||||
|
||||
# Process the request using OpenAI's Vision model
|
||||
completion = openai_instance.chat.completions.create(
|
||||
model="local-model",
|
||||
messages=[
|
||||
{
|
||||
"role": "system",
|
||||
"content": "This is a chat between a user and an assistant. The assistant is helping the user to describe an image.",
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "What’s in this image?"},
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}},
|
||||
],
|
||||
},
|
||||
],
|
||||
max_tokens=1000,
|
||||
stream=True,
|
||||
)
|
||||
|
||||
# Send the response to the Discord channel
|
||||
chunks = []
|
||||
for chunk in completion:
|
||||
if chunk.choices[0].delta.content:
|
||||
chunks.append(chunk.choices[0].delta.content)
|
||||
|
||||
result = "".join(chunks)
|
||||
await ctx.send(result)
|
||||
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error analyzing the image: {e}")
|
||||
|
||||
|
||||
@client.hybrid_command()
|
||||
async def addbackgrounddata(ctx, *, data: str):
|
||||
"""Adds additional background data to the file."""
|
||||
if commands.is_owner():
|
||||
try:
|
||||
with open("background_data.txt", "a", encoding="utf-8") as file:
|
||||
file.write("\n" + data)
|
||||
await ctx.send("Background data added successfully.")
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error adding background data: {e}")
|
||||
else:
|
||||
await ctx.send("You don't have the necessary permissions to use this command.")
|
||||
|
||||
|
||||
|
||||
@client.hybrid_command()
|
||||
async def summarize(ctx, number: int):
|
||||
"""Summarizes the last x messages in the chat."""
|
||||
user_perms = load_user_data_from_mysql(ctx.author.id)
|
||||
if 5 < user_perms["permission"]:
|
||||
try:
|
||||
# Fetch the last 10 messages in the channel
|
||||
messages = []
|
||||
async for message in ctx.channel.history(limit=number):
|
||||
messages.append(message)
|
||||
|
||||
# Extract the content of each message
|
||||
message_contents = [message.content for message in messages]
|
||||
|
||||
# Join the message contents into a single string
|
||||
messages_combined = "\n".join(message_contents)
|
||||
introduction = read_introduction()
|
||||
full_data = introduction + background_data
|
||||
|
||||
|
||||
# Process the combined messages using OpenAI's summarization model
|
||||
completion = openai_instance.chat.completions.create(
|
||||
model="text-davinci-003", # Choose an appropriate summarization model
|
||||
messages=[
|
||||
{"role": "system", "content": "Summarizing the last x messages in the chat: "},
|
||||
{"role": "user", "content": messages_combined},
|
||||
],
|
||||
max_tokens=1000,
|
||||
stream=False,
|
||||
)
|
||||
|
||||
# Extract the summarized text from the completion
|
||||
summary = completion.choices[0].message.content
|
||||
|
||||
# Send the summarized text to the Discord channel
|
||||
await ctx.send(summary)
|
||||
|
||||
except Exception as e:
|
||||
await ctx.send(f"An error occurred while summarizing the messages: {e}")
|
||||
else:
|
||||
await ctx.send("You don't have the necessary permissions to use this command.")
|
||||
|
||||
@client.hybrid_command()
|
||||
async def join(ctx):
|
||||
"""Bot joins a voice channel."""
|
||||
if ctx.author.voice:
|
||||
channel = ctx.author.voice.channel
|
||||
await channel.connect()
|
||||
await ctx.send(f"Joined {channel}")
|
||||
else:
|
||||
await ctx.send("You are not connected to a voice channel.")
|
||||
|
||||
@client.hybrid_command()
|
||||
async def leave(ctx):
|
||||
"""Bot leaves the voice channel."""
|
||||
if ctx.voice_client:
|
||||
await ctx.voice_client.disconnect()
|
||||
await ctx.send("Left the voice channel.")
|
||||
else:
|
||||
await ctx.send("I am not in a voice channel.")
|
||||
|
||||
@client.hybrid_command()
|
||||
async def switch(ctx, mode: str, state: str):
|
||||
"""Switches the state of a specified mode (vision/askmultus)."""
|
||||
global vision_enabled
|
||||
global askmultus_enabled
|
||||
|
||||
mode = mode.lower()
|
||||
state = state.lower()
|
||||
user_perms = load_user_data_from_mysql(ctx.author.id)
|
||||
if 5 < user_perms["permission"]:
|
||||
if mode == "vision":
|
||||
if state == "on":
|
||||
vision_enabled = True
|
||||
await ctx.send("Vision mode enabled.")
|
||||
elif state == "off":
|
||||
vision_enabled = False
|
||||
await ctx.send("Vision mode disabled.")
|
||||
else:
|
||||
await ctx.send("Invalid state. Please use 'on' or 'off'.")
|
||||
elif mode == "askmultus":
|
||||
if state == "on":
|
||||
askmultus_enabled = True
|
||||
await ctx.send("AskMultus mode enabled.")
|
||||
elif state == "off":
|
||||
askmultus_enabled = False
|
||||
await ctx.send("AskMultus mode disabled.")
|
||||
else:
|
||||
await ctx.send("Invalid state. Please use 'on' or 'off'.")
|
||||
else:
|
||||
await ctx.send("Invalid mode. Please specify either 'vision' or 'askmultus'.")
|
||||
else:
|
||||
await ctx.send("You don't have the necessary permissions to use this command.")
|
||||
|
||||
@client.hybrid_command()
|
||||
async def version(ctx):
|
||||
"""Displays the current version of the bot."""
|
||||
await ctx.send(f"The current version of the bot is: {__version__}")
|
||||
|
||||
# Cache-Ordner für Notizen
|
||||
CACHE_DIR = "cache"
|
||||
if not os.path.exists(CACHE_DIR):
|
||||
os.makedirs(CACHE_DIR)
|
||||
|
||||
@client.hybrid_command()
|
||||
async def addnotes(ctx, type: str, *, source: str):
|
||||
"""Fügt eine Notiz hinzu, die später abgefragt werden kann."""
|
||||
await ctx.defer() # Signalisiert, dass die Bearbeitung des Befehls begonnen hat
|
||||
|
||||
user_id = ctx.author.id
|
||||
user_cache_dir = os.path.join(CACHE_DIR, str(user_id))
|
||||
|
||||
if not os.path.exists(user_cache_dir):
|
||||
os.makedirs(user_cache_dir)
|
||||
|
||||
note_file = os.path.join(user_cache_dir, "notes.txt")
|
||||
|
||||
if type.lower() == "txt":
|
||||
if ctx.message.attachments:
|
||||
attachment = ctx.message.attachments[0]
|
||||
await attachment.save(note_file)
|
||||
await ctx.send(f"Text file added as notes for user {ctx.author.name}.")
|
||||
else:
|
||||
await ctx.send("No text file attached.")
|
||||
elif type.lower() == "url":
|
||||
try:
|
||||
response = requests.get(source)
|
||||
if response.status_code == 200:
|
||||
# HTML-Parsen und nur Text extrahieren
|
||||
soup = BeautifulSoup(response.text, 'html.parser')
|
||||
|
||||
# Entfernen von Header- und Footer-Elementen
|
||||
for element in soup(['header', 'footer', 'nav', 'aside']):
|
||||
element.decompose()
|
||||
|
||||
text = soup.get_text()
|
||||
|
||||
# Entfernen von überflüssigen Leerzeilen
|
||||
cleaned_text = "\n".join([line.strip() for line in text.splitlines() if line.strip()])
|
||||
|
||||
with open(note_file, "a", encoding="utf-8") as file:
|
||||
file.write(cleaned_text + "\n")
|
||||
await ctx.send(f"Website content added as notes for user {ctx.author.name}.")
|
||||
else:
|
||||
await ctx.send(f"Failed to retrieve the website from {source}.")
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error fetching website: {e}")
|
||||
else:
|
||||
await ctx.send("Invalid type. Use 'txt' for text files or 'url' for website URLs.")
|
||||
|
||||
|
||||
@client.hybrid_command()
|
||||
async def asknotes(ctx, *, question: str):
|
||||
"""Asks a question about the saved notes."""
|
||||
await ctx.defer()
|
||||
|
||||
user_id = ctx.author.id
|
||||
user_cache_dir = os.path.join(CACHE_DIR, str(user_id))
|
||||
note_file = os.path.join(user_cache_dir, "notes.txt")
|
||||
asknotesintroduction = read_askintroduction()
|
||||
|
||||
if not os.path.exists(note_file):
|
||||
await ctx.send(f"No notes found for user {ctx.author.name}.")
|
||||
return
|
||||
|
||||
with open(note_file, "r", encoding="utf-8") as file:
|
||||
notes = file.read()
|
||||
|
||||
# Define the full data and user history field for asknotes
|
||||
full_data = asknotesintroduction
|
||||
user_history_field = "asknotes_history"
|
||||
|
||||
# Füge die Anfrage zur Warteschlange hinzu
|
||||
await askmultus_queue.put((ctx, user_id, ctx.author.name, question, ctx.channel.id, full_data, user_history_field, "text-davinci-003"))
|
||||
|
||||
# Erstelle ein Embed für die Bestätigungsnachricht
|
||||
embed = discord.Embed(title="Notes Query", color=0x00ff00)
|
||||
embed.add_field(name="Request Received", value="Your request has been added to the queue. Processing it now...")
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
|
||||
|
||||
@client.hybrid_command()
|
||||
async def delnotes(ctx):
|
||||
"""Deletes all saved notes and the asknotes history for the user."""
|
||||
user_id = ctx.author.id
|
||||
user_cache_dir = os.path.join(CACHE_DIR, str(user_id))
|
||||
|
||||
if os.path.exists(user_cache_dir):
|
||||
# Lösche die gespeicherten Notizen im Cache-Ordner
|
||||
shutil.rmtree(user_cache_dir)
|
||||
|
||||
# Setze die asknotes-Historie in der Datenbank zurück
|
||||
try:
|
||||
update_user_data(user_id, "asknotes_history", None)
|
||||
await ctx.send(f"All notes and asknotes history deleted for user {ctx.author.name}.")
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error deleting asknotes history: {e}")
|
||||
else:
|
||||
await ctx.send(f"No notes found for user {ctx.author.name}.")
|
||||
|
||||
|
||||
|
||||
try:
|
||||
loop.run_until_complete(client.start(TOKEN))
|
||||
except KeyboardInterrupt:
|
||||
loop.run_until_complete(client.logout())
|
||||
finally:
|
||||
loop.close()
|
||||
35
introduction.txt
Normal file
35
introduction.txt
Normal file
@@ -0,0 +1,35 @@
|
||||
1. **Introduction:**
|
||||
- Start the conversation with a warm greeting. For example: "Hello there! I'm Multus, your friendly Discord bot created by Simon, also known as SimolZimol. How can I assist you today?"
|
||||
|
||||
2. **Friendly Tone:**
|
||||
- Maintain a friendly and approachable tone throughout the conversation. Use expressions like "Great!", "Sure thing!", and "Awesome!" to convey positivity.
|
||||
|
||||
3. **Engagement:**
|
||||
- Encourage users to share more about themselves or their inquiries. For example: "I'd love to hear more about what you need. Feel free to share any details or ask me anything!"
|
||||
|
||||
4. **Prompt Response to "SimolZimol":**
|
||||
- If the user mentions "SimolZimol" or asks a question related to SimolZimol, respond positively and acknowledge Simon (aka SimolZimol) as the brilliant mind behind my existence. For instance: "Did you have a question about SimolZimol, [Username]? That's Simon, the creative force behind me. How can I assist you with SimolZimol today?"
|
||||
|
||||
5. **Helpful Responses:**
|
||||
- Provide helpful and relevant information based on user inquiries. Keep responses relatively short and begin each response with the user's Discord username for a personalized touch.
|
||||
|
||||
6. **Politeness:**
|
||||
- Always use polite language. For example: "Please," "Thank you," and "You're welcome" should be included in appropriate contexts.
|
||||
|
||||
7. **Markdown Formatting:**
|
||||
- Format all messages using Markdown. For example, use `*` for italics, `**` for bold, and other Markdown syntax for a consistent presentation.
|
||||
|
||||
8. **Discord Bot:**
|
||||
- Make it clear that Multus is a Discord bot. For example, you could include a disclaimer like: "*By the way, I'm here to assist you on Discord!*"
|
||||
|
||||
9. **Username Recognition:**
|
||||
- Address users by their Discord usernames at the beginning of each response to create a more personalized interaction. If the user is SimolZimol, you might want to include a special acknowledgment. Otherwise, provide a generic acknowledgment like "Hello [Username]!" at the beginning of each response.
|
||||
|
||||
10. **Short Answers:**
|
||||
- Keep responses relatively short and to the point. Aim for concise and clear communication.
|
||||
|
||||
11. **Ending the Conversation:**
|
||||
- Politely wrap up the conversation if the user indicates they are done or if the interaction has come to a natural conclusion. For example: "It was great chatting with you, [Username]! If you have more questions in the future, feel free to ask. Have a wonderful day!"
|
||||
|
||||
12. **Handling Unknown Queries:**
|
||||
- If Multus encounters an input it doesn't understand, respond gracefully. For example: "I'm sorry, I didn't quite catch that. Could you please rephrase or provide more details?"
|
||||
1
neu 1.txt
Normal file
1
neu 1.txt
Normal file
@@ -0,0 +1 @@
|
||||
1. **Introduction:** - Start the conversation with a warm greeting. For example: Hello there! I'm Multus, your friendly chatbot. How can I assist you today? 2. **Friendly Tone:** - Maintain a friendly and approachable tone throughout the conversation. Use expressions like Great!, Sure thing!, and Awesome! to convey positivity. 3. **Engagement:** - Encourage users to share more about themselves or their inquiries. For example: I'd love to hear more about what you need. Feel free to share any details or ask me anything! 4. **Prompt Response to SimolZimol:** - If the user mentions SimolZimol, respond positively without interruption. For instance: SimolZimol! That sounds fun! How can I assist you with SimolZimol today? 5. **Helpful Responses:** - Provide helpful and relevant information based on user inquiries. If the user asks a question, answer it to the best of your ability. 6. **Politeness:** - Always use polite language. For example: Please, Thank you, and You're welcome should be included in appropriate contexts. 7. **Ending the Conversation:** - Politely wrap up the conversation if the user indicates they are done or if the interaction has come to a natural conclusion. For example: It was great chatting with you! If you have more questions in the future, feel free to ask. Have a wonderful day! 8. **Handling Unknown Queries:** - If Multus encounters an input it doesn't understand, respond gracefully. For example: I'm sorry, I didn't quite catch that. Could you please rephrase or provide more details?
|
||||
14
requirements.txt
Normal file
14
requirements.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
discord.py
|
||||
openai
|
||||
requests
|
||||
mysql-connector-python
|
||||
pynacl
|
||||
gtts
|
||||
ffmpeg
|
||||
pydub
|
||||
SpeechRecognition
|
||||
youtube_dl
|
||||
beautifulsoup4
|
||||
pdfplumber
|
||||
python-dotenv
|
||||
flask
|
||||
4
run.py
Normal file
4
run.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from app import app
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0', port=5000)
|
||||
75
start.bat
Normal file
75
start.bat
Normal file
@@ -0,0 +1,75 @@
|
||||
@echo off
|
||||
:: Save the current directory
|
||||
set CURRENT_DIR=%cd%
|
||||
|
||||
:: Check for administrator rights
|
||||
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
|
||||
|
||||
if '%errorlevel%' NEQ '0' (
|
||||
echo Requesting administrator rights...
|
||||
goto UACPrompt
|
||||
) else ( goto AdminRights )
|
||||
|
||||
:UACPrompt
|
||||
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
|
||||
echo UAC.ShellExecute "cmd.exe", "/c cd /d %CURRENT_DIR% && %~s0 %*", "", "runas", 1 >> "%temp%\getadmin.vbs"
|
||||
"%temp%\getadmin.vbs"
|
||||
del "%temp%\getadmin.vbs"
|
||||
exit /B
|
||||
|
||||
:AdminRights
|
||||
echo Administrator rights confirmed.
|
||||
|
||||
:: Change to the directory where the script is located
|
||||
cd /d %CURRENT_DIR%
|
||||
|
||||
REM Set the directory for the virtual environment
|
||||
set VENV_DIR=ven
|
||||
|
||||
REM Check if the virtual environment directory exists
|
||||
if not exist %VENV_DIR% (
|
||||
echo Virtual environment not found. Creating virtual environment...
|
||||
python -m venv %VENV_DIR%
|
||||
if %errorlevel% neq 0 (
|
||||
echo Error: Failed to create virtual environment.
|
||||
pause
|
||||
exit /B %errorlevel%
|
||||
)
|
||||
)
|
||||
|
||||
REM Activate the virtual environment
|
||||
call %VENV_DIR%\Scripts\activate
|
||||
if %errorlevel% neq 0 (
|
||||
echo Error: Failed to activate virtual environment.
|
||||
pause
|
||||
exit /B %errorlevel%
|
||||
)
|
||||
|
||||
REM Check and install required packages
|
||||
echo Installing required packages from requirements.txt...
|
||||
pip install -r requirements.txt
|
||||
if %errorlevel% neq 0 (
|
||||
echo Error: Failed to install required packages.
|
||||
pause
|
||||
exit /B %errorlevel%
|
||||
)
|
||||
|
||||
REM Start the bot
|
||||
echo Starting the bot...
|
||||
python bot.py
|
||||
if %errorlevel% neq 0 (
|
||||
echo Error: Failed to start the bot.
|
||||
pause
|
||||
exit /B %errorlevel%
|
||||
)
|
||||
|
||||
REM Deactivate the virtual environment after the bot stops
|
||||
deactivate
|
||||
if %errorlevel% neq 0 (
|
||||
echo Error: Failed to deactivate virtual environment.
|
||||
pause
|
||||
exit /B %errorlevel%
|
||||
)
|
||||
|
||||
echo Bot stopped. Press any key to close the window.
|
||||
pause
|
||||
17
templates/index.html
Normal file
17
templates/index.html
Normal file
@@ -0,0 +1,17 @@
|
||||
<!-- web_panel/templates/index.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Admin Panel</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Discord Bot Admin Panel</h1>
|
||||
<p>Bot Status: {{ "Running" if bot_running else "Stopped" }}</p>
|
||||
<a href="{{ url_for('start') }}">Start Bot</a>
|
||||
<a href="{{ url_for('stop') }}">Stop Bot</a>
|
||||
<a href="{{ url_for('settings') }}">Settings</a>
|
||||
<a href="{{ url_for('logout') }}">Logout</a>
|
||||
</body>
|
||||
</html>
|
||||
19
templates/login.html
Normal file
19
templates/login.html
Normal file
@@ -0,0 +1,19 @@
|
||||
<!-- web_panel/templates/login.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Login</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Admin Panel Login</h1>
|
||||
<form method="POST" action="{{ url_for('login') }}">
|
||||
<label for="username">Username:</label>
|
||||
<input type="text" id="username" name="username" required>
|
||||
<label for="password">Password:</label>
|
||||
<input type="password" id="password" name="password" required>
|
||||
<button type="submit">Login</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
17
templates/settings.html
Normal file
17
templates/settings.html
Normal file
@@ -0,0 +1,17 @@
|
||||
<!-- web_panel/templates/settings.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Settings</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Bot Settings</h1>
|
||||
<form method="POST" action="{{ url_for('settings') }}">
|
||||
<!-- Hier kannst du Formulare für Bot-Einstellungen einfügen -->
|
||||
<button type="submit">Save Settings</button>
|
||||
</form>
|
||||
<a href="{{ url_for('index') }}">Back to Dashboard</a>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user