Skip to content

Commit

Permalink
Added github integration
Browse files Browse the repository at this point in the history
added new releases command in public module
  • Loading branch information
Floydan committed May 6, 2020
1 parent 3a81af4 commit c223119
Show file tree
Hide file tree
Showing 8 changed files with 189 additions and 52 deletions.
38 changes: 36 additions & 2 deletions PickupBot.Commands/Modules/PublicModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Addons.CommandsExtension;
using Discord.Commands;
using PickupBot.Commands.Extensions;
using PickupBot.Data.Models;
using PickupBot.Data.Repositories;
using PickupBot.GitHub;
using PickupBot.GitHub.Models;

namespace PickupBot.Commands.Modules
{
Expand All @@ -17,13 +20,16 @@ public class PublicModule : ModuleBase<SocketCommandContext>
{
private readonly CommandService _commandService;
private readonly ISubscriberActivitiesRepository _activitiesRepository;

private readonly GitHubService _githubService;

public PublicModule(
CommandService commandService,
ISubscriberActivitiesRepository activitiesRepository)
ISubscriberActivitiesRepository activitiesRepository,
GitHubService gitHubService)
{
_commandService = commandService;
_activitiesRepository = activitiesRepository;
_githubService = gitHubService;
}

[Command("ping")]
Expand Down Expand Up @@ -114,5 +120,33 @@ public async Task Top10()

await ReplyAsync(sb.ToString());
}

[Command("releases")]
[Summary("Retrieves the 3 latest releases from github")]
public async Task Releases()
{
using (Context.Channel.EnterTypingState())
{
var releases = await _githubService.GetReleases();

var gitHubReleases = releases as GitHubRelease[] ?? releases.ToArray();

foreach (var release in gitHubReleases.Take(3))
{
var embed = new EmbedBuilder
{
Author = new EmbedAuthorBuilder()
.WithIconUrl(release.Author?.AvatarUrl)
.WithName(release.Author?.Name),
Title = release.Name,
Description = release.Body,
Url = release.Url

}.Build();

await ReplyAsync(embed:embed);
}
}
}
}
}
3 changes: 2 additions & 1 deletion PickupBot.Commands/PickupBot.Commands.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
Expand All @@ -13,6 +13,7 @@

<ItemGroup>
<ProjectReference Include="..\PickupBot.Data\PickupBot.Data.csproj" />
<ProjectReference Include="..\PickupBot.GitHub\PickupBot.GitHub.csproj" />
<ProjectReference Include="..\PickupBot.Translation\PickupBot.Translation.csproj" />
</ItemGroup>

Expand Down
47 changes: 47 additions & 0 deletions PickupBot.GitHub/GitHubService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using PickupBot.GitHub.Models;

namespace PickupBot.GitHub
{
public class GitHubService
{
private readonly HttpClient _client;

public GitHubService(HttpClient client)
{
client.BaseAddress = new Uri("https://api.github.com/");

client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
client.DefaultRequestHeaders.Add("User-Agent", "Discord-Pickup-Bot");

_client = client;
}

public async Task<string> GetCommits(int count = 10)
{
var response = await _client.GetAsync("/repos/Floydan/discord-pickup-bot/commits");

if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}

return $"StatusCode: {response.StatusCode}";
}

public async Task<IEnumerable<GitHubRelease>> GetReleases(int count = 3)
{
var response = await _client.GetAsync("/repos/Floydan/discord-pickup-bot/releases");

if (!response.IsSuccessStatusCode) return null;

await using var stream = await response.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync<IEnumerable<GitHubRelease>>(stream);

}
}
}
33 changes: 33 additions & 0 deletions PickupBot.GitHub/Models/GitHubRelease.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json.Serialization;

namespace PickupBot.GitHub.Models
{
public class GitHubRelease
{
[JsonPropertyName("author")]
public GitHubAuthor Author { get; set; }

[JsonPropertyName("name")]
public string Name { get; set; }

[JsonPropertyName("body")]
public string Body { get; set; }

[JsonPropertyName("published_at")]
public DateTime PublishedDate { get; set; }

[JsonPropertyName("html_url")]
public string Url { get; set; }
}

public class GitHubAuthor
{
[JsonPropertyName("login")]
public string Name { get; set; }
[JsonPropertyName("avatar_url")]
public string AvatarUrl { get; set; }
}
}
11 changes: 11 additions & 0 deletions PickupBot.GitHub/PickupBot.GitHub.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.3" />
</ItemGroup>

