mirror of
https://github.com/migatu/conjurer.git
synced 2026-07-19 16:22:10 +00:00
Bot side
This commit is contained in:
@@ -17,15 +17,16 @@ import random
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import uuid
|
||||
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, Queue
|
||||
from sys import platform
|
||||
from typing import List, Optional, TypedDict
|
||||
from queue import Queue, Empty
|
||||
|
||||
# *==============Imported libraries
|
||||
import discord
|
||||
import eyed3
|
||||
@@ -37,16 +38,14 @@ import requests
|
||||
import spotipy
|
||||
import tiktoken
|
||||
from discord.ext import commands, tasks
|
||||
from flask import Flask, jsonify, request
|
||||
from spotipy.oauth2 import SpotifyClientCredentials
|
||||
from waitress import serve
|
||||
|
||||
import yt_dlp
|
||||
from spotify_dl import spotify
|
||||
from spotify_dl import youtube as youtube_download
|
||||
|
||||
from flask import Flask, jsonify, request
|
||||
from waitress import serve
|
||||
|
||||
|
||||
COMM_Q = Queue()
|
||||
Music_Config = TypedDict(
|
||||
"Music_Config",
|
||||
@@ -56,13 +55,17 @@ Music_Config = TypedDict(
|
||||
"requester": List[str],
|
||||
},
|
||||
)
|
||||
class QueryControl():
|
||||
|
||||
|
||||
class QueryControl:
|
||||
def __init__(self, query_author, query_uuid, query_content, uplogger) -> None:
|
||||
self.author = query_author
|
||||
self.uuid = query_uuid
|
||||
self.content = query_content
|
||||
self.logger = uplogger
|
||||
self.logger.info(f"Created Query control for {self.author}, {self.uuid}: {self.content}")
|
||||
self.logger.info(
|
||||
f"Created Query control for {self.author}, {self.uuid}: {self.content}"
|
||||
)
|
||||
self.replies = []
|
||||
|
||||
|
||||
@@ -285,6 +288,8 @@ logger.info("Done")
|
||||
logger.info("Creating flask app")
|
||||
app = Flask(__name__)
|
||||
logger.info("Done")
|
||||
|
||||
|
||||
# *=========================================== Define Events
|
||||
@client.event
|
||||
async def on_ready():
|
||||
@@ -414,28 +419,51 @@ async def on_message(message):
|
||||
)
|
||||
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}")
|
||||
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}")
|
||||
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}")
|
||||
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}")
|
||||
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}"))
|
||||
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}")
|
||||
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}")
|
||||
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
|
||||
@@ -916,11 +944,25 @@ async def handle_response(
|
||||
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")
|
||||
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")
|
||||
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
|
||||
@@ -936,7 +978,6 @@ async def handle_response(
|
||||
# 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)
|
||||
@@ -1008,7 +1049,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",
|
||||
@@ -1131,6 +1173,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):
|
||||
"""
|
||||
@@ -1212,8 +1255,17 @@ async def wyszukaj(ctx, how_many=0, slowa_kluczowe=None):
|
||||
else:
|
||||
word_list = ctx.message.content.split()
|
||||
logger.info("Wyszukuje")
|
||||
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)
|
||||
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")
|
||||
@@ -1221,6 +1273,7 @@ async def wyszukaj(ctx, how_many=0, slowa_kluczowe=None):
|
||||
logger.info(return_data.json()["data"])
|
||||
return return_data.json()["data"]
|
||||
|
||||
|
||||
async def remove_characters(string, character):
|
||||
"""
|
||||
The `remove_characters` function removes all occurrences of a specified character from a given
|
||||
@@ -1852,6 +1905,7 @@ async def get_image_stable_diffusion(ctx):
|
||||
if ctx:
|
||||
pass
|
||||
|
||||
|
||||
@client.hybrid_command(
|
||||
name="zagraj_muzyke_mego_ludu",
|
||||
description="Gra muzyke wyszukana na bazie tematow konwersacji na kanale NZ",
|
||||
@@ -1890,7 +1944,9 @@ async def zagraj_muzyke_mego_ludu(ctx):
|
||||
final_key_words.extend(key_words[-MUZYKA_MOJEGO_LUDU_SLOWA_KLUCZOWE:])
|
||||
reply = "Wygenerowana plejlista:\n"
|
||||
async with ctx.typing():
|
||||
logger.info("Zagraj muzyke mego ludu:Zaczynam szukać timestamp %s", datetime.now())
|
||||
logger.info(
|
||||
"Zagraj muzyke mego ludu:Zaczynam szukać timestamp %s", datetime.now()
|
||||
)
|
||||
search_time_glob = datetime.now()
|
||||
file = await wyszukaj(
|
||||
ctx=ctx,
|
||||
@@ -1999,31 +2055,43 @@ async def parametry_muzyki_mego_ludu(
|
||||
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)
|
||||
|
||||
@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
|
||||
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
|
||||
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)
|
||||
@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
|
||||
await interaction.response.edit_message(
|
||||
content="You clicked the button!"
|
||||
) # Send a message when the button is clicked
|
||||
|
||||
|
||||
@client.hybrid_command(
|
||||
@@ -2037,19 +2105,50 @@ async def wyszukaj_linki_do_dokumentow(ctx):
|
||||
# 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)
|
||||
#query_response = await requests.post(f"{LIBRARIAN_SERVICE_ADDRESS}{SEND_QUERY}", json=json_query, timeout=360)
|
||||
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)
|
||||
|
||||
COMM_Q.put()
|
||||
# TODO: tutaj jest informacja UUID o requescie zapisywana w queue i konczymy
|
||||
# TODO: response'y idą do serwera, serwer sobie je mieli i potem wysyła do nas posta albo response
|
||||
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):
|
||||
|
||||
if not query_response.status_code == 200:
|
||||
await ctx.send("Wołaj szefa - coś się wyjebało")
|
||||
return
|
||||
# 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"])
|
||||
result_view = DoSearchView(
|
||||
uuid=str(query_uuid), result_list=query_response.json()["data"]
|
||||
)
|
||||
resulttab = []
|
||||
resultlink = []
|
||||
hit, fetched, total, _ = query_response.json()["data"][0]
|
||||
@@ -2068,10 +2167,19 @@ async def wyszukaj_linki_do_dokumentow(ctx):
|
||||
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))
|
||||
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
|
||||
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",
|
||||
@@ -2106,6 +2214,7 @@ async def krecimy_pornola(ctx):
|
||||
else:
|
||||
ctx.reply("Jak ładnie szefa poprosisz.")
|
||||
|
||||
|
||||
@app.route("/", methods=["POST"])
|
||||
def answer_external_command():
|
||||
record = json.loads(request.data)
|
||||
@@ -2119,6 +2228,7 @@ def answer_external_command():
|
||||
)
|
||||
return return_data
|
||||
|
||||
|
||||
def flask_debug():
|
||||
"""
|
||||
The `flask_debug` function starts a Flask application in debug mode without using the reloader.
|
||||
@@ -2127,6 +2237,7 @@ def flask_debug():
|
||||
# trunk-ignore(bandit/B201)
|
||||
app.run(debug=True, use_reloader=False, host=HOST_ADDRESS, port=PORT_ADDRESS)
|
||||
|
||||
|
||||
def waitress_run():
|
||||
"""
|
||||
The `waitress_run` function serves the `app` on host "0.0.0.0"
|
||||
|
||||
Reference in New Issue
Block a user