This repository has been archived on 2024-06-23. You can view files and clone it, but cannot push or open issues or pull requests.
OctobotStealth/Boyfriend.cs

179 lines
7.1 KiB
C#
Raw Normal View History

2022-05-14 16:12:24 +03:00
using System.Text;
using System.Timers;
using Boyfriend.Data;
2021-12-15 09:19:14 +03:00
using Discord;
using Discord.Rest;
2021-12-07 15:52:37 +03:00
using Discord.WebSocket;
using Timer = System.Timers.Timer;
2021-12-07 15:52:37 +03:00
namespace Boyfriend;
2021-12-15 09:19:14 +03:00
public static class Boyfriend {
2022-05-14 16:12:24 +03:00
public static readonly StringBuilder StringBuilder = new();
2021-12-07 15:52:37 +03:00
2021-12-15 09:19:14 +03:00
private static readonly DiscordSocketConfig Config = new() {
MessageCacheSize = 250,
GatewayIntents
= (GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent | GatewayIntents.GuildMembers)
& ~GatewayIntents.GuildInvites,
2022-08-29 19:24:38 +03:00
AlwaysDownloadUsers = true,
AlwaysResolveStickers = false,
AlwaysDownloadDefaultStickers = false,
LargeThreshold = 500
2021-12-15 09:19:14 +03:00
};
2021-12-07 15:52:37 +03:00
private static DateTimeOffset _nextSongAt = DateTimeOffset.MinValue;
private static uint _nextSongIndex;
private static readonly Tuple<Game, TimeSpan>[] ActivityList = {
Tuple.Create(
new Game("Masayoshi Minoshima (ft. nomico) - Bad Apple!!", ActivityType.Listening),
2022-12-21 09:52:09 +03:00
new TimeSpan(0, 3, 40)),
Tuple.Create(new Game("Xi - Blue Zenith", ActivityType.Listening), new TimeSpan(0, 4, 16)),
Tuple.Create(new Game("Kurokotei - Scattered Faith", ActivityType.Listening), new TimeSpan(0, 8, 21)),
Tuple.Create(new Game("Splatoon 3 - Candy-Coated Rocks", ActivityType.Listening), new TimeSpan(0, 2, 39)),
Tuple.Create(new Game("RetroSpecter - Genocide", ActivityType.Listening), new TimeSpan(0, 5, 52)),
2022-12-21 09:52:09 +03:00
Tuple.Create(new Game("beatMARIO - Night of Knights", ActivityType.Listening), new TimeSpan(0, 4, 10))
};
2021-12-15 09:19:14 +03:00
public static readonly DiscordSocketClient Client = new(Config);
2022-05-14 16:12:24 +03:00
private static readonly List<Task> GuildTickTasks = new();
2021-12-07 15:52:37 +03:00
public static void Main() {
InitAsync().GetAwaiter().GetResult();
}
private static async Task InitAsync() {
2021-12-15 09:19:14 +03:00
var token = (await File.ReadAllTextAsync("token.txt")).Trim();
Client.Log += Log;
2022-02-02 16:14:26 +03:00
2021-12-15 09:19:14 +03:00
await Client.LoginAsync(TokenType.Bot, token);
await Client.StartAsync();
2022-10-18 20:55:16 +03:00
EventHandler.InitEvents();
2021-12-15 09:19:14 +03:00
var timer = new Timer();
timer.Interval = 1000;
timer.AutoReset = true;
timer.Elapsed += TickAllGuildsAsync;
if (ActivityList.Length is 0) timer.Dispose(); // CodeQL moment
timer.Start();
while (ActivityList.Length > 0)
if (DateTimeOffset.Now >= _nextSongAt) {
var nextSong = ActivityList[_nextSongIndex];
await Client.SetActivityAsync(nextSong.Item1);
_nextSongAt = DateTimeOffset.Now.Add(nextSong.Item2);
_nextSongIndex++;
if (_nextSongIndex >= ActivityList.Length) _nextSongIndex = 0;
}
2021-12-15 09:19:14 +03:00
}
2021-12-07 15:52:37 +03:00
private static async void TickAllGuildsAsync(object? sender, ElapsedEventArgs e) {
foreach (var guild in Client.Guilds) GuildTickTasks.Add(TickGuildAsync(guild));
try { Task.WaitAll(GuildTickTasks.ToArray()); } catch (AggregateException ex) {
foreach (var exc in ex.InnerExceptions)
await Log(
new LogMessage(
LogSeverity.Error, nameof(Boyfriend),
"Exception while ticking guilds", exc));
}
GuildTickTasks.Clear();
}
public static Task Log(LogMessage msg) {
switch (msg.Severity) {
case LogSeverity.Critical:
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.Error.WriteLine(msg.ToString());
break;
case LogSeverity.Error:
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine(msg.ToString());
break;
case LogSeverity.Warning:
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(msg.ToString());
break;
case LogSeverity.Info:
Console.WriteLine(msg.ToString());
break;
case LogSeverity.Verbose:
case LogSeverity.Debug:
default: return Task.CompletedTask;
}
2022-02-02 16:14:26 +03:00
Console.ResetColor();
2021-12-15 09:19:14 +03:00
return Task.CompletedTask;
}
private static async Task TickGuildAsync(SocketGuild guild) {
var data = GuildData.Get(guild);
var config = data.Preferences;
var saveData = false;
_ = int.TryParse(config["EventEarlyNotificationOffset"], out var offset);
foreach (var schEvent in guild.Events)
if (schEvent.Status is GuildScheduledEventStatus.Scheduled
&& config["AutoStartEvents"] is "true"
&& DateTimeOffset
.Now
>= schEvent.StartTime) await schEvent.StartAsync();
else if (!data.EarlyNotifications.Contains(schEvent.Id)
&& DateTimeOffset.Now >= schEvent.StartTime.Subtract(new TimeSpan(0, offset, 0))) {
data.EarlyNotifications.Add(schEvent.Id);
var receivers = config["EventStartedReceivers"];
var role = guild.GetRole(ulong.Parse(config["EventNotificationRole"]));
var mentions = StringBuilder;
if (receivers.Contains("role") && role is not null) mentions.Append($"{role.Mention} ");
if (receivers.Contains("users") || receivers.Contains("interested"))
mentions = (await schEvent.GetUsersAsync(15))
.Where(user => role is null || !((RestGuildUser)user).RoleIds.Contains(role.Id))
.Aggregate(mentions, (current, user) => current.Append($"{user.Mention} "));
await Utils.GetEventNotificationChannel(guild)?.SendMessageAsync(
string.Format(
Messages.EventEarlyNotification,
mentions,
Utils.Wrap(schEvent.Name),
schEvent.StartTime.ToUnixTimeSeconds().ToString()))!;
mentions.Clear();
}
foreach (var mData in data.MemberData.Values) {
if (DateTimeOffset.Now >= mData.BannedUntil) _ = guild.RemoveBanAsync(mData.Id);
if (!mData.IsInGuild) continue;
if (DateTimeOffset.Now >= mData.MutedUntil) {
await Utils.UnmuteMemberAsync(
data, Client.CurrentUser.ToString(), guild.GetUser(mData.Id),
Messages.PunishmentExpired);
saveData = true;
}
for (var i = mData.Reminders.Count - 1; i >= 0; i--) {
var reminder = mData.Reminders[i];
if (DateTimeOffset.Now < reminder.RemindAt) continue;
var channel = guild.GetTextChannel(reminder.ReminderChannel);
if (channel is null) {
await Utils.SendDirectMessage(Client.GetUser(mData.Id), reminder.ReminderText);
continue;
}
await channel.SendMessageAsync($"<@{mData.Id}> {Utils.Wrap(reminder.ReminderText)}");
mData.Reminders.RemoveAt(i);
saveData = true;
}
}
2022-05-14 16:12:24 +03:00
if (saveData) data.Save(true).Wait();
2022-05-14 16:12:24 +03:00
}
}