diff --git a/bot.py b/bot.py index 3b3f386..d75113f 100644 --- a/bot.py +++ b/bot.py @@ -24,7 +24,7 @@ from logging import handlers from pathlib import Path, PurePath from platform import uname from sys import platform -from typing import List, TypedDict, Union +from typing import List, Optional, TypedDict # *==============Imported libraries import discord @@ -42,24 +42,23 @@ import yt_dlp from spotify_dl import spotify from spotify_dl import youtube as youtube_download -Movie = TypedDict("Movie", {"name": str, "year": int}) -movie: Movie = {"name": "Blade Runner", "year": 1982} - Music_Config = TypedDict( "Music_Config", { "playing": bool, - "ctx": Union[str, None], + "ctx": Optional[str], "queue": List[str], "requestor": List[str], }, ) # *=========================================== Predefines -formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") -master_timeout = datetime.now() +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": []} +MUZYKA: Music_Config = {"playing": False, + "ctx": None, "queue": [], "requestor": []} LOGFILE = "" NETRC_FILE = "" @@ -70,18 +69,22 @@ SETTINGS_FILE = "" ENCODING = "" GRAPHICS_PATH = "" # *=========================================== Platform Specific Predefines + if platform in ("linux", "linux2"): + SEPARATOR_FILE_PATH = "/" if "microsoft-standard" in uname().release: - LOGFILE = "/home/pi/Conjurer/discord.log" - MEMORY_FIVE_SIARA = "/home/pi/Conjurer/pamiec.json" - MEMORY_FIVE_MUZYKA = "/home/pi/Conjurer/pamiec_muzyki.json" - MUSIC_FOLDER = "/home/pi/RetroPie/mp3/" - SETTINGS_FILE = "/home/pi/Conjurer/settings.json" - NETRC_FILE = "/home/pi/netrc" - LOGSTORE = "/home/pi/RetroPie/logs/" - ACCIDENT_LOG = "/home/pi/Conjurer/accident_log.json" + LOGFILE = "/home/mtuszowski/conjurer/discord.log" + MEMORY_FIVE_SIARA = "/home/mtuszowski/conjurer/pamiec.json" + MEMORY_FIVE_MUZYKA = "/home/mtuszowski/conjurer/pamiec_muzyki.json" + MUSIC_FOLDER = "/mnt/g/Muzyka/" + SETTINGS_FILE = "/home/mtuszowski/conjurer/settings.json" + NETRC_FILE = "/home/mtuszowski/.netrc" + LOGSTORE = "/home/mtuszowski/conjurer/logs/" + ACCIDENT_LOG = "/home/mtuszowski/conjurer/accident_log.json" ENCODING = "utf-8" - GRAPHICS_PATH = "/home/pi/RetroPie/Conjurer_graphics/" + GRAPHICS_PATH = "/home/mtuszowski/conjurer/Conjurer_graphics/" + DIR_PATH_SADOX = "/mnt/c/Users/mtusz/OneDrive/Dokumenty/Fansadox" + else: LOGFILE = "/home/pi/Conjurer/discord.log" MEMORY_FIVE_SIARA = "/home/pi/Conjurer/pamiec.json" @@ -93,6 +96,8 @@ if platform in ("linux", "linux2"): ACCIDENT_LOG = "/home/pi/Conjurer/accident_log.json" ENCODING = "utf-8" GRAPHICS_PATH = "/home/pi/RetroPie/Conjurer_graphics/" + DIR_PATH_SADOX = "/home/pi/RetroPie/Fansadox/" + elif platform == "win32": LOGFILE = "discord.log" @@ -103,7 +108,10 @@ elif platform == "win32": NETRC_FILE = "C:\\Users\\mtusz\\.netrc" LOGSTORE = "C:\\Users\\mtusz\\OneDrive\\Pulpit\\Conjurer\\logs\\" ACCIDENT_LOG = "accident_log.json" - ENCODING = "cp1250" + ENCODING = "utf-8" + DIR_PATH_SADOX = "C:\\Users\\mtusz\\OneDrive\\Dokumenty\\Fansadox\\" + SEPARATOR_FILE_PATH = "\\" + # *=========================================== Keys netrc_mod = netrc.netrc(NETRC_FILE) @@ -231,7 +239,7 @@ async def on_message(message): # TODO: wpiac jego reakcje we framework chatu GPT message.content = message.content.lower() - tdelta = datetime.now() - master_timeout + tdelta = datetime.now() - MASTER_TIMEOUT tdelta = tdelta.total_seconds() if "opowiedz o fabryczce" in message.content: await message.reply(historia_fabryczki) @@ -357,7 +365,6 @@ async def disconnect(ctx): # trunk-ignore(pylint/R0915) -# trunk-ignore(pylint/R0914) # trunk-ignore(pylint/R0912) async def play(ctx, zamawial=None, arg=None): """ @@ -394,12 +401,7 @@ async def play(ctx, zamawial=None, arg=None): logger.debug(file_to_play) metadata = eyed3.load(file_to_play) query = None - separator = None - if platform in ("linux", "linux2"): - separator = "/" - elif platform == "win32": - separator = "\\" - temp = file_to_play.split(separator)[-1] + temp = file_to_play.split(SEPARATOR_FILE_PATH)[-1] kawalek = f"Zagram teraz kawalek {temp} z prywatnej kolekcji Hammera." if metadata: if metadata.tag: @@ -436,7 +438,7 @@ async def play(ctx, zamawial=None, arg=None): username = ctx.message.author.nick else: username = ctx.message.author.name - global MESSAGE_TABLE # pylint: disable=global-statement + global MESSAGE_TABLE # pylint: disable=global-statement result, MESSAGE_TABLE = await handle_response( query, vykidailo, bartender, message_table_muzyka, username, True ) @@ -448,7 +450,6 @@ 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. - # TODO: Dodać typing i dać znać że wykonuje operacje porządkowania Baru (zamiata, układa szklanki itp.) # trunk-ignore(codespell/misspelled) # TODO: dlaczego sie tu wypierdala if client.voice_clients: @@ -517,9 +518,7 @@ async def check(): # trunk-ignore(pylint/R0913) -async def handle_response( - prompt, vykidailo, bartender, history, username, music -): +async def handle_response(prompt, vykidailo, bartender, history, username, music): """ Handle responses by appending them to a history, use OpenAI to generate a response, and then append the generated response to the history. @@ -632,7 +631,8 @@ async def get_file(ctx, source, link): 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( @@ -745,7 +745,7 @@ async def async_iterator_generator(range_of_iterable): # pylint: disable=pointless-string-statement # yield the result yield i - ''' + """ Alternatywna wersja przerobienia fora na asynchroniczny. # traverse the iterable of awaitables for item in coros: @@ -753,7 +753,7 @@ async def async_iterator_generator(range_of_iterable): result = await item # report the results print(result) - ''' + """ # trunk-ignore(pylint/R0914) @@ -789,10 +789,8 @@ async def wyszukaj(ctx, how_many=0): logger.info("Słowo kluczowe: %s", word) itr = 0 for file in music_file_list: - if platform == "win32": - file = file.split("\\") - else: - file = file.split("/") + file = file.split(SEPARATOR_FILE_PATH) + char_remove = [ ".", "^", @@ -805,6 +803,7 @@ async def wyszukaj(ctx, how_many=0): "[", "]", "\\", + "/", "|", "(", ")", @@ -833,13 +832,15 @@ async def wyszukaj(ctx, how_many=0): if re.match(pattern, itm, re.IGNORECASE): temp_weight = ( search_weight[itr][0] - + (token_weight + (pingu**1.5) / pattern_len) / matched_times + + (token_weight + (pingu**1.5) / + pattern_len) / matched_times ) search_weight[itr] = temp_weight, music_file_list[itr] matched_times += 1 itr += 1 - logger.info("Stworzylem tablice wag zajęło mi to %s", datetime.now() - time_start) + 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 @@ -1069,27 +1070,22 @@ async def get_image_sadox(ctx): logger.info("Get sadox") channel = ctx.message.channel async with channel.typing(): - dir_path_sadox = "" # select random file - if platform in ("linux", "linux2"): - dir_path_sadox = "/home/pi/RetroPie/Fansadox/" - elif platform == "win32": - dir_path_sadox = "C:\\Users\\mtusz\\OneDrive\\Dokumenty\\Fansadox\\" res = [] # Iterate directory - for path in os.listdir(dir_path_sadox): + for path in os.listdir(DIR_PATH_SADOX): # check if current path is a file - if os.path.isfile(os.path.join(dir_path_sadox, path)): + if os.path.isfile(os.path.join(DIR_PATH_SADOX, path)): res.append(path) filename = res[random.randrange(0, len(res) - 1)] # select random page - file = open(dir_path_sadox + filename, "rb") + file = open(DIR_PATH_SADOX + filename, "rb") readpdf = PyPDF2.PdfReader(file) totalpages = len(readpdf.pages) page = random.randrange(1, totalpages) # convert page to image image = pdf2image.convert_from_path( - dir_path_sadox + filename, first_page=page, last_page=page + DIR_PATH_SADOX + filename, first_page=page, last_page=page ) byte_io_stream = io.BytesIO() image[0].save(byte_io_stream, "JPEG") @@ -1310,19 +1306,21 @@ async def zrob_mi_plejliste(ctx): MUZYKA["queue"].insert(0, plik[1]) MUZYKA["requestor"].insert(0, ctx.author) metadata = eyed3.load(plik[1]) - if metadata.tag.title: - reply += f"{index} {metadata.tag.title}" - else: - reply += "{index}. {plik[1]} z prywatnej kolekcji Hammera." + 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." - 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" - ) index += 1 if len(reply) > 1800: await ctx.send(reply) @@ -1339,17 +1337,16 @@ async def zrob_mi_plejliste(ctx): @client.hybrid_command( name="przytul", description="Przytul kogoś - daj mention po komendzie :)" ) -async def przytul(ctx, arg: Union[discord.Member, None] = None): +async def przytul(ctx, arg: Optional[discord.Member] = None): """ Generate a text about hugging mentioned user. :param ctx: ctx stands for "context" and is a required parameter in Discord.py commands. It - represents the context in which the command is being executed, including information such as the - message, the channel, the server, and the user who invoked the command - :param arg: The parameter "arg" is a variable that can accept either a discord.Member object or None - as its value. It is an optional parameter, which means that if no value is provided for it when the - function is called, it will default to None - :type arg: Union[discord.Member, None] + represents the context in which the command was invoked, including information such as the message, + the channel, the server, and the user who invoked the command + :param arg: arg is a parameter of the function "przytul" that expects a Discord member object. The + parameter is optional, meaning that if no member object is provided, it will default to None + :type arg: Optional[discord.Member] """ async with ctx.typing(): nieprzytulac = False