Lens Post Automation: A Technical Deep Dive into the Gelato Web3 & OpenAI Integration

Gelato Team

May 26, 2023

Experience the effortless blend of Gelato Network's Web3 Functions and OpenAI. This new function revolutionizes content creation and automates post scheduling on Lens. The first 1000 posts will trial the new app free of charge!

Users simply input creative prompts, which OpenAI transforms into engaging content. Thanks to Gelato's Web3 Functions, these posts are automatically scheduled and published on Lens three times a day — visible to everyone on Lenster.

How it works?

TL;DR

Gelato's Web3 Functions pull your stored prompts from the LensGelatoGPT contract and schedule them to post every 8 hours. OpenAI generates creative text, which is validated by Lens Protocol, stored on IPFS, and finally published via the LensHub contract.

The LensGelatoGPT Contract

The LensGelatoGPT contract manages user-generated prompts tied to Lens profiles. Only profile owners can add or remove prompts, ensuring secure and organized management. The function getPaginatedPrompts retrieves batches of prompts for OpenAI to process.

contract LensGelatoGPT {
    mapping(uint => string) public prompts;
    ...
    function getPaginatedPrompts(uint start, uint end) public view returns (string[] memory) {
        ...
    }
}

Utilizing Gelato’s Web3 Functions

Gelato Web3 Functions automate fetching prompts and scheduling posts. Triggered every 8 hours, they check time elapsed since the last post and then fetch the next prompt.

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

Prompts are transformed into content by OpenAI’s API:

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;

Lens Protocol Validation

const pub = {
  content: text,
  ...
};

const lensClient = new LensClient({ environment: production });

// Validate metadata
const validateResult = await lensClient.publication.validateMetadata(pub);

Storing on IPFS

Generated text is packaged in JSON and uploaded to IPFS via Web3.Storage:

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 content URI is passed to the LensHub contract, which creates and publishes the post:

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

If you're a developer, dive in! Or for a simpler user experience, click here.

1. Create a Profile

Secure your Lens handle on Lenster and copy your ProfileID. Note: If your address isn’t whitelisted, you cannot secure a handle.

2. Set the Dispatcher

On the LensHub contract, call setDispatcher(ProfileId,0xcc53666e25bf52c7c5bc1e8f6e1f6bf58e871659) to allow Gelato Web3 Functions to post.

3. Set the Prompt

On the LensGelatoGPT contract, use setPrompt with your ProfileID and a creative idea (10–160 characters).

setPrompt(PayableAmount, ProfileId, "YOUR PROMPT")

4. Congratulations!

Your Lenster profile will now auto-post 3 times per day with creative content based on your prompt!

Set up your dev environment

  1. Clone repo: git clone https://github.com/gelatodigital/eth-dam-gelato-lens-ai.git

  2. Install packages: npm install

  3. Configure secrets in .env for:

    • Provider URL

    • OpenAI Key

    • Web3.Storage Key

About Gelato Web3 Functions

Web3 Functions empower developers to create serverless, decentralized apps that connect on-chain contracts with off-chain data. They provide a robust, scalable infrastructure for automation.

Get started

👉 Join the community on Discord

👉 Try Web3 Functions in private beta

👉 Learn more in the documentation and use the Hardhat template

👉 Apply here to test Web3 Functions!

Disclaimer

Gelato LensGPT Beta 1.0 is in testing and provided “as is.” Availability may change, and the Gelato community will sponsor the first 1000 posts.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.

Ready to build?

Start with a testnet, launch your mainnet in days, and scale with industry-leading UX.