Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: メッセージフォーマットを整理 #47

Merged
merged 3 commits into from
Dec 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions Common/Discord/DiscordFormatUtility.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Text;
using Discord;

namespace Approvers.King.Common;

public static class DiscordFormatUtility
{
public static string Smile => MasterManager.SettingMaster.CommonSmileFormat;
public static string Missing => MasterManager.SettingMaster.CommonMissingMessage;

public static string Repeat(this string value, int count, string separator = "")
{
return string.Join(separator, EnumerableUtility.Repeat(value, count));
}

public static string Custom(this string value, string formatter)
{
var isBold = formatter.Contains("b");
var isItalic = formatter.Contains("i");
var isUnderline = formatter.Contains("u");
var isStrike = formatter.Contains("s");
var isCode = formatter.Contains("c");
var isSpoiler = formatter.Contains("p");

var result = value;
if (isBold) result = Format.Bold(result);
if (isItalic) result = Format.Italics(result);
if (isUnderline) result = Format.Underline(result);
if (isStrike) result = Format.Strikethrough(result);
if (isCode) result = Format.Code(result);
if (isSpoiler) result = Format.Spoiler(result);

return result;
}

public static string Table(IEnumerable<(string key, string value)> records)
{
var recordList = records.ToList();
var maxLength = recordList.Max(r => r.key.Length);
var sb = new StringBuilder();
foreach (var (key, value) in recordList)
{
sb.AppendLine($"| {value.PadLeft(maxLength)} | {Format.Sanitize(key)}");
}

return Format.Code(sb.ToString());
}
}
20 changes: 0 additions & 20 deletions Common/Discord/DiscordMessageUtility.cs

This file was deleted.

10 changes: 10 additions & 0 deletions Common/Master/SettingMaster.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,16 @@ private int GetInt(string key)
public int SlotRepeatPermillageUpperBound => GetInt(nameof(SlotRepeatPermillageUpperBound));

public Multiplier SlotRepeatUpperBound => Multiplier.FromPermillage(SlotRepeatPermillageUpperBound);

/// <summary>
/// 汎用的な笑顔の絵文字フォーマット
/// </summary>
public string CommonSmileFormat => GetString(nameof(CommonSmileFormat));

/// <summary>
/// 汎用的な存在しないメッセージ
/// </summary>
public string CommonMissingMessage => GetString(nameof(CommonMissingMessage));
}

[SuppressMessage("ReSharper", "UnassignedGetOnlyAutoProperty")]
Expand Down
9 changes: 0 additions & 9 deletions Common/Time/TimeManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ public class TimeManager : Singleton<TimeManager>
{
public static TimeSpan DailyResetTime => TimeSpan.FromMilliseconds(MasterManager.SettingMaster.DailyResetTime);
public static int MonthlyResetDay => MasterManager.SettingMaster.MonthlyResetDay;
public static DateTime Birthday => new(1, MasterManager.SettingMaster.BirthdayMonth, MasterManager.SettingMaster.BirthdayDay);

private DateTime? _debugBaseTime;
private TimeSpan _debugTimeOffset;
Expand All @@ -28,12 +27,4 @@ public static DateTime GetNow()
{
return DateTime.Now.ToLocalTime() + Instance._debugTimeOffset;
}

/// <summary>
/// 時間を過ぎていればtrue
/// </summary>
public static bool IsExpired(DateTime time)
{
return GetNow() > time;
}
}
5 changes: 0 additions & 5 deletions Common/Utility/EnumerableUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,4 @@ public static IEnumerable<T> Repeat<T>(T value, int count)
{
for (var i = 0; i < count; i++) yield return value;
}

public static IEnumerable<T> Repeat<T>(Func<T> value, int count)
{
for (var i = 0; i < count; i++) yield return value();
}
}
3 changes: 1 addition & 2 deletions Events/Admin/AdminMasterReloadPresenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ public class AdminMasterReloadPresenter : DiscordMessagePresenterBase
{
protected override async Task MainAsync()
{
await Message.ReplyAsync("マスターをリロードするぞ");
await MasterManager.FetchAsync();
await Message.ReplyAsync("マスターをリロードしたぞ");
await Message.ReplyAsync("done(ドゥーン)");
}
}
23 changes: 0 additions & 23 deletions Events/DailyReset/DailyResetBirthPresenter.cs

This file was deleted.

27 changes: 26 additions & 1 deletion Events/DailyReset/DailyResetPresenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@

namespace Approvers.King.Events;

using F = DiscordFormatUtility;

/// <summary>
/// 毎日のリセットを行うイベント
/// </summary>
public class DailyResetPresenter : SchedulerJobPresenterBase
{
protected override async Task MainAsync()
{
var now = TimeManager.GetNow();

await using var app = AppService.CreateSession();

var slotMaxUsers = await app.Users
Expand All @@ -33,6 +37,13 @@ protected override async Task MainAsync()
// 排出率を投稿する
await DiscordManager.GetMainChannel().SendMessageAsync(embed: GachaUtility.GetInfoEmbedBuilder(gacha).Build());

// 誕生日なら祝わせる
var isBirthday = now.Month == MasterManager.SettingMaster.BirthdayMonth && now.Day == MasterManager.SettingMaster.BirthdayDay;
if (isBirthday)
{
await SendBirthdayMessageAsync();
}

// スロットの実行回数が最大になったユーザーを通知する
await NotifySlotMaxUsers(slotMaxUsers);
}
Expand All @@ -45,7 +56,7 @@ private async Task NotifySlotMaxUsers(IReadOnlyList<User> users)
}

var sb = new StringBuilder();
sb.AppendLine("**\u2b07\ufe0e\u2b07\ufe0e\u2b07\ufe0e 昨日のスロカス一覧がこちらw \u2b07\ufe0e\u2b07\ufe0e\u2b07\ufe0e**");
sb.AppendLine("\u2b07\ufe0e\u2b07\ufe0e\u2b07\ufe0e 昨日のスロカス一覧がこちらw \u2b07\ufe0e\u2b07\ufe0e\u2b07\ufe0e".Custom("b"));
sb.AppendLine();
foreach (var user in users)
{
Expand All @@ -54,4 +65,18 @@ private async Task NotifySlotMaxUsers(IReadOnlyList<User> users)

await DiscordManager.GetMainChannel().SendMessageAsync(sb.ToString());
}

private async Task SendBirthdayMessageAsync()
{
var message = $"""
{F.Smile.Repeat(16)}
{F.Smile}                    {F.Smile}
{F.Smile} ***† 誕 生 日 だ 祝 え カ ス †*** {F.Smile}
{F.Smile}                    {F.Smile}
{F.Smile.Repeat(16)}
""";

// 誕生日を祝わせる
await DiscordManager.GetMainChannel().SendMessageAsync(message);
}
}
9 changes: 5 additions & 4 deletions Events/Gacha/GachaCommandPresenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Approvers.King.Events;

using F = DiscordFormatUtility;

/// <summary>
/// 10連ガチャを回すイベント
/// </summary>
Expand All @@ -28,9 +30,8 @@ private async Task SendReplyAsync(User user, IReadOnlyList<GachaItem?> results)
foreach (var result in results)
{
builder.AppendLine(result != null
? Format.Bold(
$"・{result.RandomMessage?.Content ?? MessageConst.MissingMessage} ({result.Probability.Rate:P0})")
: Format.Code("x"));
? $"・{result.RandomMessage?.Content ?? F.Missing} ({result.Probability.Rate:P0})".Custom("b")
: "x".Custom("c"));
}

// 爆死してたら煽る
Expand All @@ -39,7 +40,7 @@ private async Task SendReplyAsync(User user, IReadOnlyList<GachaItem?> results)
builder.AppendLine();
var messages = MasterManager.RandomMessageMaster.GetAll(x => x.Type == RandomMessageType.GachaFailed);
var failedMessage = RandomManager.PickRandom(messages).Content;
builder.AppendLine(Format.Bold(Format.Italics(failedMessage)));
builder.AppendLine(failedMessage.Custom("bi"));
}

builder.AppendLine();
Expand Down
4 changes: 3 additions & 1 deletion Events/Gacha/GachaInteractReplyPresenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

namespace Approvers.King.Events;

using F = DiscordFormatUtility;

/// <summary>
/// 確定ガチャを回すイベント
/// </summary>
Expand All @@ -15,7 +17,7 @@ protected override async Task MainAsync()
var gacha = await app.GetDefaultGachaAsync();

var message = user.RollGachaOnceCertain(gacha);
await SendReplyAsync(message.RandomMessage?.Content ?? MessageConst.MissingMessage);
await SendReplyAsync(message.RandomMessage?.Content ?? F.Missing);

await app.SaveChangesAsync();
}
Expand Down
4 changes: 3 additions & 1 deletion Events/Gacha/GachaRareReplyPresenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

namespace Approvers.King.Events;

using F = DiscordFormatUtility;

/// <summary>
/// 単発ガチャを回すイベント
/// </summary>
Expand All @@ -22,7 +24,7 @@ protected override async Task MainAsync()
var message = user.RollGachaOnce(gacha);
if (message != null)
{
await SendReplyAsync(message.RandomMessage?.Content ?? MessageConst.MissingMessage);
await SendReplyAsync(message.RandomMessage?.Content ?? F.Missing);
}

await app.SaveChangesAsync();
Expand Down
15 changes: 7 additions & 8 deletions Events/Gacha/GachaUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Approvers.King.Events;

using F = DiscordFormatUtility;

