Commit ae8c6e36 by lei
parents 0e5a1225 770cd2e3
......@@ -65,6 +65,7 @@ async def imagine(data=Body(None)):
error_message = ""
try:
response = await mid_journey.imagine(guild_id, channel_id, prompt)
print(123)
if response.status >= 400:
error_message = "请求失败;请稍后再试"
else:
......@@ -72,6 +73,7 @@ async def imagine(data=Body(None)):
"message": "您的图像正在准备中,请稍等片刻..."
}
except Exception as e:
print(e)
response = {}
use_time = time.time() - start_time
if response:
......@@ -86,9 +88,10 @@ async def download_images(data=Body(None)):
data = data['data']
url = data['url']
name = data['name']
index = data['index']
error_message = ""
try:
response = await download_image(url, name)
response = await download_image(url, name, index)
except Exception as e:
print(e)
response = {}
......
import json
import discord
from discord.ext import commands
from loguru import logger
from salai.common_config import TOKEN, REDIS_HOST, REDIS_PORT, REDIS_PASSWORD, REDIS_DB
from aredis import StrictRedis, ConnectionPool
from salai.helper import download_image
class RedisConnectionPoolSingleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
"""
aredis connection
:param args:
:param kwargs:
"""
if cls._instance is None:
cls._instance = ConnectionPool(max_connections=1000, host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB,
password=REDIS_PASSWORD)
return cls._instance
redis_con = StrictRedis(connection_pool=RedisConnectionPoolSingleton())
intents = discord.Intents.default()
intents.messages = True
client = commands.Bot(command_prefix='>', intents=intents)
DIRECTORY = "/www/wwwroot/salai"
INPUT_FOLDER = "input"
OUTPUT_FOLDER = "output"
@client.event
async def on_message(message):
......@@ -22,13 +42,16 @@ async def on_message(message):
"guild_id": message.guild.id,
"guild_name": message.guild.name,
}
logger.info(message_data)
for attachment in message.attachments:
if attachment.filename.lower().endswith((".png", ".jpg", ".jpeg", ".gif")):
message_data["attachment_url"] = attachment.url
message_data["attachment_filename"] = attachment.filename
logger.info(f"message 参数: {message_data}")
download_result = await download_image(message_data["attachment_url"], message_data["attachment_filename"])
message_data['attachment_url'] = download_result[0]
await redis_con.lpush("laravel_database_discord_message", json.dumps(message_data))
client.run("MTA5NTg4MzI5MzkyNjM3MTQ0OA.GUjqoM.8tFZ1phIIV-NO9l9sJqNPYuCbY8kjmZfyi48HA")
client.run(TOKEN)
......@@ -13,4 +13,15 @@ ACCESS_KEY_ID = config.get('oss', 'ACCESS_KEY_ID')
ACCESS_KEY_SECRET = config.get('oss', 'ACCESS_KEY_SECRET')
ENDPOINT = config.get('oss', 'ENDPOINT')
BUCKET_NAME = config.get('oss', 'BUCKET_NAME')
SAVE_PATH = config.get('oss', 'SAVE_PATH')
\ No newline at end of file
SAVE_PATH = config.get('oss', 'SAVE_PATH')
# 账号配置
TOKEN = config.get('user', 'TOKEN')
# redis配置
REDIS_HOST = config.get('redis', 'HOST')
REDIS_PORT = config.get('redis', 'PORT')
REDIS_PASSWORD = config.get('redis', 'PASSWORD')
REDIS_DB = config.get('redis', 'DB')
......@@ -6,4 +6,13 @@ ENDPOINT=
ACCESS_KEY_ID=
ACCESS_KEY_SECRET=
BUCKET_NAME=
SAVE_PATH=
\ No newline at end of file
SAVE_PATH=
[user]
TOKEN=
[redis]
HOST=
PORT=
PASSWORD=
DB=
......@@ -45,38 +45,51 @@ async def oss_upload(file_name, file_path):
return bucket.put_object_from_file(file_name, file_path)
async def download_image(url, filename):
async def download_image(url: str, filename: str, index: int = 0):
"""
下载图片
"""
r = requests.get(url)
r.raise_for_status()
# 打开一个文件作为文件对象
save_image_list = list()
filename = get_hash(filename) + ".png"
path = f"{DOWNLOAD_IMAGE_PATH}{filename}"
with open(path, 'wb') as f:
f.write(r.content)
f.close()
top_left, top_right, bottom_left, bottom_right = split_image(path)
image_list = [top_left, top_right, bottom_left, bottom_right]
save_image_list = list()
number = 1
for image in image_list:
new_file_name = os.path.join(f"{DOWNLOAD_IMAGE_PATH}/{number}_{filename}")
image.save(new_file_name)
temp = {
"name": f"{number}_{filename}",
"path": new_file_name
}
save_image_list.append(temp)
number += 1
if index == 0:
save_image_list.append(
{
"name": f"{filename}",
"path": path
}
)
if index > 0:
top_left, top_right, bottom_left, bottom_right = split_image(path)
image_list = [top_left, top_right, bottom_left, bottom_right]
number = 0
for image in image_list:
number += 1
if index != number:
continue
new_file_name = os.path.join(f"{DOWNLOAD_IMAGE_PATH}/{number}_{filename}")
image.save(new_file_name)
temp = {
"name": f"{number}_{filename}",
"path": new_file_name
}
save_image_list.append(temp)
result = list()
for file in save_image_list:
save_name = f"{SAVE_PATH}/{file['name']}"
await oss_upload(save_name, file['path'])
save_name = "https://{}.{}/{}".format(BUCKET_NAME, ENDPOINT, save_name)
result.append(save_name)
if len(save_image_list) > 0:
for file in save_image_list:
save_name = f"{SAVE_PATH}/{file['name']}"
await oss_upload(save_name, file['path'])
save_name = "https://{}.{}/{}".format(BUCKET_NAME, ENDPOINT, save_name)
result.append(save_name)
return result
import json
import aiohttp
......@@ -33,10 +35,9 @@ class MidJourney:
"description": "The prompt to imagine",
"required": True}]},
"attachments": []}}
async with aiohttp.ClientSession() as session:
async with session.post(
"https://discord.com/api/v9/interactions",
url="https://discord.com/api/v9/interactions",
headers=self.headers,
json=payload,
timeout=5,
......@@ -44,9 +45,3 @@ class MidJourney:
) as resp:
response = resp
return response
if __name__ == '__main__':
token = "MTA0MDkxMDY4NzgzODQyMTA2Mw.Gj2fzk.SvEdsuifUw9deKCbQaWGFs4j6alq3KTTsXGP3w"
mid_journey = MidJourney(token)
mid_journey.imagine('1095628793860857957', '1095628793860857960', 'this is a picture')
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment