575 days ago
Lens Post Automation: A Technical Deep Dive into the Gelato Web3 & OpenAI Integration
Experience the effortless blend of Gelato Network's Web3 Functions and OpenAI. This new function is revolutionizing content creation and automating posts scheduling on Lens. Here's the kicker - the first 1000 posts will trial the new app free of charge!
This integration allows users to input creative prompts, which OpenAI then turns into creative content. Thanks to Gelato's Web3 Functions, these posts are then automatically scheduled and published on Lens three times a day, for everyone to see on Lenster, the social media web app built with Lens Protocol.
The result? A user-friendly platform that handles content creation and posts like clockwork.
How it works?
TL;DR
Gelato's Web3 Functions work tirelessly, pulling your stored prompts from the LensGelatoGPT contract and scheduling them to post on Lens every 8 hours. All you have to do is input your creative ideas, and the Gelato Web3 Functions takes care of the rest.
This process includes using OpenAI to turn your prompts into interesting posts. These posts are then checked using the Lens Protocol to make sure they're up to standard. After that, the posts are safely stored on IPFS and finally published on Lens using the LensHub contract. With this simple and efficient system, your prompts become engaging posts that are automatically scheduled and visible on Lenster.
Let’s see how this works under the hood:
The LensGelatoGPT Contract
LensGelatoGPT contract forms the crux of our platform, ensuring secure, organized, and effective management of user-generated messages or prompts. It allows users to associate unique messages or "prompts" with their profiles, subject to a fee. Only the profile owners can add or remove their prompts.
The contract also maintains a special relationship with LensHub, keeping track of user profiles and ensuring only the correct user can operate their profiles.
One of its important functions is 'getPaginatedPrompts'. This function systematically retrieves prompts in batches, providing a consistent stream of user-defined prompts. These prompts are used by OpenAI as a basis for creating engaging content.
contract LensGelatoGPT {
mapping(uint => string) public prompts;
...
function getPaginatedPrompts(uint start, uint end) public view returns (string[] memory) {
...
}
}
Utilizing Gelato’s Web3 Functions
Once the prompts are securely stored in the smart contract, Gelato’s Web3 Functions step in to automate the process of retrieving these prompts and scheduling the posts. Set to trigger at predefined intervals (in this case every 8 hours), these functions first verify if the time elapsed since the last post is greater than the set interval before they fetch the next prompt from the LensGelatoGPT contract.
const timeElapsed = blockTime - lastPostTime >= INTERVAL_IN_MIN * 60;
if (!timeElapsed && nextPromptIndex == 0 && !areThereNewProfileIds) {
return {
canExec: false,
message: "Not time elapsed since last post and not newcomers",
};
}
OpenAI API
The fetched prompt is then processed by OpenAI's API, which then serves as the genesis for a unique piece of content. OpenAI takes the simple prompt and transforms it into a creative snippet of text.
const openai = new OpenAIApi(new Configuration({ apiKey:SECRETS_OPEN_AI_API_KEY }));
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: ` ${contentURI} in less than 15 words.`,
temperature: 1,
max_tokens: 256,
top_p: 1,
frequency_penalty: 1.5,
presence_penalty: 1,
});
let text = response.data.choices[0].text as string;
Upon generation, Lens Protocol is employed to validate the publication metadata and ensure it is in alignment with Lens standards.
const pub = {
…
content: text,
...
};
// Checking the metadata is Correct
const lensClient = new LensClient({
environment: production,
});
// Validating publication metadata using LensClient
const validateResult = await lensClient.publication.validateMetadata(pub);
Storing on IPFS
The generated text is securely stored on IPFS, with the post's metadata conveniently packaged in a JSON file. Utilizing the Web3 storage client, this metadata file is effortlessly uploaded to IPFS. The resulting CID acts as the content URI for the post, granting a direct and reliable link to access the metadata stored on IPFS.
// Upload metadata to IPFS
const storage = new Web3Storage({ token: WEB3_STORAGE_API_KEY! });
const myFile = new File([JSON.stringify(pub)], "publication.json");
const cid = await storage.put([myFile]);
contentURI = `https://${cid}.ipfs.w3s.link/publication.json`;
LensHub contract
The final stage of this process involves packaging the CID along with other post data and forwarding it to the LensHub contract, which validates the data, formulates a new post, and lines it up for publication on Lenster.
const postData = {
profileId: profileID
contentURI: `https://${cid}.ipfs.w3s.link/publication.json`,
…
};
const lensHubAddress = "0xDb46d1Dc155634FbC732f92E853b10B288AD5a1d";
const iface = new utils.Interface(lens_hub_abi);
return {
canExec: true,
callData: [
{
to: lensHubAddress,
data: iface.encodeFunctionData("post", [postData]),
},
],
};
Get started with LensGPT
Eager to experience this revolutionary fusion first-hand? If you're a developer, dive right in! FIf you're aiming for a simpler user experience click here.
1. Create a Profile
Before you dive in, ensure you've secured your Lens handle, then head over to the Lenster app and log in then connect to your wallet either through your browser or with WalletConnect.
After successfully creating your profile, copy your ProfileID, as you’ll need it for what’s coming next!
NOTE: if your address hasn’t been whitelisted, you will be unable to secure a Lens handle.
2. Set the Dispatcher
Next, head to the LensHub contract. Click on 'Write as a Proxy' and then select the 'setDispatcher' method.
You now need two things: your ProfileID and a dispatcher address. Use the ProfileID from Step 1.
For the dispatcher address, paste in this: 0xcc53666e25bf52c7c5bc1e8f6e1f6bf58e871659. This step allows Gelato’s Web3 Functions post on your Lenster account
setDispatcher(ProfileId,0xcc53666e25bf52c7c5bc1e8f6e1f6bf58e871659).
3. Set the Prompt
IMPORTANT: Ensure you have at least 5 MATIC in your account to set up the prompt!
Next, visit the LensGelatoGPT contract. Click on 'Write as a Proxy' and pick the 'setPrompt' method. It's time to fill in some details.
For 'PAYABLE AMOUNT', enter '0'. For 'ProfileID', use the one you copied from step 1. For 'YOUR PROMPT', put in a creative idea of yours.
setPrompt(PayableAmount,ProfileId,"YOUR PROMPT")
Make sure the prompt follows the character limits (10 - 160 characters). If you need some inspo, we’ve got you covered:
- I’m about to start my web3 journey, what advice do you have for me?
- How can I maintain a healthy work-life balance? Give me practical tips.
- Give me a simple exercise routine to help me stay healthy and move during my work breaks
- Which productivity tool or app would make a significant difference in my daily routine?
And that's all! Now, sit back and watch as the creative content starts flowing.
4. Congratulations!
If you take a look at your Lenster profile, you’ll see a new post that was generated from your prompt! The best part? 3 times per day, a new post will be created that will keep your Lenster account active.
Set up your dev environment
Once you've prepared your profile on Lenster, it's time to configure the necessary secrets and settings for your development environment. Follow these instructions to set everything up properly:
Step 1: Clone the Repository
Open the terminal and write,
git clone https://github.com/gelatodigital/eth-dam-gelato-lens-ai.git
Step 2: Install packages
Next, install the necessary packages:
npm install
Step 3: Configure Secrets
We need to provide three types of keys for our application:
- A Provider URL
- An OpenAI Key
- A Web3.Storage Key
Provider URLs: Locate the .env.template file in your root folder, copy it and rename the copy to .env. Now open this .env file and input your Provider URLs like so:
PROVIDER_URLS= YOUR_RPC
Replace YOUR_RPC with your actual Provider URLs.
OpenAI and Web3.Storage Keys: Find the .env.template file in the web3-functions/lens-ai directory. Again, make a copy of it and rename the copy to .env.
Open this .env file and input your OpenAI API key and Web3.Storage API key as shown below:
OPEN_AI_API_KEY=YOUR_KEY
WEB3_STORAGE_API_KEY=YOUR_KEY
Replace YOUR_KEY with your actual OpenAI and Web3.Storage keys respectively. In case you don't have a Web3.Storage key, you can obtain one by visiting Web3.Storage and signing up for their service.
Well done on setting up your development environment! With this configuration, you're now equipped to delve into the world of automatic content creation and scheduling post on Lens, powered by Gelato's Web3 functions and OpenAI.
About Gelato Web3 Functions
Web3 Functions provide an innovative solution for developers to create serverless, decentralized applications with ease. They enable seamless integration of smart contracts with off-chain data, bridging the gap between on-chain and off-chain worlds.
By leveraging Web3 Functions, developers can build robust, scalable, and decentralized web3 applications, supported by a reliable and resilient infrastructure.
Get started
Join our community and developer discussion on Discord.
Web3 Functions are available today in private beta. For more information, please check out the Web3 Functions documentation. To learn how to write, test, and deploy your own Web3 Functions, use this Hardhat template
Apply here to be one of the first to test Web3 Functions!
Disclaimer
Gelato LensGPT Beta 1.0 is still in the testing phase and is provided "as is" and "as available" basis. The Gelato LensGPT Beta 1.0 app may not be available indefinitely and we reserve the right to discontinue it in the future. The Gelato community will sponsor the first 1000 posts.