Skip to content

Instantly share code, notes, and snippets.

@readpan
Created May 18, 2023 07:21
Show Gist options
  • Save readpan/e93f03bf8f38ffa3caffac9e4fb5f858 to your computer and use it in GitHub Desktop.
Save readpan/e93f03bf8f38ffa3caffac9e4fb5f858 to your computer and use it in GitHub Desktop.
import json
import asyncio
import aiohttp
from random import randint
class Queue:
def __init__(self, concurrency_limit):
self.semaphore = asyncio.Semaphore(concurrency_limit)
async def add_task(self, task):
async with self.semaphore:
return await task
class Midjourney:
def __init__(self, ServerId, SalaiToken, ChannelId):
if not ServerId or not SalaiToken or not ChannelId:
raise ValueError("ServerId, ChannelId and SalaiToken are required")
self.ApiQueue = Queue(1)
self.config = {
'ServerId': ServerId,
'SalaiToken': SalaiToken,
'ChannelId': ChannelId,
"SessionId": "8bb7f5b79c7a49f7d0824ab4b8773a81",
"MaxWait": 10
}
async def Imagine(self, prompt, loading=None):
if "--seed" not in prompt:
speed = randint(1000, 9999)
prompt = f"{prompt} --seed {speed}"
print('Imagine', prompt)
httpStatus = await self.ImagineApi(prompt)
if httpStatus != 204:
raise Exception(f"ImagineApi failed with status {httpStatus}")
return httpStatus
async def safeInteractions(self, payload):
return await self.ApiQueue.add_task(
self.interactions(payload)
)
async def interactions(self, payload):
headers = {
"Content-Type": "application/json",
"Authorization": self.config['SalaiToken']
}
async with aiohttp.ClientSession() as session:
async with session.post("https://discord.com/api/v9/interactions", headers=headers,
data=json.dumps(payload)) as response:
status = response.status
await asyncio.sleep(0.95)
if status >= 400:
print('error config', self.config)
return status
# Define other methods (ImagineApi, VariationApi, UpscaleApi, UpscaleByCustomID, etc.) here...
async def ImagineApi(self, prompt):
payload = {
"type": 2,
"application_id": "936929561302675456",
"guild_id": self.config['ServerId'],
"channel_id": self.config['ChannelId'],
"session_id": self.config['SessionId'],
"data": {
"version": "1077969938624553050",
"id": "938956540159881230",
"name": "imagine",
"type": 1,
"options": [
{
"type": 3,
"name": "prompt",
"value": prompt,
},
],
"application_command": {
"id": "938956540159881230",
"application_id": "936929561302675456",
"version": "1077969938624553050",
"default_permission": True,
"default_member_permissions": None,
"type": 1,
"nsfw": False,
"name": "imagine",
"description": "Create images with Midjourney",
"dm_permission": True,
"options": [
{
"type": 3,
"name": "prompt",
"description": "The prompt to imagine",
"required": True,
},
],
},
"attachments": [],
},
}
return await self.safeInteractions(payload)
if __name__ == '__main__':
mdj = Midjourney("", # server id
"", # authentication
"") # channel id
prompt = "" # your prompt
asyncio.run(mdj.Imagine(prompt))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment