mirror of
https://github.com/migatu/conjurer.git
synced 2026-07-14 21:38:38 +00:00
Merge branch 'main' of https://github.com/migatu/conjurer
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
|
||||
from sys import platform
|
||||
from typing import List, Optional, TypedDict
|
||||
from queue import Queue, Empty
|
||||
|
||||
# *==============Imported libraries
|
||||
import discord
|
||||
import eyed3
|
||||
@@ -43,11 +44,9 @@ 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
|
||||
from communication_subroutine import comm_subroutine, IN_COMM_Q, OUT_COMM_Q
|
||||
|
||||
|
||||
COMM_Q = Queue()
|
||||
Music_Config = TypedDict(
|
||||
"Music_Config",
|
||||
{
|
||||
@@ -56,13 +55,19 @@ Music_Config = TypedDict(
|
||||
"requester": List[str],
|
||||
},
|
||||
)
|
||||
class QueryControl():
|
||||
def __init__(self, query_author, query_uuid, query_content, uplogger) -> None:
|
||||
|
||||
|
||||
class QueryControl:
|
||||
def __init__(self, query_author, query_uuid, query_content, uplogger, ctx) -> 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.stop = False
|
||||
self.ctx = ctx
|
||||
self.logger.info(
|
||||
f"Created Query control for {self.author}, {self.uuid}: {self.content}"
|
||||
)
|
||||
self.replies = []
|
||||
|
||||
|
||||
@@ -92,8 +97,8 @@ LIBRARIAN_SERVICE_ADDRESS = "http://192.168.1.192:5001"
|
||||
SEND_QUERY = "/query"
|
||||
TIME_BETWEEN_CALLS = 100000
|
||||
LAST_SPONTANEOUS_CALL = datetime.now()
|
||||
HOST_ADDRESS = "http://192.168.1.192"
|
||||
PORT_ADDRESS = "5000"
|
||||
HOST_ADDRESS = "192.168.1.191"
|
||||
PORT_ADDRESS = 5000
|
||||
|
||||
# *=========================================== Platform Specific Predefines
|
||||
|
||||
@@ -283,8 +288,9 @@ logger.info("Creating discord bot")
|
||||
client = commands.Bot(intents=intents, command_prefix="$")
|
||||
logger.info("Done")
|
||||
logger.info("Creating flask app")
|
||||
app = Flask(__name__)
|
||||
logger.info("Done")
|
||||
|
||||
|
||||
# *=========================================== Define Events
|
||||
@client.event
|
||||
async def on_ready():
|
||||
@@ -292,7 +298,8 @@ async def on_ready():
|
||||
logger.debug("%s has connected to Discord!", client.user)
|
||||
await client.change_presence(activity=discord.Game(name="Axe Throwing Darts"))
|
||||
await client.tree.sync()
|
||||
check_data.start()
|
||||
check_self.start()
|
||||
check_data_q.start()
|
||||
|
||||
|
||||
@client.event
|
||||
@@ -406,36 +413,59 @@ async def on_message(message):
|
||||
logger.debug("Wywolanie obrazka: %s", message.content)
|
||||
try:
|
||||
response = await openAIClient.images.generate(
|
||||
model="dall-e-3",
|
||||
prompt=message.content,
|
||||
size="1024x1024",
|
||||
quality="standard",
|
||||
n=1,
|
||||
model="dall-e-3",
|
||||
prompt=message.content,
|
||||
size="1024x1024",
|
||||
quality="standard",
|
||||
n=1,
|
||||
)
|
||||
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}")
|
||||
# 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}"
|
||||
)
|
||||
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
|
||||
# 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}")
|
||||
# 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}"
|
||||
)
|
||||
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}"))
|
||||
# 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}"
|
||||
)
|
||||
)
|
||||
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}")
|
||||
# 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}"
|
||||
)
|
||||
if response:
|
||||
logger.info(response)
|
||||
image_url = response.data[0].url
|
||||
@@ -452,7 +482,7 @@ async def on_message(message):
|
||||
fnord = discord.File(
|
||||
temp_file_name, spoiler=False, description=message.content
|
||||
)
|
||||
await message.reply(f"{image_desc}",file=fnord)
|
||||
await message.reply(f"{image_desc}", file=fnord)
|
||||
|
||||
|
||||
# *=========================================== Define Functions
|
||||
@@ -649,16 +679,25 @@ async def check_music():
|
||||
await play(MUZYKA["ctx"], MUZYKA["requester"])
|
||||
await asyncio.sleep(2)
|
||||
|
||||
@tasks.loop(seconds=3)
|
||||
# trunk-ignore(pylint/R0915)
|
||||
async def check_data_q():
|
||||
channel = client.get_channel(1062047367337095268)
|
||||
try:
|
||||
data = IN_COMM_Q.get(block=False)
|
||||
await channel.send(f"O. A tak będzie wyglądało coś ciekawego w przyszłości: {data}")
|
||||
except Empty:
|
||||
pass
|
||||
|
||||
@tasks.loop(seconds=120)
|
||||
# trunk-ignore(pylint/R0915)
|
||||
async def check_data():
|
||||
async def check_self():
|
||||
"""
|
||||
The function `check_data` periodically checks for conditions to send messages and manage log files
|
||||
in a Discord channel.
|
||||
"""
|
||||
# trunk-ignore(codespell/misspelled)
|
||||
#logger.info("Heartbeat of cleanup proc")
|
||||
# logger.info("Heartbeat of cleanup proc")
|
||||
channel = client.get_channel(1062047367337095268)
|
||||
messages = [message async for message in channel.history(limit=1)]
|
||||
for mess in messages:
|
||||
@@ -680,7 +719,6 @@ async def check_data():
|
||||
"*Conjurer porządkuje bar, wypala szklanki do czysta miotaczem płomieni ze swojej zbroi i ogólnie wygląda na zajętego....*"
|
||||
)
|
||||
async with channel.typing():
|
||||
#TODO: Tu jest błąd. Ścieżka MEMORY_FIVE_MUZYKA jest absolutna a nie względna
|
||||
path_newfile = f"{LOGSTORE}pamiec_muzyki{datetime.now()}.json"
|
||||
logger.info(path_newfile)
|
||||
with open(MEMORY_FIVE_MUZYKA, "r+", encoding=ENCODING) as file_music_memory:
|
||||
@@ -700,8 +738,7 @@ async def check_data():
|
||||
"*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_SIARA) > 3000000:
|
||||
#TODO: Tu jest błąd. Ścieżka MEMORY_FIVE_MUZYKA jest absolutna a nie względna
|
||||
path_newfile = "{LOGSTORE}pamiec_rozmow{datetime.now()}.json"
|
||||
path_newfile = f"{LOGSTORE}pamiec_rozmow{datetime.now()}.json"
|
||||
logger.info(path_newfile)
|
||||
await channel.send(
|
||||
"*Conjurer porządkuje bar, ścina lekkim laserem pulsacyjnym powierzchnie baru o grubości kilku mikronów i ogólnie wygląda na zajętego....*"
|
||||
@@ -910,33 +947,46 @@ async def handle_response(
|
||||
model=algorithm, messages=history
|
||||
)
|
||||
except openai.APITimeoutError as e:
|
||||
#Handle timeout error, e.g. retry or log
|
||||
result = 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}"
|
||||
# Handle timeout error, e.g. retry or log
|
||||
result = 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:
|
||||
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")
|
||||
# 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",
|
||||
)
|
||||
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")
|
||||
# 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",
|
||||
)
|
||||
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
|
||||
# Handle authentication error, e.g. check credentials or log
|
||||
result = 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
|
||||
# Handle permission error, e.g. check scope or log
|
||||
result = 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:
|
||||
result = f"*Kondziu patrzy na terminal* Wołaj szefa. Zapłacić rachunki za AI trzeba. Jak chcesz to się na #zebranie dorzuć. {e}"
|
||||
except openai.UnprocessableEntityError as e:
|
||||
result = f"*Kondziu patrzy na terminal. Potem na to co każesz mu wysłać....* Ja wiem że jesteśmy w barze BDSM - ale nie da się włożyć TEGO w TO. *Za jego plecami na terminalu pojawia się:* {e}"
|
||||
except openai.APIError as e:
|
||||
#Handle API error, e.g. retry or log
|
||||
# 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 +1058,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 +1182,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 +1264,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 +1282,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 +1914,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 +1953,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 +2064,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
|
||||
# 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
|
||||
# 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
|
||||
# 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(
|
||||
@@ -2034,22 +2111,49 @@ class DoSearchView(discord.ui.View):
|
||||
async def wyszukaj_linki_do_dokumentow(ctx):
|
||||
query = ctx.message.content
|
||||
query_uuid = uuid.uuid4()
|
||||
#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)
|
||||
# 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,
|
||||
)
|
||||
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
|
||||
#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
|
||||
|
||||
if not query_response.status_code == 200:
|
||||
await ctx.send("Wołaj szefa - coś się wyjebało")
|
||||
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
|
||||
#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"])
|
||||
|
||||
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, ctx)
|
||||
OUT_COMM_Q.put(query_object)
|
||||
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):
|
||||
|
||||
# 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"]
|
||||
)
|
||||
resulttab = []
|
||||
resultlink = []
|
||||
hit, fetched, total, _ = query_response.json()["data"][0]
|
||||
@@ -2060,7 +2164,7 @@ async def wyszukaj_linki_do_dokumentow(ctx):
|
||||
item_link = "https://sci-hub.se/" + str(item["DOI"])
|
||||
resultlink.append(item_link)
|
||||
logger.info(len(resulttab))
|
||||
for i in range(0, min(4,len(resulttab))):
|
||||
for i in range(0, min(4, len(resulttab))):
|
||||
logger.info(i)
|
||||
logger.info(resulttab[i])
|
||||
logger.info(resultlink[i])
|
||||
@@ -2068,10 +2172,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,47 +2219,30 @@ 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)
|
||||
logger.info(record)
|
||||
answer_data = None
|
||||
if "UUID" in record and "QUERY" in record and "AUTHOR" in record:
|
||||
answer_data = "Query logged"
|
||||
return_data = (
|
||||
jsonify(isError=False, message="Success", statusCode=200, data=answer_data),
|
||||
200,
|
||||
)
|
||||
return return_data
|
||||
|
||||
def flask_debug():
|
||||
"""
|
||||
The `flask_debug` function starts a Flask application in debug mode without using the reloader.
|
||||
Do not use for production for fucks sake.
|
||||
"""
|
||||
# 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"
|
||||
and port 5000 using the Waitress WSGI server.
|
||||
"""
|
||||
serve(app, host=HOST_ADDRESS, port=PORT_ADDRESS)
|
||||
|
||||
|
||||
# *================================== Run
|
||||
if __name__ == "__main__":
|
||||
#TODO: wpakowac kondzia w wąteki odpalic asynchronicznie rownolegle z flaskiem do sterowania nim
|
||||
# TODO: wpakowac kondzia w wątki odpalic asynchronicznie rownolegle z flaskiem do sterowania nim
|
||||
logger.info("Starting discord bot")
|
||||
threads = []
|
||||
logger.info("Starting discord bot: Creating threads")
|
||||
threads.append(threading.Thread(target=client.run, args=(TOKEN,)))
|
||||
threads.append(threading.Thread(target=comm_subroutine, args=(logger,)))
|
||||
logger.info("Starting discord bot: Starting threads")
|
||||
i = 0
|
||||
for worker in threads:
|
||||
i+=1
|
||||
logger.info("Starting discord bot: Starting thread {i}")
|
||||
worker.start()
|
||||
logger.info("Starting discord bot: Joining threads")
|
||||
i=0
|
||||
for worker in threads:
|
||||
i+=1
|
||||
logger.info("Starting discord bot: Joining thread {i}")
|
||||
worker.join()
|
||||
|
||||
#widok - generuje się 5 stron po 4 linki
|
||||
# widok - generuje się 5 stron po 4 linki
|
||||
# odśwież - zamienić na "dalej" - zaciąga kolejne 20 rezultatów
|
||||
# po wyslaniu czekamy na odbior i dodajemy UUID oraz nick poszukiwacza do queue ktora jest sprawdzana
|
||||
# flask sobie chodzi i jak dostaje posta z wynikami to wyciaga z queue UUID i odpowiada że znalazła
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import logging
|
||||
import threading
|
||||
import json
|
||||
from queue import Queue, Empty
|
||||
from flask import Flask, jsonify, request
|
||||
from waitress import serve
|
||||
|
||||
HOST_ADDRESS = "192.168.1.191"
|
||||
PORT_ADDRESS = 5000
|
||||
OUT_COMM_Q = Queue()
|
||||
IN_COMM_Q = Queue()
|
||||
internal_q = Queue()
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route("/conjurer", methods=["POST"])
|
||||
def answer_external_command():
|
||||
record = json.loads(request.data)
|
||||
app.logger.info(record)
|
||||
app.logger.info("DATA RECEIVED")
|
||||
|
||||
|
||||
while True:
|
||||
try:
|
||||
q_data = internal_q.get(block=False)
|
||||
except Empty:
|
||||
break
|
||||
if q_data.uuid in record:
|
||||
pass
|
||||
|
||||
return jsonify("SUCCESS")
|
||||
|
||||
@app.route("/conjurer", methods=["GET"])
|
||||
def check_alive():
|
||||
return jsonify("ALIVE")
|
||||
|
||||
def flask_debug(_logger):
|
||||
"""
|
||||
The `flask_debug` function starts a Flask application in debug mode without using the reloader.
|
||||
Do not use for production for fucks sake.
|
||||
"""
|
||||
_logger.info("Attempt debug")
|
||||
# trunk-ignore(bandit/B201)
|
||||
app.run(debug=True, use_reloader=False, host=HOST_ADDRESS, port=PORT_ADDRESS)
|
||||
|
||||
|
||||
def waitress_run(_logger):
|
||||
"""
|
||||
The `waitress_run` function serves the `app` on host "0.0.0.0"
|
||||
and port 5000 using the Waitress WSGI server.
|
||||
"""
|
||||
_logger.info("Attempt waitress")
|
||||
serve(app, host=HOST_ADDRESS, port=PORT_ADDRESS)
|
||||
|
||||
def scan_queue(_logger):
|
||||
while True:
|
||||
data = OUT_COMM_Q.get()
|
||||
_logger.info(data)
|
||||
internal_q.put(data)
|
||||
query_list.append(data)
|
||||
|
||||
def comm_subroutine(logger):
|
||||
#logger.setLevel(logging.DEBUG)
|
||||
logger.info("Started")
|
||||
threads = []
|
||||
threads.append(threading.Thread(target=flask_debug, args=(logger,)))
|
||||
#threads.append(threading.Thread(target=waitress_run, args=(logger,)))
|
||||
threads.append(threading.Thread(target=scan_queue,args=(logger,)))
|
||||
|
||||
for worker in threads:
|
||||
worker.start()
|
||||
for worker in threads:
|
||||
worker.join()
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging_client = logging.getLogger(__name__)
|
||||
comm_subroutine(logging_client)
|
||||
@@ -266,7 +266,6 @@ if __name__ == "__main__":
|
||||
threads = []
|
||||
threads.append(threading.Thread(target=waitress_run))
|
||||
threads.append(threading.Thread(target=thread_rescan))
|
||||
#threads.append(threading.Thread(target=flask_debug))
|
||||
|
||||
for worker in threads:
|
||||
worker.start()
|
||||
|
||||
@@ -11,3 +11,5 @@ requests
|
||||
spotipy
|
||||
tiktoken
|
||||
PyNaCl
|
||||
flask
|
||||
waitress
|
||||
Reference in New Issue
Block a user