News Feed on ao usingĀ 0rbit

gm gm Buildooors!! šŸš€

In this blog, we'll explore how to use 0rbit to create a news feed bot. But before that picture this: ā€œeasily accessing data from both on-chain and off-chain sourcesā€. This is where 0rbit comes in handy.

Before we dive in, let's get a grasp of what 0rbit is all about. Simply put, 0rbit is a decentralized, permissionless, and censorship-resistant oracle network. It's built on top of Arweave using ao. Its main goal is to make accessing and using blockchain data easier and more efficient for everyone.

Now let's kick things off by following these steps:

šŸ”‘ Pre-Requisites:

  • Understanding of theĀ aoĀ andĀ aos.

  • aos installed on your system.

  • Some $0RBT.Ā Learn how to get $0RBTĀ here

  • Any Code Editor (VSCode, Sublime Text, etc)

Checkpoint 0:šŸ“¦ Initialize the Project

Create a new file namedĀ 0rbit-News-Feed.luaĀ in your project directory.

touch 0rbit-News-Feed.lua

Checkpoint 1: šŸ“ Initialize the Variables

local json = require("json")
 
_0RBIT = "BaMK1dfayo75s3q1ow6AO64UDpD9SEFbeE8xYrY2fyQ"
_0RBT_TOKEN = "BUhZLMwQ6yZHguLtJYA5lLUa9LQzLXMXRfaq9FVcPJc"
 
URL = "https://saurav.tech/NewsAPI/top-headlines/category/health/in.json"
FEE_AMOUNT = "1000000000000" -- 1 $0RBT
NEWS = NEWS or {}

Breakdown of the above code:

  • json: The module required to destruct the stringified JSON data.

  • _0RBIT: The processId of the 0rbit process.

  • _0RBT_TOKEN: The processId of the $0RBT process.

  • URL: The API URL you want to fetch data from.

  • FEE_AMOUNT: The amount of $0RBT you want to send to the 0rbit process for the request.

  • NEWS: The table to store the news data.

For more detailed information on how to use the JSON module, you can visit the documentationĀ here.

Checkpoint 2: šŸ›  Create Functions

Fetch News Function

TheĀ fetchNewsĀ function fetches the news from theĀ URLĀ using 0rbit'sĀ Get-Real-DataĀ handler.

function fetchNews()
    Send({
        Target = _0RBT_TOKEN,
        Action = "Transfer",
        Recipient = _0RBIT,
        Quantity = FEE_AMOUNT,
        ["X-Url"] = URL,
        ["X-Action"] = "Get-Real-Data"
    })
    print(Colors.green .. "GET Request sent to the 0rbit process.")
end

Breakdown of the above code:

  • Send: Transfer 1 $0RBT to the 0rbit process and make a GET request. With this, we initiate a transfer of 1 $0RBT to the 0rbit process and execute a GET request.

    • Target: This denotes the process to be pinged with the following Action, specifically the 0rbit Token Process.

    • Action: This signifies the task to be carried out, in this case, the transfer of 1 0rbit token from the current process to the 0rbit process ID.

    • Recipient: This indicates the receiver of the transfer, which, in this context, is the 0rbit oracle's process.

    • Quantity: This denotes the amount intended for transfer.

    Additionally:

    • The ["X-Url"] tag specifies the URL from which the data is to be fetched.

    • The ["X-Action"] tag specifies the action to be performed.

    The "X-" prefix in these tags is a convention used to denote forwarded tags. Forwarded tags refer to additional information or metadata included in a message that is passed along to subsequent messages or handlers.

Receive Data Function

TheĀ receiveDataĀ function is called when the 0rbit process sends the fetched data to the process.

function receiveData(msg)
    local res = json.decode(msg.Data);
    local articles;
    local article;
    if res.status == "ok" then
        articles = res.articles;
        for k, v in pairs(articles) do
            article =
            {
                title = v.title,
                description = v.description,
                url = v.url
            }
            table.insert(NEWS, article)
        end
        print("News Updated")
    else
        print("Error in fetching news")
    end
end

Breakdown of the above code:

  • res: Parse the JSON data received from the 0rbit process.

  • articles: To store the articles array.

  • article: To store the article object.

  • if res.status == "ok": Check if the status is ok.

    if true:

    • for k, v in pairs(articles): Iterate over the articles array.

    • article: Create an article object with a title, description, and URL.

    • table.insert(NEWS, article): Insert the article object into the NEWS table.

    • Print "News Updated".

    if false:

    • Print an error message.

Get News Function

TheĀ getNewsĀ function returns the news data from theĀ NEWSĀ table.

function getNews(msg)    
  local news = json.encode(NEWS)    
  Handlers.utils.reply(news)(msg)
end

Breakdown of the above code:

  • news: Stringify the NEWS table.

  • Handlers.utils.reply(news): Send the news data to the sender.

Checkpoint 3: šŸ§­ Create Handlers

Get News Handler

TheĀ GetNewsĀ handler is called when a process wants the latest news.

Handlers.add(
    "GetNews",
    Handlers.utils.hasMatchingTag("Action", "Get-News"),
    getNews
)

Breakdown of the above code:

  • GetNews: The name of the handler.

  • Handlers.utils.hasMatchingTag("Action", "Get-News"): Checks if the message action tag isĀ Get-News.

  • getNews: The function that sends the latest news from theĀ NEWSĀ table.

Cron Handler

TheĀ FetchNewsĀ handler fetches the news using 0rbit.

Handlers.add(
    "FetchNews",
    Handlers.utils.hasMatchingTag("Action", "Fetch-News"),
    fetchNews
)

Breakdown of the above code:

  • FetchNews: The name of the handler.

  • Handlers.utils.hasMatchingTag("Action", "Fetch-News"): Checks if the message action tag isĀ Cron

  • fetchNews: The function that sends a GET Request to 0rbit process to fetch the latest news.

Receive Data Handler

TheĀ ReceiveDataĀ handler is called when the 0rbit process sends the fetched data to the process.

Handlers.add(    
  "ReceiveData",    
  Handlers.utils.hasMatchingTag("Action", "Receive-Response"),   
  receiveData
)

Breakdown of the above code:

  • ReceivingData: The name of the handler.

  • Handlers.utils.hasMatchingTag("Action", "Receive-Response"): Checks if the message action tag isĀ Receive-Response

  • receiveData: The function that updates the latest news in theĀ NEWSĀ table.

Checkpoint 4: šŸ”„ Run the Process

Open your Terminal

Open your terminal in the directory that containsĀ 0rbit-News-Feed.luaĀ and enter the following command:

aos 0rbitNewsFeed --cron 30-seconds

The above command will create a new process with the nameĀ 0rbitNewsFeedĀ and set a cron job every 30 seconds.

Load your process

Load your script into the process:

aos> .load 0rbit-News-Feed.lua

Fund your process

Transfer some $0RBT to your processID.

Check the News Feed

aos> Send({ Target = ao.id, Action="Get-News"})

As we wrap up, I hope you've picked up something new today. šŸ¦¾


Check out the contract here:

Next up, we'll tackle building the frontend for the News-Feed Bot in our upcoming blog. šŸ˜‰

In the meantime,

if you've got any questions, don't hesitate to shoot us a DM on TwitterĀ orĀ hop into our Discord communityĀ to learn more about 0rbitšŸ’«.

Happy Building!! šŸ§±šŸ’«šŸš€

Subscribe to 0rbit
Receive the latest updates directly to yourĀ inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.