Commit ae8c6e36 by lei
parents 0e5a1225 770cd2e3
...@@ -65,6 +65,7 @@ async def imagine(data=Body(None)): ...@@ -65,6 +65,7 @@ async def imagine(data=Body(None)):
error_message = "" error_message = ""
try: try:
response = await mid_journey.imagine(guild_id, channel_id, prompt) response = await mid_journey.imagine(guild_id, channel_id, prompt)
print(123)
if response.status >= 400: if response.status >= 400:
error_message = "请求失败;请稍后再试" error_message = "请求失败;请稍后再试"
else: else:
...@@ -72,6 +73,7 @@ async def imagine(data=Body(None)): ...@@ -72,6 +73,7 @@ async def imagine(data=Body(None)):
"message": "您的图像正在准备中,请稍等片刻..." "message": "您的图像正在准备中,请稍等片刻..."
} }
except Exception as e: except Exception as e:
print(e)
response = {} response = {}
use_time = time.time() - start_time use_time = time.time() - start_time
if response: if response:
...@@ -86,9 +88,10 @@ async def download_images(data=Body(None)): ...@@ -86,9 +88,10 @@ async def download_images(data=Body(None)):
data = data['data'] data = data['data']
url = data['url'] url = data['url']
name = data['name'] name = data['name']
index = data['index']
error_message = "" error_message = ""
try: try:
response = await download_image(url, name) response = await download_image(url, name, index)
except Exception as e: except Exception as e:
print(e) print(e)
response = {} response = {}
......
import json
import discord import discord
from discord.ext import commands from discord.ext import commands
from loguru import logger 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 = discord.Intents.default()
intents.messages = True intents.messages = True
client = commands.Bot(command_prefix='>', intents=intents) client = commands.Bot(command_prefix='>', intents=intents)
DIRECTORY = "/www/wwwroot/salai"
INPUT_FOLDER = "input"
OUTPUT_FOLDER = "output"
@client.event @client.event
async def on_message(message): async def on_message(message):
...@@ -22,13 +42,16 @@ async def on_message(message): ...@@ -22,13 +42,16 @@ async def on_message(message):
"guild_id": message.guild.id, "guild_id": message.guild.id,
"guild_name": message.guild.name, "guild_name": message.guild.name,
} }
logger.info(message_data) logger.info(message_data)
for attachment in message.attachments: for attachment in message.attachments:
if attachment.filename.lower().endswith((".png", ".jpg", ".jpeg", ".gif")): if attachment.filename.lower().endswith((".png", ".jpg", ".jpeg", ".gif")):
message_data["attachment_url"] = attachment.url message_data["attachment_url"] = attachment.url
message_data["attachment_filename"] = attachment.filename message_data["attachment_filename"] = attachment.filename
logger.info(f"message 参数: {message_data}") 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(TOKEN)
client.run("MTA5NTg4MzI5MzkyNjM3MTQ0OA.GUjqoM.8tFZ1phIIV-NO9l9sJqNPYuCbY8kjmZfyi48HA")
...@@ -13,4 +13,15 @@ ACCESS_KEY_ID = config.get('oss', 'ACCESS_KEY_ID') ...@@ -13,4 +13,15 @@ ACCESS_KEY_ID = config.get('oss', 'ACCESS_KEY_ID')
ACCESS_KEY_SECRET = config.get('oss', 'ACCESS_KEY_SECRET') ACCESS_KEY_SECRET = config.get('oss', 'ACCESS_KEY_SECRET')
ENDPOINT = config.get('oss', 'ENDPOINT') ENDPOINT = config.get('oss', 'ENDPOINT')
BUCKET_NAME = config.get('oss', 'BUCKET_NAME') BUCKET_NAME = config.get('oss', 'BUCKET_NAME')
SAVE_PATH = config.get('oss', 'SAVE_PATH') SAVE_PATH = config.get('oss', 'SAVE_PATH')
\ No newline at end of file
# 账号配置
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= ...@@ -6,4 +6,13 @@ ENDPOINT=
ACCESS_KEY_ID= ACCESS_KEY_ID=
ACCESS_KEY_SECRET= ACCESS_KEY_SECRET=
BUCKET_NAME= BUCKET_NAME=
SAVE_PATH= SAVE_PATH=
\ No newline at end of file
[user]
TOKEN=
[redis]
HOST=
PORT=
PASSWORD=
DB=
...@@ -45,38 +45,51 @@ async def oss_upload(file_name, file_path): ...@@ -45,38 +45,51 @@ async def oss_upload(file_name, file_path):
return bucket.put_object_from_file(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 = requests.get(url)
r.raise_for_status() r.raise_for_status()
# 打开一个文件作为文件对象 # 打开一个文件作为文件对象
save_image_list = list()
filename = get_hash(filename) + ".png" filename = get_hash(filename) + ".png"
path = f"{DOWNLOAD_IMAGE_PATH}{filename}" path = f"{DOWNLOAD_IMAGE_PATH}{filename}"
with open(path, 'wb') as f: with open(path, 'wb') as f:
f.write(r.content) f.write(r.content)
f.close() f.close()
top_left, top_right, bottom_left, bottom_right = split_image(path) if index == 0:
image_list = [top_left, top_right, bottom_left, bottom_right] save_image_list.append(
save_image_list = list() {
number = 1 "name": f"{filename}",
for image in image_list: "path": path
new_file_name = os.path.join(f"{DOWNLOAD_IMAGE_PATH}/{number}_{filename}") }
image.save(new_file_name) )
temp = {
"name": f"{number}_{filename}", if index > 0:
"path": new_file_name top_left, top_right, bottom_left, bottom_right = split_image(path)
} image_list = [top_left, top_right, bottom_left, bottom_right]
save_image_list.append(temp) number = 0
number += 1 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() result = list()
for file in save_image_list: if len(save_image_list) > 0:
save_name = f"{SAVE_PATH}/{file['name']}" for file in save_image_list:
await oss_upload(save_name, file['path']) save_name = f"{SAVE_PATH}/{file['name']}"
save_name = "https://{}.{}/{}".format(BUCKET_NAME, ENDPOINT, save_name) await oss_upload(save_name, file['path'])
result.append(save_name) save_name = "https://{}.{}/{}".format(BUCKET_NAME, ENDPOINT, save_name)
result.append(save_name)
return result return result
import json
import aiohttp import aiohttp
...@@ -33,10 +35,9 @@ class MidJourney: ...@@ -33,10 +35,9 @@ class MidJourney:
"description": "The prompt to imagine", "description": "The prompt to imagine",
"required": True}]}, "required": True}]},
"attachments": []}} "attachments": []}}
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.post( async with session.post(
"https://discord.com/api/v9/interactions", url="https://discord.com/api/v9/interactions",
headers=self.headers, headers=self.headers,
json=payload, json=payload,
timeout=5, timeout=5,
...@@ -44,9 +45,3 @@ class MidJourney: ...@@ -44,9 +45,3 @@ class MidJourney:
) as resp: ) as resp:
response = resp response = resp
return response 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