search the accounts you follow
full-text search over posts from the accounts one user follows, grouped by author.
//! search posts from the accounts you follow, grouped by author.
//!
//! set ATPROTO_HANDLE and ATPROTO_PASSWORD (an app password), and
//! ATPROTO_SEARCH_QUERY for the topic. the account's PDS is resolved from
//! the handle, not configured.
//!
//! run: zig build example-search-your-follows
const std = @import("std");
const zat = @import("zat");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const allocator = init.gpa;
const query = init.environ_map.get("ATPROTO_SEARCH_QUERY") orelse "zig";
const handle = init.environ_map.get("ATPROTO_HANDLE") orelse return error.MissingHandle;
const app_password = init.environ_map.get("ATPROTO_PASSWORD") orelse return error.MissingPassword;
// the handle names the account; its DID document says where the account
// lives today. resolving instead of assuming is what lets accounts move.
var handle_resolver = zat.HandleResolver.init(io, allocator);
defer handle_resolver.deinit();
const did = try handle_resolver.resolve(zat.Handle.parse(handle) orelse return error.InvalidHandle);
defer allocator.free(did);
var did_resolver = zat.DidResolver.init(io, allocator);
defer did_resolver.deinit();
var doc = try did_resolver.resolve(zat.Did.parse(did).?);
defer doc.deinit();
const pds = doc.pdsEndpoint() orelse return error.NoPdsEndpoint;
var client = zat.XrpcClient.init(io, allocator, pds);
defer client.deinit();
const access_jwt = try createSession(&client, allocator, handle, app_password);
defer allocator.free(access_jwt);
client.setAuth(access_jwt);
std.debug.print("{s} via {s}\nquery: {s}\n\n", .{ handle, pds, query });
try searchFollows(&client, allocator, query);
}
fn createSession(
client: *zat.XrpcClient,
allocator: std.mem.Allocator,
identifier: []const u8,
app_password: []const u8,
) ![]u8 {
const body = try std.json.Stringify.valueAlloc(allocator, .{
.identifier = identifier,
.password = app_password,
}, .{});
defer allocator.free(body);
const method = zat.Nsid.parse("com.atproto.server.createSession").?;
var response = try client.procedure(method, body);
defer response.deinit();
if (!response.ok()) {
std.debug.print("createSession failed ({d}): {s}\n", .{ @backingInt(response.status), response.body });
return error.AuthenticationFailed;
}
var parsed = try response.json();
defer parsed.deinit();
const token = zat.json.getString(parsed.value, "accessJwt") orelse return error.MissingAccessToken;
return try allocator.dupe(u8, token);
}
fn searchFollows(client: *zat.XrpcClient, allocator: std.mem.Allocator, query: []const u8) !void {
// `following=true` is viewer-relative, so the request has to go through
// the account's own PDS to reach the AppView as this user.
const method = zat.Nsid.parse("app.bsky.feed.searchPostsV2").?;
var response = try client.queryParams(method, &.{
.{ .name = "query", .value = query },
.{ .name = "sort", .value = "recent" },
.{ .name = "allTime", .value = "true" },
.{ .name = "following", .value = "true" },
.{ .name = "limit", .value = "100" },
});
defer response.deinit();
if (!response.ok()) {
std.debug.print("searchPostsV2 failed ({d}): {s}\n", .{ @backingInt(response.status), response.body });
return error.SearchFailed;
}
var parsed = try response.json();
defer parsed.deinit();
const posts = zat.json.getArray(parsed.value, "posts") orelse return error.MissingPosts;
var counts = std.StringHashMap(usize).init(allocator);
defer counts.deinit();
var leader: ?[]const u8 = null;
var leader_count: usize = 0;
for (posts) |post| {
const author = zat.json.getString(post, "author.handle") orelse continue;
const entry = try counts.getOrPut(author);
if (!entry.found_existing) entry.value_ptr.* = 0;
entry.value_ptr.* += 1;
if (entry.value_ptr.* > leader_count) {
leader = author;
leader_count = entry.value_ptr.*;
}
}
std.debug.print("matches from accounts you follow: {d}\n", .{posts.len});
const winner = leader orelse return;
std.debug.print("most posts: @{s} ({d})\n\n", .{ winner, leader_count });
for (posts) |post| {
const author = zat.json.getString(post, "author.handle") orelse continue;
if (!std.mem.eql(u8, author, winner)) continue;
const text = zat.json.getString(post, "record.text") orelse "";
const uri = zat.json.getString(post, "uri") orelse "";
std.debug.print("- {s}\n {s}\n", .{ text, uri });
}
}
zzstoatzz.io via https://pds.zzstoatzz.io
query: zig
matches from accounts you follow: 98
most posts: @garrison.corporate.fm (13)
- some of the stuff the zig people say really activates my unix hater neuron, but I have to admit the language is crazy readable
I read and understood like half the @tigerbeetle.com codebase without consulting the zig docs once
at://did:plc:lmidtahyizyejqz74zeaip67/app.bsky.feed.post/3msqahntnkc2l
- instructions unclear, rustc rewritten in zig
at://did:plc:lmidtahyizyejqz74zeaip67/app.bsky.feed.post/3mraispyots24
...
The JSON getters borrow from parsed.value, which stays alive through both loops.
Each orelse is a per-field decision: a missing or wrong-type author skips the
post, while missing or wrong-type text and URI become empty strings. Dotted paths
work with string literals; typed decoding is only needed when you want a struct.
examples/06_search_your_follows.zig verbatim. set ATPROTO_HANDLE,
ATPROTO_PASSWORD (an app password), and ATPROTO_SEARCH_QUERY, then
zig build example-search-your-follows. output trimmed to two of thirteen posts.
following=true makes the search viewer-relative, so the request goes through
the account's PDS to the AppView as that user. allTime=true reaches past the
recent-post window; sort=recent orders newest first.
see also: the searchPostsV2 lexicon.
wiring zat into your own <code>build.zig</code>
const zat = b.dependency("zat", .{}).module("zat");
exe.root_module.addImport("zat", zat);
after zig fetch --save https://tangled.org/zat.dev/zat/archive/main.