public static class GachaUtility
{
public static EmbedBuilder GetInfoEmbedBuilder(Gacha gacha)
Expand All @@ -12,13 +14,12 @@ public static EmbedBuilder GetInfoEmbedBuilder(Gacha gacha)
var records = gacha.GachaItems
.OrderByDescending(x => x.Probability)
.Where(x => x.Probability > minProbability)
.Select(x => (x.RandomMessage?.Content ?? MessageConst.MissingMessage, x.Probability.Rate.ToString("P0")));
.Select(x => (x.RandomMessage?.Content ?? F.Missing, x.Probability.Rate.ToString("P0")));
return new EmbedBuilder()
.WithTitle(
$"{IssoUtility.SmileStamp}{IssoUtility.SmileStamp}{IssoUtility.SmileStamp} 本日のいっそう {IssoUtility.SmileStamp}{IssoUtility.SmileStamp}{IssoUtility.SmileStamp}")
.WithTitle($"{F.Smile.Repeat(3)} 本日のいっそう {F.Smile.Repeat(3)}")
.WithColor(new Color(0xf1, 0xc4, 0x0f))
.WithDescription($"本日は {Format.Bold($"{gacha.HitProbability.Rate:P0}")} の確率で反応します")
.AddField("排出確率", DiscordMessageUtility.Table(records));
.WithDescription($"本日は {$"{gacha.HitProbability.Rate:P0}".Custom("b")} の確率で反応します")
.AddField("排出確率", F.Table(records));
}

public static string CreateRankingView(IReadOnlyList<User> rankingUsers)
Expand All @@ -29,9 +30,7 @@ public static string CreateRankingView(IReadOnlyList<User> rankingUsers)
{
var scoreText = Math.Min(999_999_999, user.MonthlyGachaPurchasePrice).ToString("N0");
var whiteSpace = Math.Max(0, 11 - scoreText.Length);
var line =
Format.Code($"#{order:D2} - {"".PadLeft(whiteSpace, ' ')}{scoreText}†カス†(税込)") + " " +
MentionUtils.MentionUser(user.DiscordId);
var line = $"#{order:D2} - {"".PadLeft(whiteSpace, ' ')}{scoreText}†カス†(税込)".Custom("c") + " " + MentionUtils.MentionUser(user.DiscordId);
embedBuilder.AppendLine(line);
order++;
}
Expand Down
6 changes: 0 additions & 6 deletions Events/IssoUtility.cs

This file was deleted.

2 changes: 1 addition & 1 deletion Events/Marugame/MarugamePresenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ protected override async Task MainAsync()
return;
}

var message = Format.Code(ConvertMessageToVertical(Content));
var message = ConvertMessageToVertical(Content).Custom("c");
await Message.ReplyAsync(message);
}

Expand Down
6 changes: 0 additions & 6 deletions Events/MessageConst.cs

This file was deleted.

4 changes: 3 additions & 1 deletion Events/MonthlyReset/MonthlyResetPresenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Approvers.King.Events;

using F = DiscordFormatUtility;

/// <summary>
/// 毎月のリセットを行うイベント
/// </summary>
Expand Down Expand Up @@ -34,7 +36,7 @@ private async Task SendSummaryAsync(IReadOnlyList<User> purchaseRankingUsers, IR
{
var embed = new EmbedBuilder()
.WithColor(Color.LightOrange)
.WithTitle(Format.Bold($"{IssoUtility.SmileStamp} †今月も貢げカス† {IssoUtility.SmileStamp}"))
.WithTitle($"{F.Smile} †今月も貢げカス† {F.Smile}".Custom("b"))
.WithDescription("月が変わったから課金額をリセットした")
.AddField("先月の課金額ランキング", GachaUtility.CreateRankingView(purchaseRankingUsers))
.AddField("先月の利益ランキング", SlotUtility.CreateRankingView(slotRewardRankingUsers))
Expand Down
4 changes: 2 additions & 2 deletions Events/Slot/SlotExecutePresenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,11 @@ private static string CreatePurchaseMessage(SlotExecuteResult result, User user,
{
if (result.IsWin)
{
sb.AppendLine(Format.Bold($"Y O U W I N ! ! x{result.ResultRate.Rate:F1}"));
sb.AppendLine($"Y O U W I N ! ! x{result.ResultRate.Rate:F1}".Custom("b"));
}
else
{
sb.AppendLine(Format.Bold($"Y O U L O S E"));
sb.AppendLine($"Y O U L O S E".Custom("b"));
}
}

Expand Down
4 changes: 1 addition & 3 deletions Events/Slot/SlotUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ public static string CreateRankingView(IReadOnlyList<User> rankingUsers)
{
var scoreText = Math.Min(999_999_999, user.MonthlySlotProfitPrice).ToString("N0");
var whiteSpace = Math.Max(0, 11 - scoreText.Length);
var line =
Format.Code($"#{order:D2} - {"".PadLeft(whiteSpace, ' ')}{scoreText}†カス†(税込)") + " " +
MentionUtils.MentionUser(user.DiscordId);
var line = $"#{order:D2} - {"".PadLeft(whiteSpace, ' ')}{scoreText}†カス†(税込)".Custom("c") + " " + MentionUtils.MentionUser(user.DiscordId);
embedBuilder.AppendLine(line);
order++;
}
Expand Down
7 changes: 2 additions & 5 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ migrate:
run:
dotnet run

.PHONY: docker-build
docker-build:
.PHONY: push
push:
docker build . -t $(app_name)

.PHONY: docker-push
docker-push:
docker push $(app_name)
Loading