From 6589b7332924decdc218118c5d6c6e083080161f Mon Sep 17 00:00:00 2001 From: migatu Date: Wed, 10 Apr 2024 15:45:14 +0200 Subject: [PATCH] After squash fixes After squash fixes --- .trunk/.gitignore | 4 - .trunk/trunk.yaml | 37 - bot.py | 1085 +++++++++++++++++++------- file_webservice/conjurer_musician.py | 3 - 4 files changed, 805 insertions(+), 324 deletions(-) diff --git a/.trunk/.gitignore b/.trunk/.gitignore index 6b31cd9..15966d0 100644 --- a/.trunk/.gitignore +++ b/.trunk/.gitignore @@ -6,8 +6,4 @@ plugins user_trunk.yaml user.yaml -<<<<<<< HEAD tmp -======= -tools ->>>>>>> c7dc465 (Parametryzacja "muzyki mojego ludu") diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 5e2903b..4a7abcb 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -2,7 +2,6 @@ # To learn more about the format of this file, see https://docs.trunk.io/reference/trunk-yaml version: 0.1 cli: -<<<<<<< HEAD version: 1.20.1 # Trunk provides extensibility via plugins. (https://docs.trunk.io/plugins) plugins: @@ -11,44 +10,10 @@ plugins: ref: v1.4.5 uri: https://github.com/trunk-io/plugins # Many linters and tools depend on runtimes - configure them here. (https://docs.trunk.io/runtimes) -======= - version: 1.12.1 -plugins: - sources: - - id: trunk - ref: v0.0.22 - uri: https://github.com/trunk-io/plugins -lint: - enabled: - - actionlint@1.6.25 - - markdownlint@0.35.0 - - trivy@0.43.1 - - trufflehog@3.44.0 - - pylint - - codespell - - cspell - - git-diff-check - - eslint - - prettier - - semgrep - - autopep8 - - bandit - - black - - flake8 - - isort - - mypy - - pylint - - ruff - - semgrep - - yapf - - gitleaks - ->>>>>>> c7dc465 (Parametryzacja "muzyki mojego ludu") runtimes: enabled: - node@18.12.1 - python@3.10.8 -<<<<<<< HEAD # This is the section where you manage your linters. (https://docs.trunk.io/check/configuration) lint: enabled: @@ -66,8 +31,6 @@ lint: - trivy@0.50.1 - trufflehog@3.71.0 - yamllint@1.35.1 -======= ->>>>>>> c7dc465 (Parametryzacja "muzyki mojego ludu") actions: disabled: - trunk-announce diff --git a/bot.py b/bot.py index b2ada71..859f03c 100644 --- a/bot.py +++ b/bot.py @@ -1,12 +1,10 @@ +# This Python file uses the following encoding: utf-8 +# trunk-ignore-all(bandit/B311) +# pylint: disable=line-too-long +# pylint: disable=too-many-lines """ Module of a python bot named Conjurer - used to work on BDSM discord servers. """ -# This Python file uses the following encoding: utf-8 -# trunk-ignore-all(flake8/E501) -# trunk-ignore-all(bandit/B311) -# trunk-ignore-all(mypy/index) -# pylint: disable=line-too-long -# pylint: disable=too-many-lines import asyncio import io import json @@ -19,10 +17,13 @@ import random import re import shutil import sys +import threading +import uuid from datetime import datetime from logging import handlers from pathlib import Path, PurePath from platform import uname +from queue import Empty from sys import platform from typing import List, Optional, TypedDict @@ -35,30 +36,46 @@ import pdf2image import PyPDF2 import requests import spotipy -from discord.ext import commands +import tiktoken +from discord.ext import commands, tasks from spotipy.oauth2 import SpotifyClientCredentials +import yt_dlp +from spotify_dl import spotify from spotify_dl import youtube as youtube_download -from spotify_dl import spotify +from communication_subroutine import comm_subroutine, IN_COMM_Q, OUT_COMM_Q + Music_Config = TypedDict( "Music_Config", { - "playing": bool, "ctx": Optional[str], "queue": List[str], - "requestor": List[str], + "requester": List[str], }, ) + +class QueryControl: + def __init__(self, query_author, query_uuid, query_content, uplogger, ctx) -> None: + self.author = query_author + self.uuid = query_uuid + self.content = query_content + self.logger = uplogger + self.stop = False + self.ctx = ctx + self.logger.info( + f"Created Query control for {self.author}, {self.uuid}: {self.content}" + ) + self.replies = [] + + # *=========================================== Predefines -formatter = logging.Formatter( - "%(asctime)s - %(name)s - %(levelname)s - %(message)s") +formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") MASTER_TIMEOUT = datetime.now() -INITIAL_TIME_WAIT = 5 -MUZYKA: Music_Config = {"playing": False, - "ctx": None, "queue": [], "requestor": []} +INITIAL_TIME_WAIT = 500 +MUZYKA: Music_Config = {"ctx": None, "queue": [], "requester": []} LOGFILE = "" NETRC_FILE = "" @@ -69,9 +86,19 @@ SETTINGS_FILE = "" ENCODING = "" GRAPHICS_PATH = "" MUZYKA_MOJEGO_LUDU_HISTORIA = 1500 -MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE = 30 +MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE = 15 MUZYKA_MOJEGO_LUDU_PLAJLISTA = 30 +FILE_SERVICE_ADDRESS = "http://192.168.1.15:5000" +GET_MP3 = "/mp3" +SEND_MP3 = "/update_mp3" +GET_PLAYLIST = "/get_music" +LIBRARIAN_SERVICE_ADDRESS = "http://192.168.1.192:5001" +SEND_QUERY = "/query" +TIME_BETWEEN_CALLS = 100000 +LAST_SPONTANEOUS_CALL = datetime.now() +HOST_ADDRESS = "192.168.1.191" +PORT_ADDRESS = 5000 # *=========================================== Platform Specific Predefines @@ -80,6 +107,7 @@ if platform in ("linux", "linux2"): if "microsoft-standard" in uname().release: LOGFILE = "/home/mtuszowski/conjurer/discord.log" MEMORY_FIVE_SIARA = "/home/mtuszowski/conjurer/pamiec.json" + SYSTEM_GPT_SETTINGS = "/home/mtuszowski/conjurer/system_gpt_settings.json" MEMORY_FIVE_MUZYKA = "/home/mtuszowski/conjurer/pamiec_muzyki.json" MUSIC_FOLDER = "/mnt/g/Muzyka/" SETTINGS_FILE = "/home/mtuszowski/conjurer/settings.json" @@ -93,6 +121,7 @@ if platform in ("linux", "linux2"): else: LOGFILE = "/home/pi/Conjurer/discord.log" MEMORY_FIVE_SIARA = "/home/pi/Conjurer/pamiec.json" + SYSTEM_GPT_SETTINGS = "/home/pi/Conjurer/system_gpt_settings.json" MEMORY_FIVE_MUZYKA = "/home/pi/Conjurer/pamiec_muzyki.json" MUSIC_FOLDER = "/home/pi/RetroPie/mp3/" SETTINGS_FILE = "/home/pi/Conjurer/settings.json" @@ -107,6 +136,7 @@ if platform in ("linux", "linux2"): elif platform == "win32": LOGFILE = "discord.log" MEMORY_FIVE_SIARA = "pamiec.json" + SYSTEM_GPT_SETTINGS = "system_gpt_settings.json" MEMORY_FIVE_MUZYKA = "pamiec_muzyki.json" MUSIC_FOLDER = "G:\\Muzyka\\" SETTINGS_FILE = "settings.json" @@ -127,6 +157,7 @@ TOKEN = authTokens[2] REMOTE_HOST_NAME = "openai" authTokens = netrc_mod.authenticators(REMOTE_HOST_NAME) openai.api_key = authTokens[2] +openAIClient = openai.AsyncOpenAI(api_key=openai.api_key) REMOTE_HOST_NAME = "spotipy" authTokens = netrc_mod.authenticators(REMOTE_HOST_NAME) @@ -161,38 +192,114 @@ logger.debug(platform) logger.info("Playlist generation") # *=========================================== Load Data files + + +class MusicFileList(object): + """ + The `MusicFileList` class manages a list of music files, with the ability to refresh the list from a + file service or local directory and update the list with new items. + """ + + def __init__(self, uplogger) -> None: + self.music_file_list = [] + self.file_service_active = False + self.logger = uplogger + self.logger.info("Created Playlist organizer class") + + def refresh_file_list(self): + """ + The `refresh_file_list` function attempts to connect to a file service to retrieve a list of music + files, and if unsuccessful, it populates the list by scanning a local directory for .mp3 files. + """ + try: + self.logger.info("Attempt to connect to file service") + response = requests.get(f"{FILE_SERVICE_ADDRESS}{GET_MP3}", timeout=360) + self.music_file_list = response.json()["music_file_list"] + self.file_service_active = True + except requests.exceptions.RequestException as e: + for mp3_item in Path.glob(Path(MUSIC_FOLDER), "**/*.mp3"): + temp_music_file = mp3_item.as_posix() + if platform == "win32": + temp_music_file = temp_music_file.replace("/", "\\") + self.music_file_list.append(temp_music_file) + self.file_service_active = False + self.logger.error(e.strerror) + self.logger.error("Service Unavailable") + + def get_file_list(self): + """ + The `get_file_list` function returns the list of music files stored in the object. + :return: The `music_file_list` attribute is being returned. + """ + return self.music_file_list + + def update_file_list(self, item): + """ + The `update_file_list` function appends an item to a music file list and sends a POST request with + the item data to a file service address. + + :param item: The `item` parameter in the `update_file_list` method is the file that you want to add + to the `music_file_list` attribute of the class instance. It is then sent as a JSON payload in a + POST request to a file service address along with the endpoint `SEND_MP3` + """ + self.music_file_list.append(item) + post_data = {"item": str(item)} + requests.post(f"{FILE_SERVICE_ADDRESS}{SEND_MP3}", json=post_data, timeout=360) + + music_file_list = [] -for mp3_item in Path.glob(Path(MUSIC_FOLDER), "**/*.mp3"): - temp_music_file = mp3_item.as_posix() - if platform == "win32": - temp_music_file = temp_music_file.replace("/", "\\") - music_file_list.append(temp_music_file) +music_file_list = MusicFileList(logger) +music_file_list.refresh_file_list() +logger.info("Playlist generation done") + +logger.info("Loading GPT settings") +with open(SYSTEM_GPT_SETTINGS, "r+", encoding=ENCODING) as temp_settings_file: + # First we load existing data into a dict. + GPT_SETTINGS = json.load(temp_settings_file) +logger.info("Done") + +logger.info("Loading memory file") with open(MEMORY_FIVE_SIARA, "r+", encoding=ENCODING) as temp_memory_file: # First we load existing data into a dict. MESSAGE_TABLE = json.load(temp_memory_file) +logger.info("Done") + +logger.info("Loading music memory file") with open(MEMORY_FIVE_MUZYKA, "r+", encoding=ENCODING) as temp_music_memory_file: # First we load existing data into a dict. message_table_muzyka = json.load(temp_music_memory_file) +logger.info("Done") + +logger.info("Loading settings file") with open(SETTINGS_FILE, "r", encoding=ENCODING) as f_settings_file: data = json.load(f_settings_file) +logger.info("Done") + +logger.info("Loading reactions") word_reactions = data["word_reactions"] +cyclic_words = data["cyclic_words"] historia_fabryczki = data["fabryczka"] for key in word_reactions: word_reactions[key][2] = datetime.now() +logger.info("Done") # *=========================================== Create Client +logger.info("Creating discord bot") client = commands.Bot(intents=intents, command_prefix="$") +logger.info("Done") +logger.info("Creating flask app") +logger.info("Done") + # *=========================================== Define Events - - @client.event async def on_ready(): """Metoda wywoływana przy połączeniu do serwera.""" logger.debug("%s has connected to Discord!", client.user) await client.change_presence(activity=discord.Game(name="Axe Throwing Darts")) await client.tree.sync() - await check() + check_self.start() + check_data_q.start() @client.event @@ -200,7 +307,6 @@ async def on_ready(): # trunk-ignore(pylint/R0914) # trunk-ignore(pylint/R0912) async def on_message(message): - """ Handle incoming messages in a Discord server, perform various checks and actions based on the content and context of the message, and respond accordingly. @@ -240,7 +346,6 @@ async def on_message(message): channel = message.channel await client.process_commands(message) - # TODO: wpiac jego reakcje we framework chatu GPT message.content = message.content.lower() tdelta = datetime.now() - MASTER_TIMEOUT @@ -270,8 +375,12 @@ async def on_message(message): word_reactions[word][2] = datetime.now() # TODO: drobne literówki, mentiony, spacja przed dwukropkiem. napraw. + kondziu_mentioned = False + for mention in message.mentions: + if mention == client.user: + kondziu_mentioned = True - if "conjurer:" in message.content: + if kondziu_mentioned or "conjurer:" in message.content: async with channel.typing(): logger.debug("Procedura chatu") @@ -294,7 +403,7 @@ async def on_message(message): global MESSAGE_TABLE # pylint: disable=global-statement result, MESSAGE_TABLE = await handle_response( - prompt, vykidailo, bartender, MESSAGE_TABLE, username, False + prompt, vykidailo, bartender, MESSAGE_TABLE, username, "CONVERSATION" ) await message.reply(result) if "imaginuje sobie:" in message.content: @@ -302,28 +411,107 @@ async def on_message(message): logger.info("Poczatek procedury obrazkowej") message.content = message.content.replace("imaginuje sobie: ", "") logger.debug("Wywolanie obrazka: %s", message.content) - response = openai.Image.create( - prompt=message.content, n=1, size="1024x1024" - ) - image_url = response["data"][0]["url"] - logger.debug("Wynikowy obrazek pod url: %s", image_url) - response = requests.get(image_url, timeout=360) + try: + response = await openAIClient.images.generate( + model="dall-e-3", + prompt=message.content, + size="1024x1024", + quality="standard", + n=1, + ) + except openai.APITimeoutError as e: + # Handle timeout error, e.g. retry or log + await message.reply( + f"*Kondziu patrzy na terminal, czeka, czeka, czeka,.... Jeszcze chwile czeka Przypierdala w niego pięścią....* Nie mogę się połączyć z Openai spróbuj od nowa. *Na ekranie pojawia się*: {e}" + ) + except openai.APIConnectionError as e: + await message.reply( + f"*Kondziu patrzy na terminal, chwile się zastanawia. Przypierdala w niego pięścią....* Nie mogę się połączyć z Openai. *Na ekranie pojawia się*: {e}" + ) + except openai.BadRequestError as e: + # Handle invalid request error, e.g. validate parameters or log + if message.author.nick: + username = message.author.nick + else: + username = message.author.name + resp, _ = await handle_response( + f"Wytlumacz jakie sa zasady dotyczące treści które możesz generować używając Dalle. Wytłumacz błąd {e} prostym językiem. Przeproś za nadmierną cenzurę. Wytłumacz co mogło być nie tak w prompcie '{message.content}'", + True, + True, + MESSAGE_TABLE, + username, + "RANDOM", + ) + await message.reply( + f"Sorki, cenzura: {resp}. Jak chcesz to są kanały na nudle #sexy-foteczky i #kanal-do-fapania *Na ekranie pojawia się: {e}" + ) + except openai.AuthenticationError as e: + # Handle authentication error, e.g. check credentials or log + await message.reply( + f"*Kondziu patrzy na terminal, chwile się zastanawia. Przypierdala w niego pięścią....* Wołaj szefa - coś się z hasłem zjebało. *Na terminalu pojawia się:* {e}" + ) + except openai.PermissionDeniedError as e: + # Handle permission error, e.g. check scope or log + await message.reply( + ( + f"*Kondziu patrzy na terminal, chwile się zastanawia. Przypierdala w niego pięścią....* Wołaj szefa - coś się z uprawnieniami zjebało. *Na terminalu pojawia się:* {e}" + ) + ) + except openai.RateLimitError as e: + await message.reply( + f"*Kondziu patrzy na terminal* Wołaj szefa. Zapłacić rachunki za AI trzeba. Jak chcesz to się na #zebranie dorzuć. {e}" + ) + except openai.APIError as e: + # Handle API error, e.g. retry or log + await message.reply( + f"*Kondziu nurkuje za bar, terminal wybucha. Przed tobą ląduje pergamin zapisany pięknym gotykiem a na nim*: {e}" + ) + if response: + logger.info(response) + image_url = response.data[0].url + image_desc = response.data[0].revised_prompt + logger.debug("Wynikowy obrazek pod url: %s", image_url) + response = requests.get(image_url, timeout=360) - temp_file_name = message.content + ".png" - temp_file_name = GRAPHICS_PATH + message.content + ".png" + temp_file_name = message.content + ".png" + temp_file_name = GRAPHICS_PATH + message.content + ".png" - with open(temp_file_name, "wb") as dalle_file: - dalle_file.write(response.content) - logger.info("Koniec procedury obrazkowej.") - fnord = discord.File( - temp_file_name, spoiler=False, description=message.content - ) - await message.reply(file=fnord) + with open(temp_file_name, "wb") as dalle_file: + dalle_file.write(response.content) + logger.info("Koniec procedury obrazkowej.") + fnord = discord.File( + temp_file_name, spoiler=False, description=message.content + ) + await message.reply(f"{image_desc}", file=fnord) # *=========================================== Define Functions +def num_tokens_from_string(message, model): + """ + The function takes a string message and a model as input and returns the number of tokens in the + message according to the given model. + + :param message: A string containing the message or text from which you want to count the number of + tokens + :param model: The model parameter refers to a language model or tokenizer that can be used to + tokenize the input string. It could be a pre-trained model or a custom tokenizer + """ + tokens_per_message = 3 + tokens_per_name = 1 + chat_gpt_encoding = tiktoken.encoding_for_model(model) + + num_tokens = 0 + num_tokens += tokens_per_message + for keys, values in message.items(): + num_tokens += len(chat_gpt_encoding.encode(values)) + if keys == "role": + num_tokens += tokens_per_name + num_tokens += 3 # every reply is primed with <|start|>assistant<|message|> + return num_tokens + + async def connect(ctx, arg=None): """ Connect the bot to a voice channel if it is not already connected. @@ -400,12 +588,14 @@ async def play(ctx, zamawial=None, arg=None): await connect(ctx) if MUZYKA["queue"]: file_to_play = MUZYKA["queue"].pop() - zamawial = MUZYKA["requestor"].pop() + zamawial = MUZYKA["requester"].pop() + logger.info("Muzyka z listy zamówień") else: - index = random.randint(0, len(music_file_list) - 1) - file_to_play = music_file_list[index] + index = random.randint(0, len(music_file_list.get_file_list()) - 1) + file_to_play = music_file_list.get_file_list()[index] + logger.info("Muzyka losowo") - logger.debug(file_to_play) + logger.info(file_to_play) metadata = eyed3.load(file_to_play) query = None temp = file_to_play.split(SEPARATOR_FILE_PATH)[-1] @@ -447,99 +637,207 @@ async def play(ctx, zamawial=None, arg=None): username = ctx.message.author.name global MESSAGE_TABLE # pylint: disable=global-statement result, MESSAGE_TABLE = await handle_response( - query, vykidailo, bartender, message_table_muzyka, username, True + query, vykidailo, bartender, message_table_muzyka, username, "MUSIC" ) logger.debug("Obecna historia czatu: %s", message_table_muzyka) await ctx.send(result) async def archive_channel(channel_no): + """ + The function `archive_channel` retrieves messages from a specified channel, processes them, and + saves the data in a JSON file with a timestamp in the filename. + + :param channel_no: The `archive_channel` function you provided seems to be incomplete. It looks like + you are trying to archive messages from a Discord channel into a JSON file + """ channel = client.get_channel(channel_no) messages = [message async for message in channel.history(limit=None)] - path_newfile = ( - f"{LOGSTORE}channeldump_{channel_no}_{datetime.now()}.json" - ) + path_newfile = f"{LOGSTORE}channeldump_{channel_no}_{datetime.now()}.json" new_data = [] for message in messages: - pass + new_data.append(message) with open(path_newfile, "x", encoding=ENCODING) as new_file: new_file.seek(0) json.dump(new_data, new_file, indent=4) -async def check(): - """Funkcja sprawdzająca czy grać następny kawałek.""" - while True: - # TODO: Tu dołożyć skanowanie rozmiaru pliku logowania oraz plików pamięci i przenoszenie ich na większy dysk. - # trunk-ignore(codespell/misspelled) - # TODO: dlaczego sie tu wypierdala - if client.voice_clients: - voice_client = client.voice_clients[0] - if voice_client.is_connected(): - while MUZYKA["playing"] and voice_client.is_connected(): - if ( - voice_client - and not voice_client.is_playing() - and not voice_client.is_paused() - ): - await play(MUZYKA["ctx"], MUZYKA["requestor"]) - await asyncio.sleep(0.1) - if os.path.getsize(LOGFILE) > 600000: +@tasks.loop(seconds=1) +async def check_music(): + """ + This Python function continuously checks for music playback in a voice client and plays music if + conditions are met. + """ + if client.voice_clients: + voice_client = client.voice_clients[0] + if ( + voice_client + and voice_client.is_connected() + and not voice_client.is_playing() + and not voice_client.is_paused() + ): + await play(MUZYKA["ctx"], MUZYKA["requester"]) + await asyncio.sleep(2) + +@tasks.loop(seconds=3) +# trunk-ignore(pylint/R0915) +async def check_data_q(): + channel = client.get_channel(1062047367337095268) + try: + data = IN_COMM_Q.get(block=False) + await channel.send(f"O. A tak będzie wyglądało coś ciekawego w przyszłości: {data}") + except Empty: + pass + +@tasks.loop(seconds=120) +# trunk-ignore(pylint/R0915) +async def check_self(): + """ + The function `check_data` periodically checks for conditions to send messages and manage log files + in a Discord channel. + """ + # trunk-ignore(codespell/misspelled) + # logger.info("Heartbeat of cleanup proc") + channel = client.get_channel(1062047367337095268) + messages = [message async for message in channel.history(limit=1)] + for mess in messages: + channel = mess.channel + if os.path.getsize(LOGFILE) > 60000000: + await channel.send( + "*Conjurer porządkuje bar, wypala szklanki do czysta miotaczem płomieni ze swojej zbroi i ogólnie wygląda na zajętego....*" + ) + async with channel.typing(): shutil.copyfile(LOGFILE, f"{LOGSTORE}discord{datetime.now()}") logger.info("Log rollover") handler.doRollover() + await channel.send( + "*Przeciąga się za barem* No dobra - porobione to można dalej pi... *Zauważa spojrzenie Hammera* ...sać powieści o naszym wspaniałym barze SZEFIE!" + ) - if os.path.getsize(MEMORY_FIVE_MUZYKA) > 300000: - channel = client.get_channel(1062047571557744721) - await channel.send( - "*Conjurer porządkuje bar, wypala szklanki do czysta miotaczem płomieni ze swojej zbroi i ogólnie wygląda na zajętego....*" - ) - with channel.typing(): - path_newfile = ( - f"{LOGSTORE}{MEMORY_FIVE_MUZYKA[:-4]}{datetime.now()}.json" - ) - with open( - MEMORY_FIVE_MUZYKA, "r+", encoding=ENCODING - ) as file_music_memory: - with open(path_newfile, "x", encoding=ENCODING) as new_file: - # First we load existing data into a dict. - file_data = json.load(file_music_memory) - new_data = [] - new_data.append(file_data[0]) - new_data.extend(file_data[:-20]) - file_music_memory.seek(0) - # convert back to json. - new_file.seek(0) - json.dump(new_data, file_music_memory, indent=4) - json.dump(file_data, new_file, indent=4) - await channel.send( - "*Przeciąga się za barem* No dobra - porobione to można dalej pi... *Zauważa spojrzenie Hammera* ...sać powieści o naszym wspaniałym barze SZEFIE!" - ) - if os.path.getsize(MEMORY_FIVE_SIARA) > 300000: - path_newfile = "{LOGSTORE}{MEMORY_FIVE_SIARA[:-4]}{datetime.now()}.json" - await channel.send( - "*Conjurer porządkuje bar, ścina lekkim laserem pulsacyjnym powierzchnie baru o grubości kilku mikronów i ogólnie wygląda na zajętego....*" - ) - with open(MEMORY_FIVE_SIARA, "r+", encoding=ENCODING) as file: + if os.path.getsize(MEMORY_FIVE_MUZYKA) > 3000000: + await channel.send( + "*Conjurer porządkuje bar, wypala szklanki do czysta miotaczem płomieni ze swojej zbroi i ogólnie wygląda na zajętego....*" + ) + async with channel.typing(): + path_newfile = f"{LOGSTORE}pamiec_muzyki{datetime.now()}.json" + logger.info(path_newfile) + with open(MEMORY_FIVE_MUZYKA, "r+", encoding=ENCODING) as file_music_memory: with open(path_newfile, "x", encoding=ENCODING) as new_file: # First we load existing data into a dict. - file_data = json.load(file) + file_data = json.load(file_music_memory) new_data = [] new_data.append(file_data[0]) new_data.extend(file_data[:-20]) - file.seek(0) - new_file.seek(0) + file_music_memory.truncate(0) + file_music_memory.seek(0) # convert back to json. - json.dump(new_data, file, indent=4) + new_file.seek(0) + json.dump(new_data, file_music_memory, indent=4) json.dump(file_data, new_file, indent=4) await channel.send( - "*Przeciąga się za barem* No dobra - porobione to można dalej pi... *Zauważa spojrzenie Hammera* eprzyć o głupotach z klientami... Szefie... *Bierze 'ukradkowy' łyk z piersiówki*" + "*Przeciąga się za barem* No dobra - porobione to można dalej pi... *Zauważa spojrzenie Hammera* ...sać powieści o naszym wspaniałym barze SZEFIE!" ) - await asyncio.sleep(60) + if os.path.getsize(MEMORY_FIVE_SIARA) > 3000000: + path_newfile = f"{LOGSTORE}pamiec_rozmow{datetime.now()}.json" + logger.info(path_newfile) + await channel.send( + "*Conjurer porządkuje bar, ścina lekkim laserem pulsacyjnym powierzchnie baru o grubości kilku mikronów i ogólnie wygląda na zajętego....*" + ) + with open(MEMORY_FIVE_SIARA, "r+", encoding=ENCODING) as file: + with open(path_newfile, "x", encoding=ENCODING) as new_file: + # First we load existing data into a dict. + file_data = json.load(file) + new_data = [] + new_data.append(file_data[0]) + new_data.extend(file_data[-20]) + file.truncate(0) + file.seek(0) + new_file.seek(0) + # convert back to json. + json.dump(new_data, file, indent=4) + json.dump(file_data, new_file, indent=4) + await channel.send( + "*Przeciąga się za barem* No dobra - porobione to można dalej pi... *Zauważa spojrzenie Hammera* eprzyć o głupotach z klientami... Szefie... *Bierze 'ukradkowy' łyk z piersiówki*" + ) + # trunk-ignore(pylint/W0603) + global LAST_SPONTANEOUS_CALL + # trunk-ignore(pylint/W0603) + global TIME_BETWEEN_CALLS + tdelta = datetime.now() - LAST_SPONTANEOUS_CALL + tdelta = tdelta.total_seconds() + if tdelta > TIME_BETWEEN_CALLS: + logger.info("Spontaneous call") + TIME_BETWEEN_CALLS = random.randint( + 10200, 272800 + ) # temp random, set after each call + logger.debug(TIME_BETWEEN_CALLS) + LAST_SPONTANEOUS_CALL = datetime.now() + async with channel.typing(): + message = await get_random_cyclic_message() + logger.info("Odpowiedz") + logger.info(message) + await channel.send(message) +async def get_random_cyclic_message(): + """ + The function `get_random_cyclic_message` returns a random cyclic message from a list of cyclic + words. + :return: a random cyclic message from the list `cyclic_words`. + """ + channel_id = 1062047367337095268 + channel = client.get_channel(channel_id) + ai_check = random.randint(0, 10) + logger.info("Losowa wypowiedź") + if ai_check < 2: + logger.info("Predefiniowana") + messnum = random.randint(0, len(cyclic_words)) + logger.debug(messnum) + logger.debug(len(cyclic_words)) + mess_key = list(cyclic_words.keys())[messnum] + return cyclic_words[mess_key][0] + ai_check2 = random.randint(0, 10) + # trunk-ignore(pylint/W0603) + global MESSAGE_TABLE + if ai_check2 < 6: + logger.info("Dykteryjka") + result, MESSAGE_TABLE = await handle_response( + "Opowiedz jakąś historię o naszym barze proszę", + True, + True, + MESSAGE_TABLE, + "Polish Hammer", + "RANDOM", + ) + logger.info(result) + else: + logger.info("Wtracenie w dyskusje") + messages = [message async for message in channel.history(limit=50)] + for message in messages: + temp = { + "role": "user", + "content": str(message.author) + ":" + str(message.content), + } + MESSAGE_TABLE.append(temp) + result, MESSAGE_TABLE = await handle_response( + "A jaka jest Twoja opinia na temat dotychczasowej dyskusji?", + True, + True, + MESSAGE_TABLE, + "Polish Hammer", + "RANDOM", + ) + logger.info(result) + return result + + +# trunk-ignore(pylint/R0912) # trunk-ignore(pylint/R0913) -async def handle_response(prompt, vykidailo, bartender, history, username, music): +# trunk-ignore(pylint/R0914) +# trunk-ignore(pylint/R0915) +async def handle_response( + prompt, vykidailo, bartender, history, username, request_type +): """ Handle responses by appending them to a history, use OpenAI to generate a response, and then append the generated response to the history. @@ -562,7 +860,7 @@ async def handle_response(prompt, vykidailo, bartender, history, username, music if vykidailo or bartender: logger.info("Administrator coś chciał") history.append(temp) - if music: + if request_type == "MUSIC": with open(MEMORY_FIVE_MUZYKA, "r+", encoding=ENCODING) as file_music_memory: # First we load existing data into a dict. file_data = json.load(file_music_memory) @@ -571,6 +869,15 @@ async def handle_response(prompt, vykidailo, bartender, history, username, music file_music_memory.seek(0) # convert back to json. json.dump(file_data, file_music_memory, indent=4) + elif request_type == "RANDOM": + with open(MEMORY_FIVE_SIARA, "r+", encoding=ENCODING) as file_memory: + # First we load existing data into a dict. + file_data = json.load(file_memory) + # Join new_data with file_data inside emp_details + file_data.append(temp) + file_memory.seek(0) + # convert back to json. + json.dump(file_data, file_memory, indent=4) else: with open(MEMORY_FIVE_SIARA, "r+", encoding=ENCODING) as file_memory: # First we load existing data into a dict. @@ -581,22 +888,111 @@ async def handle_response(prompt, vykidailo, bartender, history, username, music # convert back to json. json.dump(file_data, file_memory, indent=4) history = [] - # * append bo pierwszy index - # * extend bo 20 ostatnich - if music: - history.append(message_table_muzyka[0]) - history.extend(message_table_muzyka[-15:]) - else: - history.append(MESSAGE_TABLE[0]) - history.extend(MESSAGE_TABLE[-15:]) - logger.info("Historia wysłana:") - logger.debug(history) - response = await openai.ChatCompletion.acreate( - model="gpt-4", messages=history + history.append(GPT_SETTINGS[0]) + chat_gpt_config_request_size = num_tokens_from_string(GPT_SETTINGS[0], "gpt-4") + + for slowo, reakcja in word_reactions.items(): + if not reakcja[3]: + content = ( + "Kiedy słyszysz " + + slowo + + " to reagujesz lub dzieje się to " + + reakcja[0] + ) + temp = {"role": "system", "content": content} + chat_gpt_config_request_size += num_tokens_from_string(temp, "gpt-4") + history.append(temp) + + final_prompt = username + ":" + prompt + logger.debug( + "Rozmiar zapytania przed dodaniem historii %s", chat_gpt_config_request_size ) - await asyncio.sleep(10) + if request_type == "MUSIC": + algorithm = "gpt-3.5-turbo-0125" + table = message_table_muzyka + token_amount = 10700 + elif request_type == "RANDOM": + algorithm = "gpt-3.5-turbo-0125" + table = MESSAGE_TABLE + token_amount = 10700 + else: + table = MESSAGE_TABLE + algorithm = "gpt-4" + token_amount = 7000 + + prompt_gpt_request_size = num_tokens_from_string( + {"role": "user", "content": final_prompt}, "gpt-4" + ) + temptable = [] + for i in reversed(table): + temp_token = num_tokens_from_string(i, "gpt-4") + logger.debug( + "Rozmiar zapytania %s prompt %s temp %s", + chat_gpt_config_request_size, + prompt_gpt_request_size, + temp_token, + ) + if ( + chat_gpt_config_request_size + < token_amount + prompt_gpt_request_size + temp_token + ): + temptable.insert(1, i) + chat_gpt_config_request_size += temp_token + history.extend(temptable) + temp = {"role": "user", "content": final_prompt} + history.append(temp) + logger.info("Rozmiar zapytania po wyslaniu %s", chat_gpt_config_request_size) + try: + response = await openAIClient.chat.completions.create( + model=algorithm, messages=history + ) + except openai.APITimeoutError as e: + # Handle timeout error, e.g. retry or log + result = f"*Kondziu patrzy na terminal, czeka, czeka, czeka,.... Jeszcze chwile czeka Przypierdala w niego pięścią....* Nie mogę się połączyć z Openai spróbuj od nowa. *Na ekranie pojawia się*: {e}" + except openai.APIConnectionError as e: + result = f"*Kondziu patrzy na terminal, chwile się zastanawia. Przypierdala w niego pięścią....* Nie mogę się połączyć z Openai. *Na ekranie pojawia się*: {e}" + except openai.BadRequestError as e: + # Handle invalid request error, e.g. validate parameters or log + resp, _ = await handle_response( + f"Wytlumacz jakie sa zasady dotyczące treści które możesz generować używając Dalle. Wytłumacz błąd {e} prostym językiem. Przeproś za nadmierną cenzurę. Wytłumacz co mogło być nie tak w prompcie 'prompt'", + True, + True, + MESSAGE_TABLE, + username, + "RANDOM", + ) + result = f"Sorki, cenzura: {resp}. Jak chcesz to są kanały na nudle #sexy-foteczky i #kanal-do-fapania *Na ekranie pojawia się: {e}" + except openai.APIResponseValidationError as e: + # Handle invalid request error, e.g. validate parameters or log + resp, _ = await handle_response( + f"Wytlumacz jakie sa zasady dotyczące treści które możesz generować używając Dalle. Wytłumacz błąd {e} prostym językiem. Przeproś za nadmierną cenzurę. Wytłumacz co mogło być nie tak w prompcie 'prompt'", + True, + True, + MESSAGE_TABLE, + username, + "RANDOM", + ) + result = f"Sorki, cenzura: {resp}. Jak chcesz to są kanały na nudle #sexy-foteczky i #kanal-do-fapania *Na ekranie pojawia się: {e}" + except openai.AuthenticationError as e: + # Handle authentication error, e.g. check credentials or log + result = f"*Kondziu patrzy na terminal, chwile się zastanawia. Przypierdala w niego pięścią....* Wołaj szefa - coś się z hasłem zjebało. *Na terminalu pojawia się:* {e}" + except openai.PermissionDeniedError as e: + # Handle permission error, e.g. check scope or log + result = f"*Kondziu patrzy na terminal, chwile się zastanawia. Przypierdala w niego pięścią....* Wołaj szefa - coś się z uprawnieniami zjebało. *Na terminalu pojawia się:* {e}" + except openai.RateLimitError as e: + result = f"*Kondziu patrzy na terminal* Wołaj szefa. Zapłacić rachunki za AI trzeba. Jak chcesz to się na #zebranie dorzuć. {e}" + except openai.UnprocessableEntityError as e: + result = f"*Kondziu patrzy na terminal. Potem na to co każesz mu wysłać....* Ja wiem że jesteśmy w barze BDSM - ale nie da się włożyć TEGO w TO. *Za jego plecami na terminalu pojawia się:* {e}" + except openai.APIError as e: + # Handle API error, e.g. retry or log + result = f"*Kondziu nurkuje za bar, terminal wybucha. Przed tobą ląduje pergamin zapisany pięknym gotykiem a na nim*: {e}" + + logger.info("Historia wysłana:") + logger.info(history) + await asyncio.sleep(15) result = "" logger.debug("Odpowiedzi") + logger.info(response) logger.debug(response.choices) for choice in response.choices: result += choice.message.content @@ -604,7 +1000,7 @@ async def handle_response(prompt, vykidailo, bartender, history, username, music logger.info(result) temp = {"role": "assistant", "content": result} history.append(temp) - if music: + if request_type: with open(MEMORY_FIVE_MUZYKA, "r+", encoding=ENCODING) as file: # First we load existing data into a dict. file_data = json.load(file) @@ -627,8 +1023,8 @@ async def handle_response(prompt, vykidailo, bartender, history, username, music return result, MESSAGE_TABLE -# trunk-ignore(pylint/R0914) # trunk-ignore(pylint/R0915) +# trunk-ignore(pylint/R0914) async def get_file(ctx, source, link): """ Take in three parameters: "ctx" (context), @@ -646,14 +1042,13 @@ async def get_file(ctx, source, link): """ item_id = None item_type = None - file_list = {} + file_list = [] if source == "Spotify": dir_path = None item_type, item_id = spotify.parse_spotify_url(link) if item_id: file_list = spotify.fetch_tracks(spotify_ctrl, item_type, link) - directory_name = spotify.get_item_name( - spotify_ctrl, item_type, item_id) + directory_name = spotify.get_item_name(spotify_ctrl, item_type, item_id) url_data = {"urls": []} url_dict = {} url_dict["save_path"] = Path( @@ -663,7 +1058,8 @@ async def get_file(ctx, source, link): url_dict["songs"] = file_list url_data["urls"].append(url_dict.copy()) file_name_f = youtube_download.default_filename - coro = asyncio.to_thread(youtube_download.download_songs, + coro = asyncio.to_thread( + youtube_download.download_songs, songs=url_data, output_dir=MUSIC_FOLDER, format_str="bestaudio/best", @@ -707,7 +1103,7 @@ async def get_file(ctx, source, link): "force_keyframes": True, }, ] - #TODO: Make sponsorblock work + # TODO: Make sponsorblock work sponsorblock_postprocessor = [] if platform == "win32": dir_path = "G:\\Muzyka\\Youtube" @@ -717,6 +1113,7 @@ async def get_file(ctx, source, link): "proxy": "", "default_search": "ytsearch", "format": "bestaudio/best", + "postprocessors": sponsorblock_postprocessor, "noplaylist": True, "no_color": False, "paths": {"home": dir_path}, @@ -785,6 +1182,7 @@ async def get_file(ctx, source, link): file_list.append("wiadomo co wiadomo gdzie") return dir_path, file_list + # define an asynchronous generator async def async_iterator_generator(range_of_iterable): """ @@ -845,9 +1243,9 @@ async def get_stats(ctx, history_limit): yield name, how_many -# trunk-ignore(pylint/R0914) # trunk-ignore(pylint/R0915) # trunk-ignore(pylint/R0912) +# trunk-ignore(pylint/R0914) async def wyszukaj(ctx, how_many=0, slowa_kluczowe=None): """ Take in a context object and an optional integer parameter "how_many" and perform search @@ -860,98 +1258,41 @@ async def wyszukaj(ctx, how_many=0, slowa_kluczowe=None): It is an optional parameter with a default value of 0, which means that if no value is provided for how_many, the function will return all search results, defaults to 0 (optional) """ - #TODO: Przerobić na webservice # i sieć neuronową z możliwością wyrażenia opinii o dopasowaniu. if slowa_kluczowe: word_list = slowa_kluczowe else: word_list = ctx.message.content.split() logger.info("Wyszukuje") - search_weight = [] - for _ in range(len(music_file_list)): - search_weight.append((0, "")) + jrequest = { + "lista_slow": word_list, + "dlugosc_plejlisty": how_many, + "UUID": str(uuid.uuid4()), + } + coroutine = asyncio.to_thread( + requests.post, + f"{FILE_SERVICE_ADDRESS}{GET_PLAYLIST}", + json=jrequest, + timeout=360, + ) + return_data = await coroutine + if not return_data.status_code == 200: + await ctx.send("Wołaj szefa - coś się wyjebało") + return + logger.info(return_data.json()["data"]) + return return_data.json()["data"] - time_start = datetime.now() - if int(how_many) > 0: - skip_start = 2 - else: - skip_start = 1 - async for word in async_iterator_generator(word_list[skip_start:]): - token_weight = len(word) - logger.info("Słowo kluczowe: %s", word) - itr = 0 - async for file in async_iterator_generator(music_file_list): - file = file.split(SEPARATOR_FILE_PATH) - char_remove = [ - ".", - "^", - "$", - "*", - "+", - "?", - "{", - "}", - "[", - "]", - "\\", - "/", - "|", - "(", - ")", - "!", - ",", - "-", - ":", - "mp3", - ] - all_words = [] - async for f_iter in async_iterator_generator(file): - async for char in async_iterator_generator(char_remove): - f_iter = f_iter.replace(char, "") - tmp = f_iter.split() - all_words.extend(tmp) - pingu = 1 - pattern_len = len(all_words) - if platform == "win32": - skip = 2 - else: - skip = 4 - matched_times = 1 - async for itm in async_iterator_generator(all_words[skip:]): - pingu += 1 - pattern = ".*" + word + ".*" - if re.match(pattern, itm, re.IGNORECASE): - temp_weight = ( - search_weight[itr][0] - + (token_weight + (pingu**1.5) / - pattern_len) / matched_times - ) - search_weight[itr] = temp_weight, music_file_list[itr] - matched_times += 1 - itr += 1 +async def remove_characters(string, character): + """ + The `remove_characters` function removes all occurrences of a specified character from a given + string. - logger.info("Stworzylem tablice wag zajęło mi to %s", - datetime.now() - time_start) - time_start = datetime.now() - item_to_search = await max_weight(search_weight) - itr = 0 - if item_to_search == 0: - return None - not_found = True - return_list = [] - if int(how_many) <= 0: - logger.info("Jeden plik do zagrania") - while not_found: - if search_weight[itr][0] == item_to_search: - return_list.append(search_weight[itr]) - return return_list - itr += 1 - else: - logger.info("Wiele plików do zagrania") - search_weight.sort(key=lambda x: x[0], reverse=True) - return_list.extend(search_weight[: int(how_many)]) - return return_list + :param string: The string parameter is the input string from which characters will be removed + :param character: The character parameter is the character that you want to remove from the string + :return: a new string where all occurrences of the specified character have been removed. + """ + return string.replace(character, "") async def max_weight(lista): @@ -973,7 +1314,6 @@ async def max_weight(lista): # *=========================================== Define Commands -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="dej_co_ze_spotifaja", description="Podaj link do spotify - sciagnie i doda muzyke", @@ -1001,6 +1341,14 @@ async def dej_co_ze_spotifaja(ctx): else: separator = "/" for file in files: + file_path = ( + dir_path + + separator + + file["artist"] + + " - " + + file["name"] + + ".mp3" + ) global MUZYKA # pylint: disable=global-variable-not-assigned MUZYKA["queue"].insert( 0, @@ -1011,15 +1359,14 @@ async def dej_co_ze_spotifaja(ctx): + file["name"] + ".mp3", ) - MUZYKA["requestor"].insert(0, ctx.author) - music_file_list.append(file) + MUZYKA["requester"].insert(0, ctx.author) + music_file_list.update_file_list(file_path) await ctx.send( f"Dodałem do listy {dir_path}{file['artist']} - + {file['name']}.mp3" ) logger.info("Spotifaj udany") -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="dej_co_z_jutuba", description="Podaj link do youtube - sciagnie i doda muzyke", @@ -1046,13 +1393,12 @@ async def dej_co_z_jutuba(ctx): for file_iter in files: global MUZYKA # pylint: disable=global-variable-not-assigned MUZYKA["queue"].insert(0, file_iter) - music_file_list.append(file_iter) - MUZYKA["requestor"].insert(0, ctx.author) + music_file_list.update_file_list(file_iter) + MUZYKA["requester"].insert(0, ctx.author) await ctx.send(f"Dodałem do listy {file_iter}") logger.info("Jutub udany") -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="update_banlist", description="Jeśli nie wiesz jak użyć tej komendy to nawet nie próbuj", @@ -1092,7 +1438,7 @@ async def update_banlist(ctx): for line in lines: match = re.search( "\\d{18}", - line + line, # trunk-ignore(codespell/misspelled) ) # poprawilem backslash na podwojny bo linter sie czepial if match: @@ -1143,7 +1489,6 @@ async def update_banlist(ctx): await ctx.send("Zrobione tak czy inaczej") -# trunk-ignore(mypy/arg-type) @client.hybrid_command( nsfw=True, name="get_image_sadox", @@ -1188,7 +1533,6 @@ async def get_image_sadox(ctx): logger.info("Get sadox completed") -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="graj_muzyko", description="Włącza muzykę na kanale #nocna-zmiana.", @@ -1207,14 +1551,13 @@ async def graj_muzyko(ctx): logger.info("Press play on tape") async with ctx.typing(): global MUZYKA # pylint: disable=global-variable-not-assigned - MUZYKA["playing"] = True MUZYKA["ctx"] = ctx await connect(ctx=ctx) await play(ctx=ctx) logger.info("Press play on tape completed") + check_music.start() -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="cisza", description="Wyłącza muzykę i czyści plejliste.", @@ -1231,18 +1574,17 @@ async def cisza(ctx): """ logger.info("Stop") global MUZYKA # pylint: disable=global-variable-not-assigned - MUZYKA["playing"] = False MUZYKA["ctx"] = None voice_client = client.voice_clients[0] + check_music.stop() if voice_client.is_connected(): await disconnect(ctx=ctx) while MUZYKA["queue"]: MUZYKA["queue"].pop() - MUZYKA["requestor"].pop() + MUZYKA["requester"].pop() logger.info("Stop completed") -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="dalej", description="Przerzuca na następny kawałek", @@ -1263,11 +1605,9 @@ async def dalej(ctx): voice_client = client.voice_clients[0] if voice_client.is_connected(): voice_client.stop() - await play(ctx=ctx) logger.info("Next completed") -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="daj_mi_chwile", description="Pauzuje", @@ -1292,7 +1632,6 @@ async def daj_mi_chwile(ctx): logger.info("Pause completed") -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="graj_dalej", description="Odpauzowuje", @@ -1316,7 +1655,6 @@ async def graj_dalej(ctx): logger.info("Unpause completed") -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="zagraj_mi_kawalek", description="Wyszukuje w bibliotece muzycznej Hammera kawałek który ma zostać zagrany", @@ -1346,7 +1684,7 @@ async def zagraj_mi_kawalek(ctx): for plik in file: global MUZYKA # pylint: disable=global-variable-not-assigned MUZYKA["queue"].insert(0, plik[1]) - MUZYKA["requestor"].insert(0, ctx.author) + MUZYKA["requester"].insert(0, ctx.author) metadata = eyed3.load(plik[1]) reply = "Dodałem do playlisty {plik[1]} z prywatnej kolekcji Hammera." if metadata.tag.title: @@ -1363,7 +1701,6 @@ async def zagraj_mi_kawalek(ctx): ) -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="zrob_mi_plejliste", description="Generuje playliste - param1 - dlugosc, potem slowa wyszukiwania", @@ -1394,29 +1731,31 @@ async def zrob_mi_plejliste(ctx): index = 1 if file: for plik in file: - global MUZYKA # pylint: disable=global-variable-not-assigned - MUZYKA["queue"].insert(0, plik[1]) - MUZYKA["requestor"].insert(0, ctx.author) - metadata = eyed3.load(plik[1]) - if metadata and metadata.tag: - if metadata.tag.title: - reply += f"{index} {metadata.tag.title}" + if plik[1]: + logger.info(plik) + global MUZYKA # pylint: disable=global-variable-not-assigned + MUZYKA["queue"].insert(0, plik[1]) + MUZYKA["requester"].insert(0, ctx.author) + metadata = eyed3.load(plik[1]) + if metadata and metadata.tag: + if metadata.tag.title: + reply += f"{index} {metadata.tag.title}" + else: + reply += f"{index}. {plik[1]} z prywatnej kolekcji Hammera." + + if metadata.tag.artist: + reply += f" wykonawcy {metadata.tag.artist}" + if metadata.tag.album: + reply += f" z albumu {metadata.tag.album}" + if metadata.tag.title: + reply += " z prywatnej kolekcji Hammera i na Twoją specjalną rpośbę.\n" else: - reply += f"{index}. {plik[1]} z prywatnej kolekcji Hammera." + reply += f"{index}. {plik[1]} z prywatnej kolekcji Hammera.\n" - if metadata.tag.artist: - reply += f" wykonawcy {metadata.tag.artist}" - if metadata.tag.album: - reply += f" z albumu {metadata.tag.album}" - if metadata.tag.title: - reply += " z prywatnej kolekcji Hammera i na Twoją specjalną rpośbę.\n" - else: - reply += f"{index}. {plik[1]} z prywatnej kolekcji Hammera." - - index += 1 - if len(reply) > 1800: - await ctx.send(reply) - reply = "" + index += 1 + if len(reply) > 1800: + await ctx.send(reply) + reply = "" else: await ctx.send( "Obawiam się że nie mogę nic znaleźć u siebie. Spróbuj komendy '$dej_co_ze_spotifaja' jeśli masz link" @@ -1425,7 +1764,6 @@ async def zrob_mi_plejliste(ctx): logger.info("Plejlista zrobiona") -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="przytul", description="Przytul kogoś - daj mention po komendzie :)" ) @@ -1462,7 +1800,6 @@ async def przytul(ctx, arg: Optional[discord.Member] = None): ) -# trunk-ignore(mypy/arg-type) @client.hybrid_command(name="fabryczka", description="Historia fabryczki") async def fabryczka(ctx): """ @@ -1476,7 +1813,6 @@ async def fabryczka(ctx): await ctx.send(historia_fabryczki) -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="chata_hammera", description="Czas od ostatniego incydentu w AbsinthHammerTimeSpaceContinuum", @@ -1500,7 +1836,6 @@ async def chata_hammera(ctx): ) -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="historia_incydentow_u_hammera", description="Wyswietla liste incydentów które miały miejsce w AbsinthHammerTimeSpaceContinuum.", @@ -1528,7 +1863,6 @@ async def historia_incydentow_u_hammera(ctx): await ctx.send(return_data) -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="reset_the_clock", description="Resetowanie zegara - dostępne wyłącznie dla Hammera", @@ -1581,13 +1915,13 @@ async def get_image_stable_diffusion(ctx): pass -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="zagraj_muzyke_mego_ludu", description="Gra muzyke wyszukana na bazie tematow konwersacji na kanale NZ", guild=discord.Object(id=664789470779932693), ) # trunk-ignore(pylint/R0912) +# trunk-ignore(pylint/R0915) async def zagraj_muzyke_mego_ludu(ctx): """ Play completeley random playlist based on messaging history. @@ -1599,24 +1933,39 @@ async def zagraj_muzyke_mego_ludu(ctx): """ stats = {} if ctx: + logger.info("Zagraj muzyke mego ludu: wywolane") stat_iter = get_stats(ctx, MUZYKA_MOJEGO_LUDU_HISTORIA) async for name, how_many in stat_iter: if len(name) > 3: stats[name] = how_many sorted_stats = sorted(stats.items(), key=lambda x: x[1]) + logger.info("Zagraj muzyke mego ludu:zebrano statystyki") key_words = [] for stat in sorted_stats: key_words.append(stat[0]) - logger.info(sorted_stats[:30]) - logger.info(key_words[:30]) + logger.info(sorted_stats[:MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE]) + logger.info(key_words[:MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE]) + logger.info(sorted_stats[-MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE:]) + logger.info(key_words[-MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE:]) + + final_key_words = key_words[:MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE] + final_key_words.extend(key_words[-MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE:]) reply = "Wygenerowana plejlista:\n" async with ctx.typing(): - logger.info("Zaczynam szukać timestamp %s", datetime.now()) - search_time_glob = datetime.now() - file = await wyszukaj(ctx=ctx, how_many=MUZYKA_MOJEGO_LUDU_PLAJLISTA, slowa_kluczowe=key_words[:MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE]) logger.info( - "Koniec szukania(timestamp %s zajęło %s", + "Zagraj muzyke mego ludu:Zaczynam szukać timestamp %s", datetime.now() + ) + search_time_glob = datetime.now() + file = await wyszukaj( + ctx=ctx, + how_many=MUZYKA_MOJEGO_LUDU_PLAJLISTA, + slowa_kluczowe=final_key_words, + ) + logger.info("Zagraj muzyke mego ludu:wygenerowano plejliste") + logger.info(file) + logger.info( + "Zagraj muzyke mego ludu: Koniec szukania(timestamp %s zajęło %s", datetime.now(), datetime.now() - search_time_glob, ) @@ -1625,7 +1974,7 @@ async def zagraj_muzyke_mego_ludu(ctx): for plik in file: global MUZYKA # pylint: disable=global-variable-not-assigned MUZYKA["queue"].insert(0, plik[1]) - MUZYKA["requestor"].insert(0, ctx.author) + MUZYKA["requester"].insert(0, ctx.author) metadata = eyed3.load(plik[1]) if metadata and metadata.tag: if metadata.tag.title: @@ -1640,7 +1989,7 @@ async def zagraj_muzyke_mego_ludu(ctx): if metadata.tag.title: reply += " z prywatnej kolekcji Hammera i na Twoją specjalną rpośbę.\n" else: - reply += f"{index}. {plik[1]} z prywatnej kolekcji Hammera." + reply += f"{index}. {plik[1]} z prywatnej kolekcji Hammera.\n" index += 1 if len(reply) > 1800: @@ -1654,13 +2003,14 @@ async def zagraj_muzyke_mego_ludu(ctx): logger.info("Plejlista zrobiona") -# trunk-ignore(mypy/arg-type) @client.hybrid_command( name="parametry_muzyki_mego_ludu", description="Konfiguruje komende zagraj muzyke mojego ludu", guild=discord.Object(id=664789470779932693), ) -async def parametry_muzyki_mego_ludu(ctx, ile_historii=1500, ile_slow_kluczowych=30, jak_dluga_plejlista=30): +async def parametry_muzyki_mego_ludu( + ctx, ile_historii=1500, ile_slow_kluczowych=15, jak_dluga_plejlista=30 +): """ The function `parametry_muzyki_mego_ludu` sets global variables for the number of history entries, number of keywords, and length of playlist for a music application. @@ -1678,12 +2028,163 @@ async def parametry_muzyki_mego_ludu(ctx, ile_historii=1500, ile_slow_kluczowych """ if ctx: - global MUZYKA_MOJEGO_LUDU_HISTORIA # pylint: disable=global-statement - MUZYKA_MOJEGO_LUDU_HISTORIA = ile_historii - global MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE # pylint: disable=global-statement - MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE = ile_slow_kluczowych - global MUZYKA_MOJEGO_LUDU_PLAJLISTA # pylint: disable=global-statement - MUZYKA_MOJEGO_LUDU_PLAJLISTA = jak_dluga_plejlista + async with ctx.typing(): + # if ':' in ile_historii: + # _, _, ile_historii = ile_historii.partition(':') + # if ':' in ile_slow_kluczowych: + # _, _, ile_slow_kluczowych = ile_slow_kluczowych.partition(':') + # if ':' in jak_dluga_plejlista: + # _, _, jak_dluga_plejlista = jak_dluga_plejlista.partition(':') + try: + global MUZYKA_MOJEGO_LUDU_HISTORIA # pylint: disable=global-statement + global MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE # pylint: disable=global-statement + global MUZYKA_MOJEGO_LUDU_PLAJLISTA # pylint: disable=global-statement + logger.info( + "Długość historii wyszukiwania: %s\n Ilość słów kluczowych: %s\n Długość plejlisty do wygenerowanie: %s", + MUZYKA_MOJEGO_LUDU_HISTORIA, + MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE, + MUZYKA_MOJEGO_LUDU_PLAJLISTA, + ) + ctx.send( + f"Dotychczasowe wartośći:\n Długość historii wyszukiwania: {MUZYKA_MOJEGO_LUDU_HISTORIA}\n Ilość słów kluczowych: {MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE}\n Długość plejlisty do wygenerowanie:{MUZYKA_MOJEGO_LUDU_PLAJLISTA}" + ) + MUZYKA_MOJEGO_LUDU_HISTORIA = ile_historii + MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE = ile_slow_kluczowych + MUZYKA_MOJEGO_LUDU_PLAJLISTA = jak_dluga_plejlista + logger.info( + "Długość historii wyszukiwania: %s\n Ilość słów kluczowych: %s\n Długość plejlisty do wygenerowanie: %s", + MUZYKA_MOJEGO_LUDU_HISTORIA, + MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE, + MUZYKA_MOJEGO_LUDU_PLAJLISTA, + ) + ctx.send( + f"Zmienione wartośći:\n Długość historii wyszukiwania: {MUZYKA_MOJEGO_LUDU_HISTORIA}\n Ilość słów kluczowych: {MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE}\n Długość plejlisty do wygenerowanie:{MUZYKA_MOJEGO_LUDU_PLAJLISTA}" + ) + except discord.ext.commands.errors.BadArgument as exce: + ctx.send("Spierdalaj") + logger.info(exce) + + +class DoSearchView(discord.ui.View): + def __init__(self, uuid, result_list, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.uuid = uuid + self.result_list = result_list + + @discord.ui.button( + label="Nastepna strona", style=discord.ButtonStyle.primary, row=0 + ) + async def next_callback(self, interaction, button): + # emoji = await ctx.guild.fetch_emoji(id) + # button.emoji=1102174413887111189 + logger.info("Pressed") + await interaction.response.edit_message( + content="You clicked the button!" + ) # Send a message when the button is clicked + + @discord.ui.button(label="Wyszukaj wiecej", style=discord.ButtonStyle.danger, row=0) + async def reset_callback(self, interaction, button): + # emoji = await ctx.guild.fetch_emoji(id) + # button.emoji=1102174413887111189 + logger.info("Pressed") + await interaction.response.edit_message( + content="You clicked the button!" + ) # Send a message when the button is clicked + + @discord.ui.button( + label="Poprzednia Strona", style=discord.ButtonStyle.primary, row=0 + ) + async def perv_callback(self, interaction, button): + # emoji = await ctx.guild.fetch_emoji(id) + # button.emoji=1102174413887111189 + logger.info("Pressed") + await interaction.response.edit_message( + content="You clicked the button!" + ) # Send a message when the button is clicked + + +@client.hybrid_command( + name="wyszukaj_linki_do_dokumentow", + description="Szuka linkow doi w bazie crossref i podaje linki do scihuba", + guild=discord.Object(id=664789470779932693), +) +async def wyszukaj_linki_do_dokumentow(ctx): + query = ctx.message.content + query_uuid = uuid.uuid4() + # query_uuid = "test" + # 3 wyslij Librariana + json_query = {"UUID": str(query_uuid), "query": str(query)[30:], "page": 1} + coroutine = asyncio.to_thread( + requests.post, + f"{LIBRARIAN_SERVICE_ADDRESS}{SEND_QUERY}", + json=json_query, + timeout=360, + ) + await ctx.send( + "*Conjurer powoli notuje podane przez Ciebie. Podchodzi do sprytnie ukrytej przy barze rury od poczty pneumatycznej i" + + " wrzuca twój liścik do środka* To teraz trza poczekać kilka godzin. Biblioteka to te 3/4 stacji."+ + " A przecież pół stacji to browar, motelik dla zabaw cielesnych i ten Bar. Więc te 12/8 stacji teraz będzie ciężko pracować" + ) + query_response = await coroutine + if not query_response.status_code == 200: + await ctx.send("*Z rury wydobywa się dym. Conjurer łapie pierwszą ciecz pod ręką i pryska na rurę. Następuje drobna eksplozja i wszystko zaczyna się palić."+ + " Conjurer jest skonfundowany..* Wołaj szefa - mam nieodparte wrażenie że się coś wyjebało") + return + + query, query_uuid, queue_size = ( + query_response.json()["data"][0], + query_response.json()["data"][1], + query_response.json()["data"][2], + ) + if ctx.message.author.nick: + username = ctx.message.author.nick + else: + username = ctx.message.author.name + query_object = QueryControl(username, query_uuid, query, logger, ctx) + OUT_COMM_Q.put(query_object) + await ctx.send(f"No dobra poszło. Zapamiętaj proszę {query_uuid} - to identyfikator twojego zapytania. Jesteś {queue_size} w kolejce."+ + " Zapytania obsługuje algorytm zasilany czterema chomikami zapierdalającymi w kołowrotku - więc wyniki najwcześniej za kilka godzi - ale mogą być też dni.") + +''' +async def wyswietl_wyniki_wyszukiwania(ctx): + + # 4 zwroc 4 wyniki od librariana + # 5 przyciski przy każdym wierszu pozwalają sprawdzić czy plik istnieje na scihubie - jeśli tak podaje link do sciagniecia + # 6 ostatni wiersz to dalej, wróć, skasuj, zaciagnij kolejne wyniki (jeśli jest ich więcej niż 1000) + result_view = DoSearchView( + uuid=str(query_uuid), result_list=query_response.json()["data"] + ) + resulttab = [] + resultlink = [] + hit, fetched, total, _ = query_response.json()["data"][0] + answer = query_response.json()["data"][1] + + for item in answer: + resulttab.append(str(item["title"])) + item_link = "https://sci-hub.se/" + str(item["DOI"]) + resultlink.append(item_link) + logger.info(len(resulttab)) + for i in range(0, min(4, len(resulttab))): + logger.info(i) + logger.info(resulttab[i]) + logger.info(resultlink[i]) + url = resultlink[i] + logger.info(url) + temp_label = str(resulttab[i]) + temp_label = temp_label.strip("[']") + result_view.add_item( + discord.ui.Button(label=str(temp_label[0:79]), row=i + 1, url=url) + ) + + labelka = ( + "Wyniki wyszukiwania dla: " + + str(query)[30:] + + f"\nWszystkich {total} sprawdzonych: {fetched} znalezionych: {hit} " + ) # ile znaleziono artykułów w ogóle, ile zostało po refine + await ctx.send( + labelka, view=result_view + ) # Send a message with our View class that contains the button +''' @client.hybrid_command( name="krecimy_pornola", @@ -1721,5 +2222,29 @@ async def krecimy_pornola(ctx): # *================================== Run -# trunk-ignore(mypy/arg-type) -client.run(TOKEN) +if __name__ == "__main__": + # TODO: wpakowac kondzia w wątki odpalic asynchronicznie rownolegle z flaskiem do sterowania nim + logger.info("Starting discord bot") + threads = [] + logger.info("Starting discord bot: Creating threads") + threads.append(threading.Thread(target=client.run, args=(TOKEN,))) + threads.append(threading.Thread(target=comm_subroutine, args=(logger,))) + logger.info("Starting discord bot: Starting threads") + i = 0 + for worker in threads: + i+=1 + logger.info("Starting discord bot: Starting thread {i}") + worker.start() + logger.info("Starting discord bot: Joining threads") + i=0 + for worker in threads: + i+=1 + logger.info("Starting discord bot: Joining thread {i}") + worker.join() + +# widok - generuje się 5 stron po 4 linki +# odśwież - zamienić na "dalej" - zaciąga kolejne 20 rezultatów +# po wyslaniu czekamy na odbior i dodajemy UUID oraz nick poszukiwacza do queue ktora jest sprawdzana +# flask sobie chodzi i jak dostaje posta z wynikami to wyciaga z queue UUID i odpowiada że znalazła +# po samym wyszukaniu dajemy info że "Zaczynam szukać ale pare godzin to potrwa." +# OPCJONALNIE: Dosyłamy znalezione wyniki na bieżąco - wtedy wkładamy do queue dla UUID wyniki diff --git a/file_webservice/conjurer_musician.py b/file_webservice/conjurer_musician.py index c824bce..2b12709 100644 --- a/file_webservice/conjurer_musician.py +++ b/file_webservice/conjurer_musician.py @@ -258,9 +258,6 @@ def waitress_run(): """ serve(app, host=HOST_ADDRESS, port=PORT_ADDRESS) -def waitress_run(): - serve(app, host="0.0.0.0", port=5000) - if __name__ == "__main__": logger = logging.getLogger('conjurer_musician') logger.setLevel(logging.DEBUG)