Skip to content

Instantly share code, notes, and snippets.

@JamieMagee
Last active March 4, 2022 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamieMagee/fb5ffc670bd4f7cdb3378eca33cfc12f to your computer and use it in GitHub Desktop.
Save JamieMagee/fb5ffc670bd4f7cdb3378eca33cfc12f to your computer and use it in GitHub Desktop.
Writing GitHub bots in .NET
dotnet add package Octokit.Webhooks.AspNetCore
dotnet add package Octokit
using Octokit.Webhooks;
using Octokit.Webhooks.Events;
using Octokit.Webhooks.Events.IssueComment;
public sealed class MyWebhookEventProcessor : WebhookEventProcessor
{
private readonly ILogger<MyWebhookEventProcessor> logger;
public MyWebhookEventProcessor(ILogger<MyWebhookEventProcessor> logger)
{
this.logger = logger;
}
protected override Task ProcessIssueCommentWebhookAsync(WebhookHeaders headers, IssueCommentEvent issueCommentEvent, IssueCommentAction action)
{
this.logger.LogInformation(issueCommentEvent.Comment.Body);
return Task.CompletedTask;
}
}
private readonly GitHubClient client;
public MyWebhookEventProcessor(ILogger<MyWebhookEventProcessor> logger)
{
this.logger = logger;
this.client = new GitHubClient(new ProductHeaderValue("octokit-webhooks-sample"))
{
Credentials = new Credentials("...")
};
}
protected override async Task ProcessIssueCommentWebhookAsync(WebhookHeaders headers, IssueCommentEvent issueCommentEvent, IssueCommentAction action)
{
this.logger.LogInformation(issueCommentEvent.Comment.Body);
await this.client.Issue.Comment.Create(
repositoryId: issueCommentEvent.Repository.Id,
number: (int)issueCommentEvent.Issue.Number,
newComment: "Hello, world!"
);
}
dotnet new webapi --output octokit-webhooks-sample
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5002
$ ssh -R 80:localhost:5002 nokey@localhost.run
...
b49b69845954b1.lhrtunnel.link tunneled with tls termination, https://b49b69845954b1.lhrtunnel.link
info: MyWebhookEventProcessor[0]
Test comment
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Run();
using Octokit.Webhooks;
using Octokit.Webhooks.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<WebhookEventProcessor, MyWebhookEventProcessor>();
var app = builder.Build();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGitHubWebhooks();
});
app.Run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment