diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml new file mode 100644 index 0000000..25f43e7 --- /dev/null +++ b/.github/workflows/dotnet.yml @@ -0,0 +1,28 @@ +# This workflow will build a .NET project +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-net + +name: .NET + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Setup .NET + uses: actions/setup-dotnet@v3 + with: + dotnet-version: 6.0.x + - name: Restore dependencies + run: dotnet restore + - name: Build + run: dotnet build --no-restore + - name: Test + run: dotnet test --no-build --verbosity normal diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9848aa7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,489 @@ +### DotnetCore template +# .NET Core build folders +bin/ +obj/ + +# Common node modules locations +/node_modules +/wwwroot/node_modules + +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Csharp template +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +.env diff --git a/Common/DiscordManager.cs b/Common/DiscordManager.cs new file mode 100644 index 0000000..f5717d7 --- /dev/null +++ b/Common/DiscordManager.cs @@ -0,0 +1,33 @@ +using Discord; +using Discord.WebSocket; + +namespace Approvers.King.Common; + +public static class DiscordManager +{ + public static readonly DiscordSocketClient Client = new(new DiscordSocketConfig + { + GatewayIntents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages, + }); + + public static async Task InitializeAsync() + { + Client.Log += OnLog; + await Client.LoginAsync(TokenType.Bot, SettingManager.Get("DISCORD_SECRET")); + await Client.StartAsync(); + } + + private static Task OnLog(LogMessage content) + { + Console.WriteLine(content.ToString()); + return Task.CompletedTask; + } + + public static async Task ExecuteAsync(SocketUserMessage message, Func? onInitializeAsync = null) + where T : DiscordMessagePresenterBase, new() + { + var presenter = new T { Message = message }; + if (onInitializeAsync != null) await onInitializeAsync.Invoke(presenter); + await presenter.RunAsync(); + } +} \ No newline at end of file diff --git a/Common/DiscordMessagePresenterBase.cs b/Common/DiscordMessagePresenterBase.cs new file mode 100644 index 0000000..7f098d4 --- /dev/null +++ b/Common/DiscordMessagePresenterBase.cs @@ -0,0 +1,8 @@ +using Discord.WebSocket; + +namespace Approvers.King.Common; + +public abstract class DiscordMessagePresenterBase : PresenterBase +{ + public SocketUserMessage Message { get; init; } = null!; +} \ No newline at end of file diff --git a/Common/MasterManager.cs b/Common/MasterManager.cs new file mode 100644 index 0000000..29bc2a8 --- /dev/null +++ b/Common/MasterManager.cs @@ -0,0 +1,18 @@ +namespace Approvers.King.Common; + +public static class MasterManager +{ + public static double ReplyRate => 0.05; + + public static IReadOnlyList<(float rate, string message)> ReplyMessages => new List<(float rate, string message)> + { + (1f, "あほしね"), + (1f, "ばか"), + (1f, "かす"), + (1f, "わかる"), + (1f, "草"), + (1f, "あほくさ"), + (1f, "noob"), + (1f, "それね、ちょっと分かる"), + }; +} \ No newline at end of file diff --git a/Common/PresenterBase.cs b/Common/PresenterBase.cs new file mode 100644 index 0000000..58b69a9 --- /dev/null +++ b/Common/PresenterBase.cs @@ -0,0 +1,31 @@ +using Discord; + +namespace Approvers.King.Common; + +public abstract class PresenterBase +{ + public async Task RunAsync() + { + try + { + await MainAsync(); + } + catch (Exception e) + { + await Console.Error.WriteLineAsync("========================================\n"); + Console.Error.Write(e); + } + } + + protected abstract Task MainAsync(); + + public static Embed ErrorEmbed(string message) + { + return new EmbedBuilder() + .WithColor(Color.Red) + .WithTitle("⚠ エラー") + .WithDescription(message) + .WithCurrentTimestamp() + .Build(); + } +} \ No newline at end of file diff --git a/Common/SettingManager.cs b/Common/SettingManager.cs new file mode 100644 index 0000000..853a74c --- /dev/null +++ b/Common/SettingManager.cs @@ -0,0 +1,19 @@ +using Microsoft.Extensions.Configuration; + +namespace Approvers.King.Common; + +public class SettingManager +{ + private static IConfigurationRoot Configuration { get; } = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json", true) + .AddEnvironmentVariables() + .AddUserSecrets(true) + .Build(); + + public static string Get(string name) + { + return Configuration[name] ?? + throw new Exception($"Environment variable {name} is not set."); + } +} \ No newline at end of file diff --git a/DiscordEntry.cs b/DiscordEntry.cs new file mode 100644 index 0000000..342d67f --- /dev/null +++ b/DiscordEntry.cs @@ -0,0 +1,22 @@ +using Approvers.King.Common; +using Approvers.King.Events; +using Discord.WebSocket; + +namespace Approvers.King; + +public static class DiscordEntry +{ + public static void RegisterEvents() + { + DiscordManager.Client.MessageReceived += OnMessageReceived; + } + + private static async Task OnMessageReceived(SocketMessage message) + { + // botは弾く + if (message is not SocketUserMessage userMessage || userMessage.Author.IsBot) return; + + // 発言 + await DiscordManager.ExecuteAsync(userMessage); + } +} \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..22b3b68 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,10 @@ +FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build +WORKDIR /App +COPY . . +RUN dotnet restore +RUN dotnet publish -c Release -o out + +FROM mcr.microsoft.com/dotnet/runtime:7.0 AS runtime +WORKDIR /App +COPY --from=build /App/out . +ENTRYPOINT ["dotnet", "king-server.dll"] \ No newline at end of file diff --git a/Environment/docker-compose.yml b/Environment/docker-compose.yml new file mode 100644 index 0000000..302e99f --- /dev/null +++ b/Environment/docker-compose.yml @@ -0,0 +1,8 @@ +version: "3" + +services: + app: + image: [ docker_user_id ]/king-server:latest + environment: + DISCORD_SECRET: SECRET # Change this + TZ: Asia/Tokyo \ No newline at end of file diff --git a/Events/ReplyPresenter.cs b/Events/ReplyPresenter.cs new file mode 100644 index 0000000..a2dae3c --- /dev/null +++ b/Events/ReplyPresenter.cs @@ -0,0 +1,33 @@ +using Approvers.King.Common; +using Discord; + +namespace Approvers.King.Events; + +public class ReplyPresenter : DiscordMessagePresenterBase +{ + private static readonly Random Random = new(); + + protected override async Task MainAsync() + { + var rand = Random.NextDouble(); + Console.WriteLine($"rand: {rand}"); + if (rand > MasterManager.ReplyRate) return; + + await Message.ReplyAsync(PickRandomMessage()); + } + + private static string PickRandomMessage() + { + var totalRate = MasterManager.ReplyMessages.Sum(x => x.rate); + var value = Random.NextDouble() * totalRate; + + foreach (var (rate, message) in MasterManager.ReplyMessages) + { + if (value < rate) return message; + + value -= rate; + } + + return MasterManager.ReplyMessages[^1].message; + } +} \ No newline at end of file diff --git a/Folder.DotSettings b/Folder.DotSettings new file mode 100644 index 0000000..b6ca8b0 --- /dev/null +++ b/Folder.DotSettings @@ -0,0 +1,5 @@ + + True \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0211362 --- /dev/null +++ b/Makefile @@ -0,0 +1,3 @@ +.PHONY: run +run: + dotnet run diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..053dc79 --- /dev/null +++ b/Program.cs @@ -0,0 +1,21 @@ +using Approvers.King.Common; + +namespace Approvers.King; + +public class Program +{ + private static void Main(string[] args) + { + BuildAsync(args).GetAwaiter().GetResult(); + } + + private static async Task BuildAsync(string[] args) + { + await DiscordManager.InitializeAsync(); + + DiscordEntry.RegisterEvents(); + + // 永久に待つ + await Task.Delay(-1); + } +} \ No newline at end of file diff --git a/appsettings.json b/appsettings.json new file mode 100644 index 0000000..8b72436 --- /dev/null +++ b/appsettings.json @@ -0,0 +1,3 @@ +{ + "DISCORD_SECRET": "" +} \ No newline at end of file diff --git a/king-server.csproj b/king-server.csproj new file mode 100644 index 0000000..33b01f5 --- /dev/null +++ b/king-server.csproj @@ -0,0 +1,24 @@ + + + + Exe + net7.0 + Approvers.King + enable + enable + df5761a4-8b04-42f7-b09e-696dcbb74b3c + king-server + + + + + + + + + + + + + + diff --git a/king-server.csproj.DotSettings b/king-server.csproj.DotSettings new file mode 100644 index 0000000..ce976a5 --- /dev/null +++ b/king-server.csproj.DotSettings @@ -0,0 +1,66 @@ + + False + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + False + True + True + True + True + True + True + True + True + True + True \ No newline at end of file diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..ab36d56 --- /dev/null +++ b/readme.md @@ -0,0 +1,27 @@ +# king-server + +## デプロイ方法のメモ + +1. dockerイメージのビルド + +```shell +# 開発環境 +$ docker build . -t [docker_user_id]/king-server +``` + +2. dockerイメージのpush + +```shell +# 開発環境 +$ docker push [docker_user_id]/king-server +``` + +3. 実行環境のリフレッシュ + +```shell +# デプロイ先にログインして、以下を実行 +# 初回の場合は、適当なディレクトリを用意して Environment/ 以下をSCP等でコピーしてください(書き換え必須の部分があるため、適宜書き換えてください) +$ docker pull [docker_user_id]/king-server +$ docker compose down +$ docker compose up -d +``` \ No newline at end of file