Trunk + mod

This commit is contained in:
2023-06-23 20:06:18 +02:00
committed by migatu
parent 06e3671ec2
commit aa00045dec
+65 -68
View File
@@ -24,7 +24,7 @@ from logging import handlers
from pathlib import Path, PurePath from pathlib import Path, PurePath
from platform import uname from platform import uname
from sys import platform from sys import platform
from typing import List, TypedDict, Union from typing import List, Optional, TypedDict
# *==============Imported libraries # *==============Imported libraries
import discord import discord
@@ -42,24 +42,23 @@ import yt_dlp
from spotify_dl import spotify from spotify_dl import spotify
from spotify_dl import youtube as youtube_download 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 = TypedDict(
"Music_Config", "Music_Config",
{ {
"playing": bool, "playing": bool,
"ctx": Union[str, None], "ctx": Optional[str],
"queue": List[str], "queue": List[str],
"requestor": List[str], "requestor": List[str],
}, },
) )
# *=========================================== Predefines # *=========================================== Predefines
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") formatter = logging.Formatter(
master_timeout = datetime.now() "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
MASTER_TIMEOUT = datetime.now()
INITIAL_TIME_WAIT = 5 INITIAL_TIME_WAIT = 5
MUZYKA: Music_Config = {"playing": False, "ctx": None, "queue": [], "requestor": []} MUZYKA: Music_Config = {"playing": False,
"ctx": None, "queue": [], "requestor": []}
LOGFILE = "" LOGFILE = ""
NETRC_FILE = "" NETRC_FILE = ""
@@ -70,18 +69,22 @@ SETTINGS_FILE = ""
ENCODING = "" ENCODING = ""
GRAPHICS_PATH = "" GRAPHICS_PATH = ""
# *=========================================== Platform Specific Predefines # *=========================================== Platform Specific Predefines
if platform in ("linux", "linux2"): if platform in ("linux", "linux2"):
SEPARATOR_FILE_PATH = "/"
if "microsoft-standard" in uname().release: if "microsoft-standard" in uname().release:
LOGFILE = "/home/pi/Conjurer/discord.log" LOGFILE = "/home/mtuszowski/conjurer/discord.log"
MEMORY_FIVE_SIARA = "/home/pi/Conjurer/pamiec.json" MEMORY_FIVE_SIARA = "/home/mtuszowski/conjurer/pamiec.json"
MEMORY_FIVE_MUZYKA = "/home/pi/Conjurer/pamiec_muzyki.json" MEMORY_FIVE_MUZYKA = "/home/mtuszowski/conjurer/pamiec_muzyki.json"
MUSIC_FOLDER = "/home/pi/RetroPie/mp3/" MUSIC_FOLDER = "/mnt/g/Muzyka/"
SETTINGS_FILE = "/home/pi/Conjurer/settings.json" SETTINGS_FILE = "/home/mtuszowski/conjurer/settings.json"
NETRC_FILE = "/home/pi/netrc" NETRC_FILE = "/home/mtuszowski/.netrc"
LOGSTORE = "/home/pi/RetroPie/logs/" LOGSTORE = "/home/mtuszowski/conjurer/logs/"
ACCIDENT_LOG = "/home/pi/Conjurer/accident_log.json" ACCIDENT_LOG = "/home/mtuszowski/conjurer/accident_log.json"
ENCODING = "utf-8" 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: else:
LOGFILE = "/home/pi/Conjurer/discord.log" LOGFILE = "/home/pi/Conjurer/discord.log"
MEMORY_FIVE_SIARA = "/home/pi/Conjurer/pamiec.json" 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" ACCIDENT_LOG = "/home/pi/Conjurer/accident_log.json"
ENCODING = "utf-8" ENCODING = "utf-8"
GRAPHICS_PATH = "/home/pi/RetroPie/Conjurer_graphics/" GRAPHICS_PATH = "/home/pi/RetroPie/Conjurer_graphics/"
DIR_PATH_SADOX = "/home/pi/RetroPie/Fansadox/"
elif platform == "win32": elif platform == "win32":
LOGFILE = "discord.log" LOGFILE = "discord.log"
@@ -103,7 +108,10 @@ elif platform == "win32":
NETRC_FILE = "C:\\Users\\mtusz\\.netrc" NETRC_FILE = "C:\\Users\\mtusz\\.netrc"
LOGSTORE = "C:\\Users\\mtusz\\OneDrive\\Pulpit\\Conjurer\\logs\\" LOGSTORE = "C:\\Users\\mtusz\\OneDrive\\Pulpit\\Conjurer\\logs\\"
ACCIDENT_LOG = "accident_log.json" ACCIDENT_LOG = "accident_log.json"
ENCODING = "cp1250" ENCODING = "utf-8"
DIR_PATH_SADOX = "C:\\Users\\mtusz\\OneDrive\\Dokumenty\\Fansadox\\"
SEPARATOR_FILE_PATH = "\\"
# *=========================================== Keys # *=========================================== Keys
netrc_mod = netrc.netrc(NETRC_FILE) netrc_mod = netrc.netrc(NETRC_FILE)
@@ -231,7 +239,7 @@ async def on_message(message):
# TODO: wpiac jego reakcje we framework chatu GPT # TODO: wpiac jego reakcje we framework chatu GPT
message.content = message.content.lower() message.content = message.content.lower()
tdelta = datetime.now() - master_timeout tdelta = datetime.now() - MASTER_TIMEOUT
tdelta = tdelta.total_seconds() tdelta = tdelta.total_seconds()
if "opowiedz o fabryczce" in message.content: if "opowiedz o fabryczce" in message.content:
await message.reply(historia_fabryczki) await message.reply(historia_fabryczki)
@@ -357,7 +365,6 @@ async def disconnect(ctx):
# trunk-ignore(pylint/R0915) # trunk-ignore(pylint/R0915)
# trunk-ignore(pylint/R0914)
# trunk-ignore(pylint/R0912) # trunk-ignore(pylint/R0912)
async def play(ctx, zamawial=None, arg=None): 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) logger.debug(file_to_play)
metadata = eyed3.load(file_to_play) metadata = eyed3.load(file_to_play)
query = None query = None
separator = None temp = file_to_play.split(SEPARATOR_FILE_PATH)[-1]
if platform in ("linux", "linux2"):
separator = "/"
elif platform == "win32":
separator = "\\"
temp = file_to_play.split(separator)[-1]
kawalek = f"Zagram teraz kawalek {temp} z prywatnej kolekcji Hammera." kawalek = f"Zagram teraz kawalek {temp} z prywatnej kolekcji Hammera."
if metadata: if metadata:
if metadata.tag: if metadata.tag:
@@ -436,7 +438,7 @@ async def play(ctx, zamawial=None, arg=None):
username = ctx.message.author.nick username = ctx.message.author.nick
else: else:
username = ctx.message.author.name 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( result, MESSAGE_TABLE = await handle_response(
query, vykidailo, bartender, message_table_muzyka, username, True query, vykidailo, bartender, message_table_muzyka, username, True
) )
@@ -448,7 +450,6 @@ async def check():
"""Funkcja sprawdzająca czy grać następny kawałek.""" """Funkcja sprawdzająca czy grać następny kawałek."""
while True: while True:
# TODO: Tu dołożyć skanowanie rozmiaru pliku logowania oraz plików pamięci i przenoszenie ich na większy dysk. # 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) # trunk-ignore(codespell/misspelled)
# TODO: dlaczego sie tu wypierdala # TODO: dlaczego sie tu wypierdala
if client.voice_clients: if client.voice_clients:
@@ -517,9 +518,7 @@ async def check():
# trunk-ignore(pylint/R0913) # trunk-ignore(pylint/R0913)
async def handle_response( async def handle_response(prompt, vykidailo, bartender, history, username, music):
prompt, vykidailo, bartender, history, username, music
):
""" """
Handle responses by appending them to a history, use OpenAI to Handle responses by appending them to a history, use OpenAI to
generate a response, and then append the generated response to the history. 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) item_type, item_id = spotify.parse_spotify_url(link)
if item_id: if item_id:
file_list = spotify.fetch_tracks(spotify_ctrl, item_type, link) 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_data = {"urls": []}
url_dict = {} url_dict = {}
url_dict["save_path"] = Path( url_dict["save_path"] = Path(
@@ -745,7 +745,7 @@ async def async_iterator_generator(range_of_iterable):
# pylint: disable=pointless-string-statement # pylint: disable=pointless-string-statement
# yield the result # yield the result
yield i yield i
''' """
Alternatywna wersja przerobienia fora na asynchroniczny. Alternatywna wersja przerobienia fora na asynchroniczny.
# traverse the iterable of awaitables # traverse the iterable of awaitables
for item in coros: for item in coros:
@@ -753,7 +753,7 @@ async def async_iterator_generator(range_of_iterable):
result = await item result = await item
# report the results # report the results
print(result) print(result)
''' """
# trunk-ignore(pylint/R0914) # trunk-ignore(pylint/R0914)
@@ -789,10 +789,8 @@ async def wyszukaj(ctx, how_many=0):
logger.info("Słowo kluczowe: %s", word) logger.info("Słowo kluczowe: %s", word)
itr = 0 itr = 0
for file in music_file_list: for file in music_file_list:
if platform == "win32": file = file.split(SEPARATOR_FILE_PATH)
file = file.split("\\")
else:
file = file.split("/")
char_remove = [ 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): if re.match(pattern, itm, re.IGNORECASE):
temp_weight = ( temp_weight = (
search_weight[itr][0] 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] search_weight[itr] = temp_weight, music_file_list[itr]
matched_times += 1 matched_times += 1
itr += 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() time_start = datetime.now()
item_to_search = await max_weight(search_weight) item_to_search = await max_weight(search_weight)
itr = 0 itr = 0
@@ -1069,27 +1070,22 @@ async def get_image_sadox(ctx):
logger.info("Get sadox") logger.info("Get sadox")
channel = ctx.message.channel channel = ctx.message.channel
async with channel.typing(): async with channel.typing():
dir_path_sadox = ""
# select random file # 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 = [] res = []
# Iterate directory # 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 # 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) res.append(path)
filename = res[random.randrange(0, len(res) - 1)] filename = res[random.randrange(0, len(res) - 1)]
# select random page # select random page
file = open(dir_path_sadox + filename, "rb") file = open(DIR_PATH_SADOX + filename, "rb")
readpdf = PyPDF2.PdfReader(file) readpdf = PyPDF2.PdfReader(file)
totalpages = len(readpdf.pages) totalpages = len(readpdf.pages)
page = random.randrange(1, totalpages) page = random.randrange(1, totalpages)
# convert page to image # convert page to image
image = pdf2image.convert_from_path( 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() byte_io_stream = io.BytesIO()
image[0].save(byte_io_stream, "JPEG") image[0].save(byte_io_stream, "JPEG")
@@ -1310,19 +1306,21 @@ async def zrob_mi_plejliste(ctx):
MUZYKA["queue"].insert(0, plik[1]) MUZYKA["queue"].insert(0, plik[1])
MUZYKA["requestor"].insert(0, ctx.author) MUZYKA["requestor"].insert(0, ctx.author)
metadata = eyed3.load(plik[1]) metadata = eyed3.load(plik[1])
if metadata.tag.title: if metadata and metadata.tag:
reply += f"{index} {metadata.tag.title}" if metadata.tag.title:
else: reply += f"{index} {metadata.tag.title}"
reply += "{index}. {plik[1]} z prywatnej kolekcji Hammera." 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 index += 1
if len(reply) > 1800: if len(reply) > 1800:
await ctx.send(reply) await ctx.send(reply)
@@ -1339,17 +1337,16 @@ async def zrob_mi_plejliste(ctx):
@client.hybrid_command( @client.hybrid_command(
name="przytul", description="Przytul kogoś - daj mention po komendzie :)" 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. Generate a text about hugging mentioned user.
:param ctx: ctx stands for "context" and is a required parameter in Discord.py commands. It :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 represents the context in which the command was invoked, including information such as the message,
message, the channel, the server, and the user who invoked the command 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 :param arg: arg is a parameter of the function "przytul" that expects a Discord member object. The
as its value. It is an optional parameter, which means that if no value is provided for it when the parameter is optional, meaning that if no member object is provided, it will default to None
function is called, it will default to None :type arg: Optional[discord.Member]
:type arg: Union[discord.Member, None]
""" """
async with ctx.typing(): async with ctx.typing():
nieprzytulac = False nieprzytulac = False