This commit is contained in:
2024-03-30 18:08:32 +01:00
parent 39c633ff4a
commit 22d2c8ab39
+79 -20
View File
@@ -36,6 +36,7 @@ import spotipy
import tiktoken import tiktoken
from discord.ext import commands, tasks from discord.ext import commands, tasks
from spotipy.oauth2 import SpotifyClientCredentials from spotipy.oauth2 import SpotifyClientCredentials
import yt_dlp 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
@@ -166,11 +167,13 @@ logger.info("Playlist generation")
# *=========================================== Load Data files # *=========================================== Load Data files
class MusicFileList(object): class MusicFileList(object):
""" """
The `MusicFileList` class manages a list of music files, with the ability to refresh the list from a 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. file service or local directory and update the list with new items.
""" """
def __init__(self, uplogger) -> None: def __init__(self, uplogger) -> None:
self.music_file_list = [] self.music_file_list = []
self.file_service_active = False self.file_service_active = False
@@ -184,7 +187,7 @@ class MusicFileList(object):
""" """
try: try:
self.logger.info("Attempt to connect to file service") self.logger.info("Attempt to connect to file service")
response = requests.get(f'{FILE_SERVICE_ADDRESS}{GET_MP3}',timeout=360) response = requests.get(f"{FILE_SERVICE_ADDRESS}{GET_MP3}", timeout=360)
self.music_file_list = response.json()["music_file_list"] self.music_file_list = response.json()["music_file_list"]
self.file_service_active = True self.file_service_active = True
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
@@ -196,13 +199,15 @@ class MusicFileList(object):
self.file_service_active = False self.file_service_active = False
self.logger.error(e.strerror) self.logger.error(e.strerror)
self.logger.error("Service Unavailable") self.logger.error("Service Unavailable")
def get_file_list(self): def get_file_list(self):
""" """
The `get_file_list` function returns the list of music files stored in the object. 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: The `music_file_list` attribute is being returned.
""" """
return self.music_file_list return self.music_file_list
def update_file_list(self,item):
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 `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. the item data to a file service address.
@@ -212,8 +217,9 @@ class MusicFileList(object):
POST request to a file service address along with the endpoint `SEND_MP3` POST request to a file service address along with the endpoint `SEND_MP3`
""" """
self.music_file_list.append(item) self.music_file_list.append(item)
post_data = {"item" : str(item)} post_data = {"item": str(item)}
requests.post(f'{FILE_SERVICE_ADDRESS}{SEND_MP3}', json=post_data, timeout = 360) requests.post(f"{FILE_SERVICE_ADDRESS}{SEND_MP3}", json=post_data, timeout=360)
music_file_list = [] music_file_list = []
music_file_list = MusicFileList(logger) music_file_list = MusicFileList(logger)
@@ -268,6 +274,9 @@ async def on_ready():
@client.event @client.event
# trunk-ignore(pylint/R0915)
# trunk-ignore(pylint/R0914)
# trunk-ignore(pylint/R0912)
async def on_message(message): async def on_message(message):
""" """
Handle incoming messages in a Discord server, perform various Handle incoming messages in a Discord server, perform various
@@ -473,6 +482,8 @@ async def disconnect(ctx):
await voice_client.disconnect() await voice_client.disconnect()
# trunk-ignore(pylint/R0915)
# trunk-ignore(pylint/R0912)
async def play(ctx, zamawial=None, arg=None): async def play(ctx, zamawial=None, arg=None):
""" """
Play a music file, retrieve metadata about the file, and send a Play a music file, retrieve metadata about the file, and send a
@@ -582,12 +593,18 @@ async def check_music():
""" """
if client.voice_clients: if client.voice_clients:
voice_client = client.voice_clients[0] 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(): 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 play(MUZYKA["ctx"], MUZYKA["requester"])
await asyncio.sleep(2) await asyncio.sleep(2)
@tasks.loop(seconds=120) @tasks.loop(seconds=120)
# trunk-ignore(pylint/R0915)
async def check_data(): async def check_data():
""" """
The function `check_data` periodically checks for conditions to send messages and manage log files The function `check_data` periodically checks for conditions to send messages and manage log files
@@ -610,7 +627,7 @@ async def check_data():
handler.doRollover() handler.doRollover()
await channel.send( 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!" "*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: if os.path.getsize(MEMORY_FIVE_MUZYKA) > 300000:
await channel.send( await channel.send(
@@ -653,13 +670,17 @@ async def check_data():
await channel.send( 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* eprzyć o głupotach z klientami... Szefie... *Bierze 'ukradkowy' łyk z piersiówki*"
) )
# trunk-ignore(pylint/W0603)
global LAST_SPONTANEOUS_CALL global LAST_SPONTANEOUS_CALL
# trunk-ignore(pylint/W0603)
global TIME_BETWEEN_CALLS global TIME_BETWEEN_CALLS
tdelta = datetime.now() - LAST_SPONTANEOUS_CALL tdelta = datetime.now() - LAST_SPONTANEOUS_CALL
tdelta = tdelta.total_seconds() tdelta = tdelta.total_seconds()
if tdelta > TIME_BETWEEN_CALLS: if tdelta > TIME_BETWEEN_CALLS:
logger.info("Spontaneous call") logger.info("Spontaneous call")
TIME_BETWEEN_CALLS = random.randint(7200,172800) #temp random, set after each call TIME_BETWEEN_CALLS = random.randint(
7200, 172800
) # temp random, set after each call
logger.debug(TIME_BETWEEN_CALLS) logger.debug(TIME_BETWEEN_CALLS)
LAST_SPONTANEOUS_CALL = datetime.now() LAST_SPONTANEOUS_CALL = datetime.now()
async with channel.typing(): async with channel.typing():
@@ -677,7 +698,7 @@ async def get_random_cyclic_message():
""" """
channel_id = 1062047367337095268 channel_id = 1062047367337095268
channel = client.get_channel(channel_id) channel = client.get_channel(channel_id)
ai_check = random.randint(0,10) ai_check = random.randint(0, 10)
logger.info("Losowa wypowiedź") logger.info("Losowa wypowiedź")
if ai_check < 2: if ai_check < 2:
logger.info("Predefiniowana") logger.info("Predefiniowana")
@@ -686,28 +707,48 @@ async def get_random_cyclic_message():
logger.debug(len(cyclic_words)) logger.debug(len(cyclic_words))
mess_key = list(cyclic_words.keys())[messnum] mess_key = list(cyclic_words.keys())[messnum]
return cyclic_words[mess_key][0] return cyclic_words[mess_key][0]
ai_check2 = random.randint(0,10) ai_check2 = random.randint(0, 10)
# trunk-ignore(pylint/W0603)
global MESSAGE_TABLE global MESSAGE_TABLE
if ai_check2 < 6: if ai_check2 < 6:
logger.info("Dykteryjka") logger.info("Dykteryjka")
result, MESSAGE_TABLE = await handle_response( result, MESSAGE_TABLE = await handle_response(
"Opowiedz jakąś historię o naszym barze proszę", True, True, MESSAGE_TABLE, "Polish Hammer", "RANDOM" "Opowiedz jakąś historię o naszym barze proszę",
) True,
True,
MESSAGE_TABLE,
"Polish Hammer",
"RANDOM",
)
logger.info(result) logger.info(result)
else: else:
logger.info("Wtracenie w dyskusje") logger.info("Wtracenie w dyskusje")
messages = [message async for message in channel.history(limit=50)] messages = [message async for message in channel.history(limit=50)]
for message in messages: for message in messages:
temp = {"role": "user", "content": str(message.author) + ":" + str(message.content)} temp = {
"role": "user",
"content": str(message.author) + ":" + str(message.content),
}
MESSAGE_TABLE.append(temp) MESSAGE_TABLE.append(temp)
result, MESSAGE_TABLE = await handle_response( result, MESSAGE_TABLE = await handle_response(
"A jaka jest Twoja opinia na temat dotychczasowej dyskusji?", True, True, MESSAGE_TABLE, "Polish Hammer", "RANDOM" "A jaka jest Twoja opinia na temat dotychczasowej dyskusji?",
True,
True,
MESSAGE_TABLE,
"Polish Hammer",
"RANDOM",
) )
logger.info(result) logger.info(result)
return result return result
async def handle_response(prompt, vykidailo, bartender, history, username, request_type): # trunk-ignore(pylint/R0912)
# trunk-ignore(pylint/R0913)
# 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 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.
@@ -852,6 +893,8 @@ async def handle_response(prompt, vykidailo, bartender, history, username, reque
return result, MESSAGE_TABLE return result, MESSAGE_TABLE
# trunk-ignore(pylint/R0915)
# trunk-ignore(pylint/R0914)
async def get_file(ctx, source, link): async def get_file(ctx, source, link):
""" """
Take in three parameters: "ctx" (context), Take in three parameters: "ctx" (context),
@@ -928,7 +971,7 @@ async def get_file(ctx, source, link):
"force_keyframes": True, "force_keyframes": True,
}, },
] ]
#TODO: Make sponsorblock work # TODO: Make sponsorblock work
sponsorblock_postprocessor = [] sponsorblock_postprocessor = []
if platform == "win32": if platform == "win32":
dir_path = "G:\\Muzyka\\Youtube" dir_path = "G:\\Muzyka\\Youtube"
@@ -1033,6 +1076,9 @@ async def get_stats(ctx, history_limit):
yield name, how_many yield name, how_many
# trunk-ignore(pylint/R0915)
# trunk-ignore(pylint/R0912)
# trunk-ignore(pylint/R0914)
async def wyszukaj(ctx, how_many=0, slowa_kluczowe=None): 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 Take in a context object and an optional integer parameter "how_many" and perform search
@@ -1111,7 +1157,10 @@ async def wyszukaj(ctx, how_many=0, slowa_kluczowe=None):
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.get_file_list()[itr] search_weight[itr] = (
temp_weight,
music_file_list.get_file_list()[itr],
)
matched_times += 1 matched_times += 1
itr += 1 itr += 1
@@ -1195,7 +1244,14 @@ async def dej_co_ze_spotifaja(ctx):
else: else:
separator = "/" separator = "/"
for file in files: for file in files:
file_path = dir_path + separator + file["artist"] + " - " + file["name"] + ".mp3" file_path = (
dir_path
+ separator
+ file["artist"]
+ " - "
+ file["name"]
+ ".mp3"
)
global MUZYKA # pylint: disable=global-variable-not-assigned global MUZYKA # pylint: disable=global-variable-not-assigned
MUZYKA["queue"].insert( MUZYKA["queue"].insert(
0, 0,
@@ -1251,6 +1307,8 @@ async def dej_co_z_jutuba(ctx):
description="Jeśli nie wiesz jak użyć tej komendy to nawet nie próbuj", description="Jeśli nie wiesz jak użyć tej komendy to nawet nie próbuj",
guild=discord.Object(id=664789470779932693), guild=discord.Object(id=664789470779932693),
) )
# trunk-ignore(pylint/R0914)
# trunk-ignore(pylint/R0912)
async def update_banlist(ctx): async def update_banlist(ctx):
""" """
Update a banlist in a Discord guild from preprovided list in channel. Update a banlist in a Discord guild from preprovided list in channel.
@@ -1758,12 +1816,13 @@ async def get_image_stable_diffusion(ctx):
if ctx: if ctx:
pass pass
@client.hybrid_command( @client.hybrid_command(
name="zagraj_muzyke_mego_ludu", name="zagraj_muzyke_mego_ludu",
description="Gra muzyke wyszukana na bazie tematow konwersacji na kanale NZ", description="Gra muzyke wyszukana na bazie tematow konwersacji na kanale NZ",
guild=discord.Object(id=664789470779932693), guild=discord.Object(id=664789470779932693),
) )
# trunk-ignore(pylint/R0912)
# trunk-ignore(pylint/R0915)
async def zagraj_muzyke_mego_ludu(ctx): async def zagraj_muzyke_mego_ludu(ctx):
""" """
Play completeley random playlist based on messaging history. Play completeley random playlist based on messaging history.