Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
LucHeart committed Apr 15, 2024
0 parents commit 822c5da
Show file tree
Hide file tree
Showing 28 changed files with 921 additions and 0 deletions.
63 changes: 63 additions & 0 deletions .github/actions/containerize/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
name: containerize
description: Builds and pushes the frontend Docker image
inputs:
registry:
required: true
description: Container registry to push the image to
registry-path:
required: true
description: Path to the image in the container registry
registry-username:
required: true
description: Username to log in to the container registry
registry-password:
required: true
description: Password to log in to the container registry
artifact-name:
required: true
description: Name of the artifact to upload
push-image:
required: true
description: If true, pushes the image to the registry

runs:
using: composite
steps:
- name: Download internal artifacts
uses: actions/download-artifact@v4
with:
name: ${{ inputs.artifact-name }}
path: publish

- name: Set up Docker Build
uses: docker/setup-buildx-action@v3

- name: Log in to Container Registry
uses: docker/login-action@v3
with:
registry: ${{ inputs.registry }}
username: ${{ inputs.registry-username }}
password: ${{ inputs.registry-password }}

- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ inputs.registry }}/${{ inputs.registry-path }}
flavor: |
latest=false
tags: |
type=raw,value={{branch}},enable=${{ github.ref_type == 'branch' && github.event_name != 'pull_request' }}
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{major}},enable=${{ !startsWith(github.ref, 'refs/tags/v0') && !startsWith(github.ref, 'refs/tags/0') }}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}.{{minor}}.{{patch}}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
push: ${{ inputs.push-image }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
13 changes: 13 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
version: 2
updates:
# Weekly checks for nuget package updates
- package-ecosystem: 'nuget'
directory: '/'
schedule:
interval: 'weekly'
day: 'monday'
time: '06:00'
groups:
nuget-dependencies:
patterns:
- '*' # Group all updates together
70 changes: 70 additions & 0 deletions .github/workflows/ci-build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
on:
push:
branches:
- master
- develop
pull_request:
branches:
- master
- develop
types: [opened, reopened, synchronize]
workflow_call:
workflow_dispatch:

name: ci-build

env:
DOTNET_VERSION: 8.0.x
REGISTRY: ghcr.io

jobs:

build:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup .NET SDK ${{ env.DOTNET_VERSION }}
uses: actions/setup-dotnet@v4
with:
dotnet-version: ${{ env.DOTNET_VERSION }}

- name: Install dependencies
run: dotnet restore

- name: Build
run: dotnet build --configuration Release --no-restore

- name: Test
run: dotnet test --no-restore --verbosity normal

- name: Publish Discord Bot
run: dotnet publish DiscordBot/DiscordBot.csproj -c Release -o ./publish/DiscordBot

- name: Upload Discord Bot artifacts
uses: actions/upload-artifact@v4
with:
name: DiscordBot
path: publish/DiscordBot/*
retention-days: 1
if-no-files-found: error

containerize:
runs-on: ubuntu-latest
needs: build

steps:
- uses: actions/checkout@v4
with:
sparse-checkout: .github

- uses: ./.github/actions/containerize
with:
registry: ghcr.io
registry-path: ${{ github.repository_owner }}/discord-bot
registry-username: ${{ github.actor }}
registry-password: ${{ secrets.GITHUB_TOKEN }}
artifact-name: ManagerDiscordBot
push-image: ${{ github.ref_type == 'branch' && github.ref_protected && github.event_name != 'pull_request' }}
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
bin/
obj/
/packages/
riderModule.iml
/_ReSharper.Caches/
.idea
.vs
16 changes: 16 additions & 0 deletions DiscordBot.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordBot", "DiscordBot\DiscordBot.csproj", "{6E6A23CE-F1D3-4A7F-AF7F-ABB2D7C280FC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6E6A23CE-F1D3-4A7F-AF7F-ABB2D7C280FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6E6A23CE-F1D3-4A7F-AF7F-ABB2D7C280FC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6E6A23CE-F1D3-4A7F-AF7F-ABB2D7C280FC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6E6A23CE-F1D3-4A7F-AF7F-ABB2D7C280FC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
8 changes: 8 additions & 0 deletions DiscordBot/Backend/IOpenShockApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using OpenShock.DiscordBot.Backend.Models;

namespace OpenShock.DiscordBot.Backend;

public interface IOpenShockApi
{
public Task<BaseResponse<IEnumerable<ResponseDeviceWithShockers>>> GetOwnShockers(Uri server, string apiKey, CancellationToken ct = default);
}
22 changes: 22 additions & 0 deletions DiscordBot/Backend/Models/BaseResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Newtonsoft.Json;

// ReSharper disable UnusedAutoPropertyAccessor.Global

namespace OpenShock.DiscordBot.Backend.Models;

public class BaseResponse<T>
{
public string? Message { get; set; }
public T? Data { get; set; }

public BaseResponse(string? message = null, T? data = default)
{
Message = message;
Data = data;
}

public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
8 changes: 8 additions & 0 deletions DiscordBot/Backend/Models/ResponseDevice.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace OpenShock.DiscordBot.Backend.Models;

public class ResponseDevice
{
public required Guid Id { get; set; }
public required string Name { get; set; }
public required DateTime CreatedOn { get; set; }
}
6 changes: 6 additions & 0 deletions DiscordBot/Backend/Models/ResponseDeviceWithShockers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace OpenShock.DiscordBot.Backend.Models;

public class ResponseDeviceWithShockers : ResponseDevice
{
public required IEnumerable<ShockerResponse> Shockers { get; set; }
}
7 changes: 7 additions & 0 deletions DiscordBot/Backend/Models/ShockerModelType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace OpenShock.DiscordBot.Backend.Models;

public enum ShockerModelType
{
Small = 0,
PetTrainer = 1
}
15 changes: 15 additions & 0 deletions DiscordBot/Backend/Models/ShockerResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace OpenShock.DiscordBot.Backend.Models;

public class MinimalShocker
{
public required Guid Id { get; set; }
public required ushort RfId { get; set; }
public required ShockerModelType Model { get; set; }
}

public class ShockerResponse : MinimalShocker
{
public required string Name { get; set; }
public required bool IsPaused { get; set; }
public required DateTime CreatedOn { get; set; }
}
6 changes: 6 additions & 0 deletions DiscordBot/Backend/Models/StatsResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace OpenShock.DiscordBot.Backend.Models;

public class StatsResponse
{
public required int DevicesOnline { get; set; }
}
53 changes: 53 additions & 0 deletions DiscordBot/Backend/OpenShockApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System.Net.Mime;
using System.Text;
using System.Text.Json;
using Discord.WebSocket;
using Microsoft.Extensions.Logging;
using OneOf;
using OneOf.Types;
using OpenShock.DiscordBot.Backend.Models;

namespace OpenShock.DiscordBot.Backend;

public class OpenShockApi : IOpenShockApi
{
private static readonly HttpClient HttpClient = new();
private readonly DiscordSocketClient _client;
private readonly ILogger<OpenShockApi> _logger;

public OpenShockApi(DiscordSocketClient client, ILogger<OpenShockApi> logger)
{
_client = client;
_logger = logger;
}

public async Task<BaseResponse<IEnumerable<ResponseDeviceWithShockers>>> GetOwnShockers(Uri server, string apiKey,
CancellationToken ct = default)
{
var response =
await Request<IEnumerable<ResponseDeviceWithShockers>, object>(server, apiKey, "/1/shockers/own",
HttpMethod.Get, null, ct);

return new BaseResponse<IEnumerable<ResponseDeviceWithShockers>>();
}

private async Task<OneOf<BaseResponse<T>, OpenShockServerError, Error<string>>> Request<T, T1>(Uri server,
string apiKey,
string path, HttpMethod method, T1? requestBody, CancellationToken ct = default)
{
var request = new HttpRequestMessage(method, new Uri(server, path));
request.Content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, MediaTypeNames.Application.Json);
request.Headers.Add("OpenShockToken", apiKey);

var response = await HttpClient.SendAsync(request, ct);
var json = await JsonSerializer.DeserializeAsync<BaseResponse<T>>(await response.Content.ReadAsStreamAsync(ct),
cancellationToken: ct);
if (json == null)
{
_logger.LogError("Couldn't deserialize response body from openshock backend");
return new Error<string>("OpenShockApi::GetFromApi|json=null");
}

return json;
}
}
10 changes: 10 additions & 0 deletions DiscordBot/Backend/OpenShockServerError.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.Net;

namespace OpenShock.DiscordBot.Backend;

public readonly struct OpenShockServerError
{
public required HttpStatusCode StatusCode { get; init; }
public required string Message { get; init; }

}
44 changes: 44 additions & 0 deletions DiscordBot/Commands/SetupCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using Discord;
using Discord.Interactions;

namespace OpenShock.DiscordBot.Commands;

public class SetupCommand : InteractionModuleBase
{
[EnabledInDm(true)]

Check warning on line 8 in DiscordBot/Commands/SetupCommand.cs

View workflow job for this annotation

GitHub Actions / build

'EnabledInDmAttribute' is obsolete: 'This attribute will be deprecated soon. Configure with CommandContextTypes attribute instead.'

Check warning on line 8 in DiscordBot/Commands/SetupCommand.cs

View workflow job for this annotation

GitHub Actions / build

'EnabledInDmAttribute' is obsolete: 'This attribute will be deprecated soon. Configure with CommandContextTypes attribute instead.'
[SlashCommand("setup", "Start setup for use with OpenShock")]
public async Task ExecuteSetupCommand()
{
await Context.Interaction.RespondWithModalAsync<SetupModal>("setup_menu");
}

// Responds to the modal.
[ModalInteraction("setup_menu")]
public async Task ModalResponce(SetupModal modal)
{


// Build the message to send.
var message =
$"cock {Context.User.Mention} penis {modal.ApiKey} ballin {modal.ApiServer}.";

// Respond to the modal.
await RespondAsync(message, allowedMentions: new AllowedMentions(AllowedMentionTypes.Users));
}
}

public class SetupModal : IModal
{
public string Title => "OpenShock Connection";

[InputLabel("API Key")]
[RequiredInput]
[ModalTextInput("api_key", TextInputStyle.Short, "Enter your API key...", maxLength: 256)]
public required string ApiKey { get; init; }

// Additional paremeters can be specified to further customize the input.
[InputLabel("OpenShock API server")]
[RequiredInput]
[ModalTextInput("api_server", TextInputStyle.Short, "https://api.shocklink.net", maxLength: 256, initValue: "https://api.shocklink.net")]
public required string ApiServer { get; init; }
}
15 changes: 15 additions & 0 deletions DiscordBot/Commands/TestCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Discord.Interactions;

namespace OpenShock.DiscordBot.Commands;

public class TestCommand : InteractionModuleBase
{

[SlashCommand("test", "test")]
public async Task Execute()
{
await RespondAsync("Test");
Context.Interaction.RespondAsync();

Check warning on line 12 in DiscordBot/Commands/TestCommand.cs

View workflow job for this annotation

GitHub Actions / build

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Check warning on line 12 in DiscordBot/Commands/TestCommand.cs

View workflow job for this annotation

GitHub Actions / build

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
}

}
Loading

0 comments on commit 822c5da

Please sign in to comment.