Bluesky bot in .NET
Fri, Apr 28, 2023
2-minute read
Let’s create a bot in .NET
First the code!
using System.Text.Json;
using Bluesky.Net;
using Bluesky.Net.Commands.AtProto.Server;
using Bluesky.Net.Commands.Bsky.Feed;
using Bluesky.Net.Models;
using Bluesky.Net.Multiples;
using Microsoft.Extensions.DependencyInjection;
IServiceCollection services = new ServiceCollection();
services.AddBluesky();
await using var serviceProvider = services.BuildServiceProvider();
var api = serviceProvider.GetRequiredService<IBlueskyApi>();
string userName = Environment.GetEnvironmentVariable("BLUESKY_USERNAME")!;
string password = Environment.GetEnvironmentVariable("BLUESKY_PASSWORD")!;
Login command = new(userName, password);
Multiple<Session, Error> result = await api.Login(command, CancellationToken.None);
if (result.IsT1)
{
Console.WriteLine($"Error logging to Bluesky {JsonSerializer.Serialize(result.AsT1)}");
return;
}
Quote[]? quotes = JsonSerializer.Deserialize<Quote[]>(File.ReadAllText(@"quotes.json"))!;
foreach (Quote quote in quotes)
{
CreatePost post = new CreatePost($"{quote.Text}\n -{quote.Author}".Substring(0, 255));
await api.CreatePost(post, CancellationToken.None);
await Task.Delay(TimeSpan.FromDays(1), CancellationToken.None);
}
Now step by step!
Bootstraping
Create a Console App and install the Bluesky.Net Nuget package
dotnet new console --framework net7.0
dotnet add package Bluesky.Net --version 0.3.0-alpha
Configure the library
Bluesky.Net is integrated with DI by default, and is the only way to access it. So you will need to have a ServiceProvider
IServiceCollection services = new ServiceCollection();
services.AddBluesky();
await using var serviceProvider = services.BuildServiceProvider();
//Now we can resolve our api
var api = serviceProvider.GetRequiredService<IBlueskyApi>();
Login into Bluesky
string userName = Environment.GetEnvironmentVariable("BLUESKY_USERNAME")!;
string password = Environment.GetEnvironmentVariable("BLUESKY_PASSWORD")!;
Login command = new(userName, password);
Multiple<Session, Error> result = await api.Login(command, CancellationToken.None);
if (result.IsT1)
{
Console.WriteLine($"Error logging to Bluesky {JsonSerializer.Serialize(result.AsT1)}");
return;
}
Create posts!
CreatePost post = new CreatePost($"{quote.Text}\n -{quote.Author}".Substring(0, 255));
await api.CreatePost(post, CancellationToken.None);
And that’s it! You can create a file with daily inspirational quotes from Type.fit