文章页顶部广告

使用PHP获取 Mastodon API数据

60 次浏览
6 评论

共计1551个字符,预计需要花费 2分钟才能阅读完成。

AI摘要:文章介绍了如何使用PHP从Mastodon API获取数据并保存为本地JSON文件。通过设置用户ID和实例地址,使用cURL请求API,循环获取最多1000条非转发的状态数据,并将其保存为toot.json文件。该方法解决了Cloudflare Workers获取API数据较慢的问题,并通过计划任务定时更新数据。

[article id="1643"]

根据 Cloudflare Workers 获取API 拉取的时候有些慢,所以使用php 获取到json 数据并保存在本地,通过计划任务定时生成.

<?php
$userId = '110711427149362311'; //改为自己的
$instance = 'jiong.us'; //改为自己的
$baseUrl = 'https://' . $instance . '/api/v1/accounts/' . $userId . '/statuses';
$limit = 20; // Maximum limit per page
$toots = [];

for ($i = 0; $i < 25; $i++) { // 25 pages * 40 toots per page = 1000 toots
    $ch = curl_init();
    $url = $baseUrl . '?limit=' . $limit;

    if (isset($lastId)) {
        $url .= '&max_id=' . $lastId;
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($ch, CURLOPT_HTTPHEADER, [
    //    'Authorization: Bearer ' . $accessToken
    //]);

    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);

    if (empty($data)) {
        break;
    }

    foreach ($data as $toot) {
        if (!isset($toot['reblog']) && !isset($toot['in_reply_to_id'])) {
            $toots[] = $toot;
        }
    }

    $lastId = end($data)['id'];
}

// Now $toots contains up to 1000 toots
$jsonData = json_encode($toots, JSON_PRETTY_PRINT);
file_put_contents('toot.json', $jsonData);
?>

保存为toot.php, 访问 toot.php 则会在同级目录生成 toot.json.

创建一个定时任务定时访问toot.php

正文完
 0
评论(6 条评论)
  1. 肖寒武 「博友」
    2024-12-13 17:31:31 回复

    我还没用过mastodon,只记得去年有段时间各大博友都在推这个。

      Windows   Edge  中国浙江省杭州市联通
    1. 老孙 博主
      2024-12-13 18:12:38 回复
      @肖寒武

      web3.0时代 去中心化很重要

        Windows   Chrome  印度马哈拉施特拉孟买Syscon
  2. acevs 熟识 LV.4
    2024-12-13 16:46:36 回复

    我用n8n 获取过Mastodon API 就是为了同步wp的文章。
    先mark~

      Windows   Chrome  美国北卡罗来纳夏洛特
    1. 老孙 博主
      2024-12-13 16:50:18 回复
      @acevs

      Wordpress 也有说说的功能吧 也可以使用Wordpress RestAPI 同步

        Windows   Chrome  印度马哈拉施特拉孟买Syscon
      1. acevs 熟识 LV.4
        2024-12-13 18:09:32 回复
        @老孙

        有的 不过服务器得翻墙才行。翻墙我发现同步消息也是有点问题的,就把插件卸载掉了。

          Windows   Chrome  美国伊利诺伊芝加哥科进
        1. 老孙 博主
          2024-12-13 18:11:12 回复
          @acevs

          不用插件啊直接用AI写个同步的脚本就好了 , 如果有可能 用 github action来同步也不是不行

            Windows   Chrome  印度马哈拉施特拉孟买Syscon
联系我们

版权说明

版权所有 转载请注明出处

SiteMap| RSS|

© 2025 老孙博客
 Theme by Puock  Powered by Typecho

老孙博客制作