This commit is contained in:
2024-03-29 21:21:09 +01:00
parent 7483302f07
commit 0a118eac0d
2 changed files with 72 additions and 36 deletions
+70 -34
View File
@@ -43,7 +43,6 @@ from spotify_dl import youtube as youtube_download
Music_Config = TypedDict(
"Music_Config",
{
"playing": bool,
"ctx": Optional[str],
"queue": List[str],
"requester": List[str],
@@ -54,7 +53,7 @@ Music_Config = TypedDict(
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": [], "requester": []}
MUZYKA: Music_Config = {"ctx": None, "queue": [], "requester": []}
LOGFILE = ""
NETRC_FILE = ""
@@ -72,6 +71,8 @@ FILE_SERVICE_ADDRESS = "http://192.168.1.15:5000"
GET_MP3 = "/mp3"
SEND_MP3 = "/update_mp3"
LAST_SPONTANEOUS_CALL = datetime.now()
# *=========================================== Platform Specific Predefines
if platform in ("linux", "linux2"):
@@ -357,7 +358,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:
@@ -540,7 +541,7 @@ 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)
@@ -573,15 +574,9 @@ async def check_music():
"""
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["requester"])
await asyncio.sleep(1)
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(minutes=2)
@@ -590,21 +585,20 @@ async def check_data():
The function `check_data` periodically checks for conditions to send messages and manage log files
in a Discord channel.
"""
last_spontaneous_call = datetime.now()
tdelta = datetime.now() - last_spontaneous_call
tdelta = tdelta.total_seconds()
if tdelta > 34000:
channel = client.get_channel(1062047571557744721)
last_spontaneous_call = datetime.now()
with channel.typing():
message = get_random_cyclic_message()
await channel.send(message)
# trunk-ignore(codespell/misspelled)
# TODO: dlaczego sie tu wypierdala
if os.path.getsize(LOGFILE) > 6000000:
shutil.copyfile(LOGFILE, f"{LOGSTORE}discord{datetime.now()}")
logger.info("Log rollover")
handler.doRollover()
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():
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)
@@ -648,7 +642,15 @@ async def check_data():
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*"
)
await asyncio.sleep(60)
global LAST_SPONTANEOUS_CALL
tdelta = LAST_SPONTANEOUS_CALL - datetime.now()
tdelta = tdelta.total_seconds()
if tdelta > 12:
channel = client.get_channel(1062047571557744721)
LAST_SPONTANEOUS_CALL = datetime.now()
with channel.typing():
message = get_random_cyclic_message()
await channel.send(message)
async def get_random_cyclic_message():
@@ -657,11 +659,34 @@ async def get_random_cyclic_message():
words.
:return: a random cyclic message from the list `cyclic_words`.
"""
messnum = random.randint(0, len(cyclic_words) - 1)
return cyclic_words[messnum][0]
ai_check = random.randint(0,10)
logger.info("Losowa wypowiedź")
if ai_check < 0:
logger.info("Predefiniowana")
messnum = random.randint(0, len(cyclic_words) - 1)
return cyclic_words[messnum][0]
ai_check2 = random.randint(0,10)
global MESSAGE_TABLE
if ai_check2 > 4:
logger.info("Dykteryjka")
result, MESSAGE_TABLE = await handle_response(
"Opowiedz jakąś historię o naszym barze proszę", True, True, MESSAGE_TABLE, "Polish Hammer", "RANDOM"
)
else:
channel_id = 1062047367337095268
channel = client.get_channel(channel_id)
logger.info("Wtracenie sie w dyskusje")
messages = [message async for message in channel.history(limit=50)]
for message in messages:
temp = {"role": "user", "content": message.author + ":" + 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"
)
return result
async def handle_response(prompt, vykidailo, bartender, history, username, music):
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.
@@ -684,7 +709,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)
@@ -693,6 +718,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.
@@ -722,10 +756,14 @@ async def handle_response(prompt, vykidailo, bartender, history, username, music
logger.info(
"Rozmiar zapytania przed dodaniem historii %s", chat_gpt_config_request_size
)
if music:
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"
@@ -770,7 +808,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)
@@ -1337,7 +1375,6 @@ 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)
@@ -1361,7 +1398,6 @@ 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()
+2 -2
View File
@@ -97,8 +97,8 @@ def write_tracks(tracks_file, song_dict):
def set_tags(temp, filename, kwargs):
"""
sets song tags after they are downloaded
:param temp: contains index used to obtain more info about song being editted
:param filename: location of song whose tags are to be editted
:param temp: contains index used to obtain more info about song being edited
:param filename: location of song whose tags are to be edited
:param kwargs: a dictionary of extra arguments to be used in tag editing
"""
song = kwargs["track_db"][int(temp[-1])]