使用PHP获取 Mastodon API数据
Gotosocial 如何获得Access Tokens本文介绍了如何通过Gotosocial API获得Access Tokens。首先需要使用API创建一个应用,得到"client_id"和"client_secret"。然后授权应用,访问指定的URL并点击通过,得到一个token。最后,使用获得的token和之前得到的"client_id"和"client_secret",发送请求获得access token。
根据 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
×
如果觉得文章对你有帮助,可以请作者喝杯咖啡 ☕️


复制链接https://www.imsun.org/archives/1664.html
复制成功!
肖寒武
我还没用过mastodon,只记得去年有段时间各大博友都在推这个。
老孙
web3.0时代 去中心化很重要
acevs
我用n8n 获取过Mastodon API 就是为了同步wp的文章。
先mark~
老孙
Wordpress 也有说说的功能吧 也可以使用Wordpress RestAPI 同步
acevs
有的 不过服务器得翻墙才行。翻墙我发现同步消息也是有点问题的,就把插件卸载掉了。
老孙
不用插件啊直接用AI写个同步的脚本就好了 , 如果有可能 用 github action来同步也不是不行