</Project>
8 changes: 7 additions & 1 deletion PickupBot.sln
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PickupBot.Data", "PickupBot.Data\PickupBot.Data.csproj", "{8CC4FB91-0E70-43E4-8879-D37FF529E43A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PickupBot.Translation", "PickupBot.Translation\PickupBot.Translation.csproj", "{1FE7EA78-D812-4895-9621-ECB2188F8A2E}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PickupBot.Translation", "PickupBot.Translation\PickupBot.Translation.csproj", "{1FE7EA78-D812-4895-9621-ECB2188F8A2E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PickupBot.GitHub", "PickupBot.GitHub\PickupBot.GitHub.csproj", "{1A49EC39-5147-48A3-AB5B-F1FFDEE253CE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -39,6 +41,10 @@ Global
{1FE7EA78-D812-4895-9621-ECB2188F8A2E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1FE7EA78-D812-4895-9621-ECB2188F8A2E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1FE7EA78-D812-4895-9621-ECB2188F8A2E}.Release|Any CPU.Build.0 = Release|Any CPU
{1A49EC39-5147-48A3-AB5B-F1FFDEE253CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1A49EC39-5147-48A3-AB5B-F1FFDEE253CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1A49EC39-5147-48A3-AB5B-F1FFDEE253CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1A49EC39-5147-48A3-AB5B-F1FFDEE253CE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
5 changes: 4 additions & 1 deletion PickupBot/PickupBot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,20 @@
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>a7bb364b-0d73-420c-a3b9-18270f20e20f</UserSecretsId>
<Version>1.5.1</Version>
<Version>1.6.0</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Azure" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="3.1.3" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.3" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.3" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PickupBot.Commands\PickupBot.Commands.csproj" />
<ProjectReference Include="..\PickupBot.Data\PickupBot.Data.csproj" />
<ProjectReference Include="..\PickupBot.GitHub\PickupBot.GitHub.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="Settings.job">
Expand Down
96 changes: 49 additions & 47 deletions PickupBot/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,44 +6,82 @@
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PickupBot.Commands;
using PickupBot.Data.Models;
using PickupBot.Data.Repositories;
using PickupBot.GitHub;
using PickupBot.Translation.Services;

namespace PickupBot
{
public class Program
{
public static void Main(string[] args) => new Program().MainAsync().GetAwaiter().GetResult();

private async Task MainAsync()
private static IHost _host;
private static async Task Main(string[] args)
{
await using var services = ConfigureServices();
var storageConnectionString = Environment.GetEnvironmentVariable("StorageConnectionString");

ServiceLocator.SetLocatorProvider(services);
var client = services.GetRequiredService<DiscordSocketClient>();
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
var discordSocketConfig = new DiscordSocketConfig { MessageCacheSize = 100, LogLevel = LogSeverity.Info };

services
.AddHttpClient()
.AddSingleton<DiscordSocketClient>(provider => new DiscordSocketClient(discordSocketConfig))
.AddSingleton<CommandService>()
.AddSingleton<ITranslationService, GoogleTranslationService>()
.AddSingleton<CommandHandlerService>()
.AddSingleton<HttpClient>()
.AddScoped<IAzureTableStorage<PickupQueue>>(provider =>
new AzureTableStorage<PickupQueue>(
new AzureTableSettings(storageConnectionString, nameof(PickupQueue))
)
)
.AddScoped<IAzureTableStorage<FlaggedSubscriber>>(provider =>
new AzureTableStorage<FlaggedSubscriber>(
new AzureTableSettings(storageConnectionString, nameof(FlaggedSubscriber))
)
)
.AddScoped<IAzureTableStorage<SubscriberActivities>>(provider =>
new AzureTableStorage<SubscriberActivities>(
new AzureTableSettings(storageConnectionString, nameof(SubscriberActivities))
)
)
.AddScoped<IQueueRepository, PickupQueueRepository>()
.AddScoped<IFlaggedSubscribersRepository, FlaggedSubscribersRepository>()
.AddScoped<ISubscriberActivitiesRepository, SubscriberActivitiesRepository>();


services.AddHttpClient<GitHubService>();

}).UseConsoleLifetime();

_host = builder.Build();

var client = _host.Services.GetRequiredService<DiscordSocketClient>();

client.Log += LogAsync;
client.JoinedGuild += OnJoinedGuild;
client.MessageUpdated += OnMessageUpdated;
services.GetRequiredService<CommandService>().Log += LogAsync;
_host.Services.GetRequiredService<CommandService>().Log += LogAsync;

// Tokens should be considered secret data and never hard-coded.
// We can read from the environment variable to avoid hardcoding.
await client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("DiscordToken"));
await client.StartAsync();

// Here we initialize the logic required to register our commands.
await services.GetRequiredService<CommandHandlerService>().InitializeAsync();
await _host.Services.GetRequiredService<CommandHandlerService>().InitializeAsync();

//await client.SetGameAsync("Pickup bot", null, ActivityType.Playing);
var prefix = Environment.GetEnvironmentVariable("CommandPrefix") ?? "!";
await client.SetActivityAsync(
new Game($"Pickup bot | {prefix}help",
ActivityType.Playing,
ActivityProperties.Play,
$"Current players on ra3.se: 3"));
ActivityProperties.Play));

await Task.Delay(-1);
}
Expand Down Expand Up @@ -76,10 +114,7 @@ await guild.CreateTextChannelAsync("pickup",

private static async Task OnMessageUpdated(Cacheable<IMessage, ulong> before, SocketMessage after, ISocketMessageChannel channel)
{
//var message = await before.GetOrDownloadAsync();
//await LogAsync(new LogMessage(LogSeverity.Info, "OnMessageUpdated", $"{message} -> {after}"));

var commandHandler = ServiceLocator.Current.GetInstance<CommandHandlerService>();
var commandHandler = _host.Services.GetService<CommandHandlerService>();
if (commandHandler != null)
await commandHandler.MessageReceivedAsync(after);
}
Expand All @@ -89,38 +124,5 @@ private static Task LogAsync(LogMessage msg)
Console.WriteLine(msg.ToString());
return Task.CompletedTask;
}

private static ServiceProvider ConfigureServices()
{
var storageConnectionString = Environment.GetEnvironmentVariable("StorageConnectionString");

var discordSocketConfig = new DiscordSocketConfig { MessageCacheSize = 100, LogLevel = LogSeverity.Info };

return new ServiceCollection()
.AddSingleton<DiscordSocketClient>(provider => new DiscordSocketClient(discordSocketConfig))
.AddSingleton<CommandService>()
.AddSingleton<ITranslationService, GoogleTranslationService>()
.AddSingleton<CommandHandlerService>()
.AddSingleton<HttpClient>()
.AddScoped<IAzureTableStorage<PickupQueue>>(provider =>
new AzureTableStorage<PickupQueue>(
new AzureTableSettings(storageConnectionString, nameof(PickupQueue))
)
)
.AddScoped<IAzureTableStorage<FlaggedSubscriber>>(provider =>
new AzureTableStorage<FlaggedSubscriber>(
new AzureTableSettings(storageConnectionString, nameof(FlaggedSubscriber))
)
)
.AddScoped<IAzureTableStorage<SubscriberActivities>>(provider =>
new AzureTableStorage<SubscriberActivities>(
new AzureTableSettings(storageConnectionString, nameof(SubscriberActivities))
)
)
.AddScoped<IQueueRepository, PickupQueueRepository>()
.AddScoped<IFlaggedSubscribersRepository, FlaggedSubscribersRepository>()
.AddScoped<ISubscriberActivitiesRepository, SubscriberActivitiesRepository>()
.BuildServiceProvider();
}
}
}

0 comments on commit c223119

Please sign in to comment.