├── .github
├── FUNDING.yml
└── ISSUE_TEMPLATE
│ └── bug_report.md
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── SECURITY.md
├── composer.json
├── example.php
├── example_old_method.php
├── img
├── cli-php.png
├── credentials.png
├── get-user-token.png
├── result.png
└── send-message.png
└── src
└── MidjourneyImageCreator.php
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | ko_fi: danielgomes53123
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /vendor
2 | composer.lock
3 | Thumbs.db
4 | .DS_Store
5 | /.fleet
6 | /.idea
7 | /.vscode
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | .
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guide
2 |
3 | Thank you for considering to contribute to this repository! Your collaboration is greatly appreciated. Please follow the guidelines below when contributing:
4 |
5 | ## How to contribute
6 |
7 | 1. Fork the repository.
8 | 2. Create a new branch based on the current main/master branch. Give your branch a descriptive name, such as `fix-bug` or `add-feature`.
9 | 3. Make your changes in the new branch.
10 | 4. Test your changes locally to ensure everything works as expected.
11 | 5. Commit your changes, using descriptive commit messages that briefly explain the changes being made.
12 | 6. Submit a Pull Request (PR) to the upstream repository, comparing your branch to the main/master branch.
13 | 7. In your PR's description, clearly explain the changes being made, the purpose of the changes, and any issue or bug the changes fix.
14 |
15 | ## Reporting Bugs
16 |
17 | - When reporting a bug, please include:
18 | - A clear and descriptive title.
19 | - A step-by-step description of how to reproduce the bug, including any necessary code snippets or examples.
20 | - Expected behavior vs. actual behavior.
21 | - Any relevant screenshots, logs, or error messages.
22 | - Information about your environment, such as your operating system, browser, or relevant software versions.
23 |
24 | ## Suggesting Features
25 |
26 | - For feature suggestions, please include the following information:
27 | - A clear and descriptive title.
28 | - A detailed description of the proposed feature.
29 | - Explanation of the benefits of the feature and why it should be added to the project.
30 | - Any relevant examples or mockups to help illustrate the concept.
31 |
32 | ## Code Style Guidelines
33 |
34 | - Follow the existing code style that is used throughout the project.
35 | - Use meaningful variable and function names.
36 | - Include helpful comments and documentation where needed.
37 | - Break down large functions into smaller, reusable functions.
38 | - Optimize code for readability and maintainability.
39 |
40 | ## Pull Request Guidelines
41 |
42 | - Keep your PRs focused on a single issue or feature.
43 | - Ensure your PR can be merged with the latest version of the main/master branch.
44 | - Address any feedback or requested changes promptly.
45 | - Provide tests for your changes, where applicable.
46 | - Update documentation or comments in the code if needed.
47 |
48 | ## Community Guidelines
49 |
50 | - Be respectful and professional when interacting with other contributors.
51 | - Understand that not all contributions or suggestions may be accepted.
52 | - Offer constructive feedback if you disagree with a decision, but be respectful and understanding of different opinions and perspectives.
53 |
54 | ## Future Contributions
55 |
56 | If you become a regular contributor, you may want to review the following:
57 |
58 | - Familiarize yourself with the project roadmap and priorities, to better align your contributions with the project's goals.
59 | - Consider attending any community meetings or discussions related to the project.
60 | - Communicate your ideas and intentions with other contributors to ensure efficient collaboration.
61 | - Offer your help to review and test other contributors' PRs, as this will help maintain the overall quality of the project and speed up the merging process.
62 | - Provide feedback on project issues and feature requests, to help shape the project's direction and future development.
63 | - Be open to learning from the experiences and expertise of other contributors in the community, and share your own knowledge and insights as well.
64 |
65 | ## Additional Resources
66 |
67 | - To better understand the codebase, review the project's documentation, code structure, and example usage.
68 | - If you are new to the project or the technology being used, take the time to learn and familiarize yourself with the relevant tools, libraries, or frameworks before diving into contribution.
69 | - Join the project's mailing list, chat room, or forums for regular updates, news, and discussions. This will help you stay informed and involved in the community.
70 |
71 | ## Contributor Recognition
72 |
73 | We greatly appreciate the efforts of all our contributors. To recognize your valuable contributions to the project, we will:
74 |
75 | - Acknowledge your contributions in the project's documentation, release notes, or relevant sections.
76 | - Showcase top contributors on the project's README, website, or social media platforms, if applicable.
77 | - Provide contributor badges or certificates, depending on the nature and impact of your contributions.
78 | - Make an effort to personally thank each contributor for their work and involvement in the project.
79 |
80 | Remember that your contributions not only positively impact the project, but also help establish your reputation as a skilled and collaborative developer within the open-source community. We highly value your input and dedication, and we look forward to working together in creating a successful, high-quality project.
81 |
82 | If you have any questions, concerns, or suggestions regarding the contributor guidelines, please feel free to reach out to the project maintainers or open an issue in the repository. Together, we can make this project a great resource for everyone.
83 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Daniel Gomes
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Utilize the Discord API to generate images with the Midjourney Bot.
2 |
3 | This PHP library offers a user-friendly interface for creating images with the Midjourney Bot, leveraging the capabilities of the Discord API.
4 |
5 | This version has the capability to incorporate example **images via URLs** into the Midjourney prompts, providing full compatibility with both **private and public channels**.
6 |
7 |
8 | ## Installation
9 |
10 | You can seamlessly integrate this library into your project using Composer. To do so, execute the following command in your project's root directory:
11 |
12 | `composer require batdan/midjourney-api-php`
13 |
14 |
15 | ## Usage
16 |
17 | ### Fundamental Usage Instructions
18 |
19 | To generate an image with the Midjourney Bot, initiate an instance of the Midjourney class:
20 |
21 | ```php
22 | use batdan\ai\MidjourneyImageCreator;
23 |
24 | $discordChannelId = 'YOUR_DISCORD_CHANNEL_ID';
25 | $discordUserToken = 'YOUR_DISCORD_USER_TOKEN';
26 |
27 | $midjourney = new MidjourneyImageCreator($discordChannelId, $discordUserToken);
28 |
29 | // Example of a prompt: text is separated from tags
30 | $promptText = "aerial view of a giant fish tank shaped like a tower in the middle of new york city, https://depuismonhamac.jardiland.com/wp-content/uploads/2019/06/AdobeStock_196378179.jpeg";
31 | $promptTags = "8k octane render, photorealistic --ar 9:20 --v 5";
32 |
33 | /**
34 | * The imageCreationV2 method is responsible for randomly selecting an image from the 4 options provided by Midjourney.
35 | * If you want to specify a particular image, you can pass its identifier (ranging from 0 to 3) as the third parameter.
36 | *
37 | * Example: $midjourneyImageCreator->imageCreation($promptText, $promptTags, 0);
38 | *
39 | * This will generate an image for the given prompt, using the specified image identifier (in this case, 0).
40 | */
41 | $message = $midjourney->imageCreationV2($promptText, $promptTags);
42 | $imgUrl = $message->upscaled_photo_url;
43 |
44 | echo chr(10) . chr(10);
45 | echo $imgUrl;
46 | echo chr(10) . chr(10);
47 | ```
48 |
49 |
50 | ### Constructor
51 |
52 | - `$discordChannelId`:
53 | - Substitute this value with the Channel ID where the Midjourney Bot has been installed. The Channel ID can be obtained by right-clicking on the channel and **selecting Copy Channel ID**.
54 | - Keep in mind that you can invite the Midjourney Bot to your own server to better organize your work. For more information, refer to https://docs.midjourney.com/docs/invite-the-bot
55 |
56 | - `$discordUserToken`:
57 | - To retrieve your Discord User Token, you will need to use the Developer Tools in your browser and look into the network data. Here are the steps:
58 |
59 | - Open Discord in your browser (not the app).
60 | - Open the Developer Tools (you can typically open this by pressing F12 or Ctrl + Shift + I on Windows/Linux or Cmd + Option + I on MacOS).
61 | - Navigate to the **"Network"** tab.
62 | - In the filter box, type **"messages"** to narrow down the list of network requests.
63 | - Send a message in any Discord channel.
64 |
65 | 
66 |
67 | - Look at the network requests that pop up after sending the message, select the one that has **"messages"** in its name.
68 | - Within the Headers tab, look for the request header named "Authorization". The value of this header **is your User Token**.
69 |
70 | 
71 |
72 |
73 | **Important Note:** Keep your User Token strictly confidential. Anyone who has your token can take control of your Discord account. Never share it with anyone and don't publish it online. If you think your token may have been compromised, change your password immediately as this will cause your current token to become invalid.
74 |
75 |
76 | ## Optimal Performance: Consider Using the CLI Script
77 | To ensure optimal performance and avoid any potential execution time issues, we recommend utilizing the CLI (Command Line Interface) script for your task. The CLI script provides a streamlined and efficient environment, allowing for faster processing and smoother execution.
78 |
79 |
80 | Before running the script, please fill in the **Channel ID** and **User Token** in the **example.php** file:
81 |
82 | 
83 |
84 | 
85 |
86 |
87 | The process can take approximately one minute.
88 |
89 | Automatically Generated Image:
90 |
91 | 
92 |
93 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | | Version | Supported |
6 | | ------------- | ------------------ |
7 | | PHP 8.3.x | :white_check_mark: |
8 | | PHP 8.2.x | :white_check_mark: |
9 | | PHP 8.1.x | :white_check_mark: |
10 | | PHP 8.0.x | :white_check_mark: |
11 | | PHP 7.4.x | :white_check_mark: |
12 | | PHP 7.3.x | :white_check_mark: |
13 | | PHP 7.2.5 | :white_check_mark: |
14 | | Guzzle 7.5.x | :white_check_mark: |
15 | | Guzzle 7.4.x | :x: |
16 | | Guzzle 7.3.x | :x: |
17 | | Guzzle 7.2.x | :x: |
18 |
19 | ## Reporting a Vulnerability
20 |
21 | If you discover a security vulnerability within this project, please leave a message in the GitHub discussion space. All security vulnerabilities will be promptly addressed.
22 |
23 | Please do not disclose security-related issues publicly until a fix has been announced and made available. We take security seriously and appreciate your efforts to responsibly disclose your findings.
24 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "batdan/midjourney-api-php",
3 | "description": "Generate images Midjourney (Discord API). URLs in prompt accepted",
4 | "keywords": [
5 | "php",
6 | "image-generation",
7 | "midjourney",
8 | "graphics",
9 | "image-processing",
10 | "image-link",
11 | "image-creation",
12 | "image-manipulation",
13 | "dynamic-images"
14 | ],
15 | "extra": {
16 | "readme": "README.md"
17 | },
18 | "license": "MIT",
19 | "support": {
20 | "issues": "https://github.com/batdan/midjourney-api-php/issues",
21 | "source": "https://github.com/batdan/midjourney-api-php"
22 | },
23 | "autoload": {
24 | "psr-4": {
25 | "batdan\\ai\\": "src/"
26 | }
27 | },
28 | "authors": [
29 | {
30 | "name": "Daniel Gomes"
31 | }
32 | ],
33 | "require": {
34 | "php": ">=7.2.5",
35 | "guzzlehttp/guzzle": "^7.5"
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/example.php:
--------------------------------------------------------------------------------
1 | imageCreationV2($promptText, $promptTags);
22 | $imgUrl = $message->upscaled_photo_url;
23 |
24 | echo chr(10);
25 | echo chr(10);
26 | echo $imgUrl;
27 | echo chr(10);
28 | echo chr(10);
29 |
--------------------------------------------------------------------------------
/example_old_method.php:
--------------------------------------------------------------------------------
1 | imageCreation($prompt);
23 | $imgUrl = $message->upscaled_photo_url;
24 |
25 | echo chr(10);
26 | echo chr(10);
27 | echo $imgUrl;
28 | echo chr(10);
29 | echo chr(10);
30 |
--------------------------------------------------------------------------------
/img/cli-php.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/batdan/midjourney-api-php/5404e6b0421ba25e512b0ad61039090f0e251d68/img/cli-php.png
--------------------------------------------------------------------------------
/img/credentials.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/batdan/midjourney-api-php/5404e6b0421ba25e512b0ad61039090f0e251d68/img/credentials.png
--------------------------------------------------------------------------------
/img/get-user-token.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/batdan/midjourney-api-php/5404e6b0421ba25e512b0ad61039090f0e251d68/img/get-user-token.png
--------------------------------------------------------------------------------
/img/result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/batdan/midjourney-api-php/5404e6b0421ba25e512b0ad61039090f0e251d68/img/result.png
--------------------------------------------------------------------------------
/img/send-message.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/batdan/midjourney-api-php/5404e6b0421ba25e512b0ad61039090f0e251d68/img/send-message.png
--------------------------------------------------------------------------------
/src/MidjourneyImageCreator.php:
--------------------------------------------------------------------------------
1 | limitProcess = 3;
44 |
45 | $this->sessionId = md5(uniqid());
46 |
47 | $this->channelId = $discordChannelId;
48 | $this->oauthToken = $discordUserToken;
49 |
50 | // Création du client GuzzleHttp
51 | $this->client = new Client([
52 | 'base_uri' => $this->apiUrl,
53 | 'headers' => [
54 | 'Authorization' => $this->oauthToken
55 | ]
56 | ]);
57 |
58 | // Guild Id recovery
59 | $response = $this->client->get('channels/' . $this->channelId);
60 | $body = $response->getBody()->getContents();
61 | $json = json_decode($body, true);
62 |
63 | $this->guildId = $json['guild_id'] ?? null;
64 |
65 | // User id recovery
66 | $response = $this->client->get('users/@me');
67 | $body = $response->getBody()->getContents();
68 | $json = json_decode($body, true);
69 |
70 | $this->userId = $json['id'];
71 |
72 | // Retrieval of dataId and dataVersion
73 | $response = $this->client->get('applications/' . $this->applicationId . '/commands');
74 | $body = $response->getBody()->getContents();
75 | $json = json_decode($body, true);
76 |
77 | $this->dataId = $json[0]['id'];
78 | $this->dataVersion = $json[0]['version'];
79 | }
80 |
81 |
82 | /**
83 | * Global method to recover an image
84 | *
85 | * In this method, I separated the textual part of the prompt and the tags.
86 | * This allowed me to no longer rely on the "seed" tag to pass a uniqid necessary for retrieving images.
87 | * With this method, all Midjouney prompts functionality is available
88 | *
89 | * @param string $promptText Midjourney prompt text
90 | * @param string $promptTags Midjourney prompt tags
91 | * @param integer $upscale_index Choice of image to upscale - default: random 0.3
92 | * @return object
93 | */
94 | public function imageCreationV2($promptText, $promptTags, $upscale_index = null)
95 | {
96 | // Check number of processes and wait if necessary
97 | $checkCountProcess = $this->checkCountProcess();
98 | if (!$checkCountProcess) {
99 | return (object) [
100 | 'imagine_message_id' => null,
101 | 'upscaled_photo_url' => null
102 | ];
103 | }
104 |
105 | $this->countProcess++;
106 |
107 | // Random image selection if $upscale_index is null
108 | if (is_null($upscale_index)) $upscale_index = rand(0, 3);
109 |
110 | // Unique ID to find the image once created
111 | $this->uniqueId = time() - rand(0, 1000);
112 | $prompt = $promptText . ' ' . $this->uniqueId . ' ' . $promptTags;
113 |
114 | $imagine = $this->getImagine($prompt);
115 | $upscaled_photo_url = $this->getUpscale($imagine, $upscale_index);
116 |
117 | $this->countProcess--;
118 |
119 | return (object) [
120 | 'imagine_message_id' => $imagine['id'],
121 | 'upscaled_photo_url' => $upscaled_photo_url
122 | ];
123 | }
124 |
125 |
126 | /**
127 | * Global method to recover an image
128 | *
129 | * This method has been kept to ensure backward compatibility of projects using it
130 | *
131 | * @param string $prompt Midjourney prompt
132 | * @param integer $upscale_index Choice of image to upscale - default: random 0.3
133 | * @return object
134 | */
135 | public function imageCreation($prompt, $upscale_index = null)
136 | {
137 | // Check number of processes and wait if necessary
138 | $checkCountProcess = $this->checkCountProcess();
139 | if (!$checkCountProcess) {
140 | return (object) [
141 | 'imagine_message_id' => null,
142 | 'upscaled_photo_url' => null
143 | ];
144 | }
145 |
146 | $this->countProcess++;
147 |
148 | // Random image selection if $upscale_index is null
149 | if (is_null($upscale_index)) $upscale_index = rand(0, 3);
150 |
151 | // Unique ID to find the image once created
152 | $this->uniqueId = time() - rand(0, 1000);
153 | $prompt = $prompt . ' --seed ' . $this->uniqueId;
154 |
155 | $imagine = $this->getImagine($prompt);
156 | $upscaled_photo_url = $this->getUpscale($imagine, $upscale_index);
157 |
158 | $this->countProcess--;
159 |
160 | return (object) [
161 | 'imagine_message_id' => $imagine['id'],
162 | 'upscaled_photo_url' => $upscaled_photo_url
163 | ];
164 | }
165 |
166 |
167 | /**
168 | * Method to check the number of processes and wait if necessary
169 | * @return boolean
170 | */
171 | private function checkCountProcess()
172 | {
173 | $maxLoop = 30;
174 | $nbLoop = 0;
175 |
176 | while ($this->countProcess == $this->limitProcess) {
177 | if ($nbLoop == $maxLoop) return false;
178 | sleep(30);
179 | $nbLoop++;
180 | }
181 |
182 | return true;
183 | }
184 |
185 |
186 | /**
187 | * Call /imagine
188 | *
189 | * @param string $prompt Prompt midjourney
190 | * @return void
191 | */
192 | private function getImagine(string $prompt)
193 | {
194 | $params = [
195 | 'type' => 2,
196 | 'application_id' => $this->applicationId,
197 | 'guild_id' => $this->guildId,
198 | 'channel_id' => $this->channelId,
199 | 'session_id' => $this->sessionId,
200 | 'data' => [
201 | 'id' => $this->dataId,
202 | 'version' => $this->dataVersion,
203 | 'name' => 'imagine',
204 | 'type' => 1,
205 | 'options' => [
206 | [
207 | 'type' => 3,
208 | 'name' => 'prompt',
209 | 'value' => $prompt
210 | ],
211 | ],
212 | ],
213 | ];
214 |
215 | if (is_null($this->guildId)) {
216 | unset($params['guild_id']);
217 | }
218 |
219 | $this->client->post('interactions', [
220 | 'json' => $params
221 | ]);
222 |
223 | sleep(8);
224 |
225 | $imagine_message = null;
226 |
227 | // Max time loop: 8 minutes of waiting
228 | $maxLoop = 60;
229 |
230 | while (is_null($imagine_message)) {
231 | $maxLoop--;
232 | if ($maxLoop == 0) break;
233 |
234 | $imagine_message = $this->checkImagine();
235 | if (is_null($imagine_message)) sleep(8);
236 | }
237 |
238 | return $imagine_message;
239 | }
240 |
241 |
242 | /**
243 | * Method to retrieve the Midjourney message and identify when the 4 visuals are ready
244 | *
245 | * @return void
246 | */
247 | private function checkImagine()
248 | {
249 | $response = $this->client->get('channels/' . $this->channelId . '/messages');
250 | $response = $response->getBody()->getContents();
251 | $items = json_decode($response, true);
252 |
253 | $raw_message = null;
254 |
255 | foreach ($items as $item) {
256 | if (
257 | str_contains($item['content'], $this->uniqueId) &&
258 | str_contains($item['content'], '<@' . $this->userId . '> (fast)')
259 | ) {
260 | $raw_message = $item;
261 | break;
262 | }
263 |
264 | if (is_null($raw_message)) {
265 | if (
266 | str_contains($item['content'], $this->uniqueId) &&
267 | str_contains($item['content'], '<@' . $this->userId . '> (Open on website for full quality) (fast)')
268 | ) {
269 | $raw_message = $item;
270 | break;
271 | }
272 | }
273 | }
274 |
275 | if (is_null($raw_message)) return null;
276 |
277 | return [
278 | 'id' => $raw_message['id'],
279 | 'raw_message' => $raw_message
280 | ];
281 | }
282 |
283 |
284 | /**
285 | * Method to upscale an image of Midjourney among the 4 proposed
286 | *
287 | * @param array $message Array returned by the getImagine method
288 | * @param integer $upscale_index Choice of image to upscale (0.3)
289 | * @return void
290 | */
291 | private function getUpscale($message, int $upscale_index)
292 | {
293 | if (!isset($message['raw_message'])) {
294 | error_log('Upscale requires a message object obtained from the imagine/getImagine methods.');
295 | }
296 |
297 | if ($upscale_index < 0 or $upscale_index > 3) {
298 | error_log('Upscale index must be between 0 and 3.');
299 | }
300 |
301 | $upscale_hash = null;
302 | $raw_message = $message['raw_message'];
303 |
304 | if (isset($raw_message['components']) && is_array($raw_message['components'])) {
305 | $upscales = $raw_message['components'][0]['components'];
306 | $upscale_hash = $upscales[$upscale_index]['custom_id'];
307 | }
308 |
309 | $params = [
310 | 'type' => 3,
311 | 'guild_id' => $this->guildId,
312 | 'channel_id' => $this->channelId,
313 | 'message_flags' => 0,
314 | 'message_id' => $message['id'],
315 | 'application_id' => $this->applicationId,
316 | 'session_id' => $this->sessionId,
317 | 'data' => [
318 | 'component_type' => 2,
319 | 'custom_id' => $upscale_hash
320 | ]
321 | ];
322 |
323 | if (is_null($this->guildId)) {
324 | unset($params['guild_id']);
325 | }
326 |
327 | $this->client->post('interactions', [
328 | 'json' => $params
329 | ]);
330 |
331 | $upscaled_photo_url = null;
332 |
333 | // Max time loop: 6 minutes
334 | $maxLoop = 120;
335 |
336 | while (is_null($upscaled_photo_url)) {
337 | $maxLoop--;
338 | if ($maxLoop == 0) break;
339 |
340 | $upscaled_photo_url = $this->checkUpscale($message, $upscale_index);
341 | if (is_null($upscaled_photo_url)) sleep(3);
342 | }
343 |
344 | return $upscaled_photo_url;
345 | }
346 |
347 |
348 | /**
349 | * Method to check if the upscaled image is ready
350 | *
351 | * @param array $message Array returned by the getImagine method
352 | * @param integer $upscale_index Choice of image to upscale (0.3)
353 | * @return void
354 | */
355 | private function checkUpscale($message, $upscale_index = 0)
356 | {
357 | if (!isset($message['raw_message'])) {
358 | error_log('Upscale requires a message object obtained from the imagine/getImagine methods.');
359 | }
360 |
361 | if ($upscale_index < 0 || $upscale_index > 3) {
362 | error_log('Upscale index must be between 0 and 3.');
363 | }
364 |
365 | $response = $this->client->get('channels/' . $this->channelId . '/messages');
366 | $response = $response->getBody()->getContents();
367 | $items = json_decode($response, true);
368 |
369 | $message_index = $upscale_index + 1;
370 | $message = null;
371 |
372 | foreach ($items as $item) {
373 | if (
374 | str_contains($item['content'], $this->uniqueId) &&
375 | str_contains($item['content'], "Image #{$message_index} <@{$this->userId}>")
376 | ) {
377 | $message = $item;
378 | break;
379 | }
380 |
381 | if (is_null($message)) {
382 | if (
383 | str_contains($item['content'], $this->uniqueId) &&
384 | str_contains($item['content'], "Upscaled by <@{$this->userId}> (fast)")
385 | ) {
386 | $message = $item;
387 | break;
388 | }
389 | }
390 | }
391 |
392 | return (!is_null($message) && isset($message['attachments'])) ? $message['attachments'][0]['url'] : null;
393 | }
394 | }
395 |
--------------------------------------------------------------------------------