Files
VORTEX-REC-LEAK/Services/DiscordBotService.cs
T
2026-07-23 18:21:43 -07:00

203 lines
7.1 KiB
C#

using DeluxeBackend;
using DeluxeBackend.Models;
using DeluxeBackend.Services;
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using Microsoft.AspNetCore.Mvc;
using System.Numerics;
using System.Reflection;
using static AGRoomRuntimeConfig;
using static DeluxeBackend.Controllers.Api.PlayerReportingController;
public class DiscordBotService : BackgroundService
{
private readonly DiscordSocketClient _client;
private readonly InteractionService _interactions;
private readonly IServiceProvider _services;
private readonly ILogger<DiscordBotService> _logger;
private readonly IConfiguration _config;
private readonly ILiteDbService _db;
private readonly INotificationService _ws;
public readonly ulong guild = 1495287391324340297;
public DiscordBotService(
ILogger<DiscordBotService> logger,
IConfiguration config,
DiscordSocketClient client,
InteractionService interactions,
IServiceProvider services,
ILiteDbService dv,
INotificationService notification
)
{
_logger = logger;
_config = config;
_client = client;
_interactions = interactions;
_services = services;
_db = dv;
_ws = notification;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_client.Log += LogAsync;
_interactions.Log += LogAsync;
_client.InteractionCreated += async interaction =>
{
var ctx = new SocketInteractionContext(_client, interaction);
await _interactions.ExecuteCommandAsync(ctx, _services);
};
_client.GuildMemberUpdated += HandleMemberUpdated;
_client.Ready += async () =>
{
await _interactions.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
await _interactions.RegisterCommandsToGuildAsync(guild);
_logger.LogInformation("Discord Slash Commands registered!");
};
var token = _config["DiscordToken"];
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();
await Task.Delay(-1, stoppingToken);
}
private async Task HandleMemberUpdated(Cacheable<SocketGuildUser, ulong> before, SocketGuildUser user)
{
if (user == null)
{
return;
}
Account account = _db.Accounts.FindOne(x => x.DiscordId == user.Id);
if (account == null)
{
return;
}
await _ws.SendToPlayer(account.Id, PushNotification.RefreshLogin, new Dictionary<string, object>());
}
private Task LogAsync(LogMessage msg)
{
_logger.LogInformation(msg.ToString());
return Task.CompletedTask;
}
public async Task<bool> HasUserBoostedGuild(ulong userId)
{
var targetGuild = _client.GetGuild(guild);
if (targetGuild == null)
{
_logger.LogWarning($"Guild {guild} not found or not cached.");
return false;
}
var user = targetGuild.GetUser(userId) ?? targetGuild.GetUser(userId) as SocketGuildUser;
if (user == null) return false;
if (user.Roles.Any(r => r.Id == 1503514258913103914))
{
return true;
}
return user.PremiumSince.HasValue;
}
public static readonly Dictionary<ulong, string> RoleMaping = new()
{
[1495587327593021490] = "moderator",
[1495580320525844581] = "developer",
[1495909230643908729] = "developer",
[1495580027453046804] = "developer",
[1501711512996282369] = "developer",
[1495580006712213674] = "developer",
[1503659138507341834] = "screenshare",
[1495635212531400875] = "booster",
[1508830399625695353] = "betastudio"
};
public async Task<List<string>> UserRoles(ulong userId)
{
var targetGuild = _client.GetGuild(guild);
if (targetGuild == null)
{
_logger.LogWarning($"Guild {guild} not found or not cached.");
return [];
}
var user = targetGuild.GetUser(userId);
if (user == null)
{
/*try
{
user = await _client.Rest.GetGuildUserAsync(guild, userId);
}
catch
{
return [];
}*/
}
if (user == null) return [];
return [.. user.Roles.Where(r => RoleMaping.ContainsKey(r.Id)).Select(r => RoleMaping[r.Id]).Distinct()];
}
public async Task<bool> HasRole(ulong userId, string role)
{
var roles = await UserRoles(userId);
return roles.Any(r => r.Equals(role, StringComparison.OrdinalIgnoreCase));
}
public async Task SendSelfReport(Account account, PGGOOHJPFPC hileType, string message)
{
var channel = _client.GetChannel(1506679765011267818) as IMessageChannel;
if (channel != null)
{
Embed embed = new EmbedBuilder().WithTitle($"@{account.Username} ({account.Id}) sent a hile report").WithDescription($"{hileType}: {message}").WithAuthor(account.Username, $"{ServerConfig.ImgApiUrl}{account.ImageName ?? "DefaultProfileImage"}?height=192&cropSquare=true").Build();
await channel.SendMessageAsync(null, false, embed, null, AllowedMentions.None);
}
}
public async Task SendSavedImg(Account account, SavedImage image)
{
var channel = _client.GetChannel(1507036679838634006) as IMessageChannel;
if (channel != null)
{
Embed embed = new EmbedBuilder().
WithAuthor(account.Username, $"{ServerConfig.ImgApiUrl}{account.ImageName ?? "DefaultProfileImage"}?height=192&cropSquare=true")
.WithTitle($"@{account.Username} ({account.Id}) uploaded a image")
.WithDescription($"RoomId: {image.RoomId}")
.WithImageUrl($"{ServerConfig.ImgApiUrl}{image.ImageName}")
.WithTimestamp(image.CreatedAt)
.Build();
var components = new ComponentBuilder()
.WithButton("Open Raw", null, ButtonStyle.Link, null, $"https://dev-cdn-kr.oldrecroom.com/img/{image.ImageName}")
.Build();
await channel.SendMessageAsync(null, false, embed, null, AllowedMentions.None, null, components);
}
var channel2 = _client.GetChannel(1509542402744909955) as IMessageChannel;
if (channel2 != null)
{
if (image.Accessibility == Enums.SavedImageAccessibility.Public && image.SavedImageType == Enums.SavedImageType.ShareCamera)
{
Embed embed2 = new EmbedBuilder().
WithAuthor(account.Username, $"{ServerConfig.ImgApiUrl}{account.ImageName ?? "DefaultProfileImage"}?height=192&cropSquare=true")
.WithTitle($"Image uploaded")
.WithImageUrl($"{ServerConfig.ImgApiUrl}{image.ImageName}")
.WithTimestamp(image.CreatedAt)
.Build();
await channel2.SendMessageAsync(null, false, embed2, null, AllowedMentions.None, null, null);
}
}
}
}