213 lines
8.2 KiB
C#
213 lines
8.2 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Threading.Tasks;
|
|
using ChaosBot.Discord.Modules.User;
|
|
using ChaosBot.Models;
|
|
using ChaosBot.Repositories;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Discord;
|
|
using Discord.Commands;
|
|
using Discord.WebSocket;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using NLog;
|
|
|
|
namespace ChaosBot.Discord.Services
|
|
{
|
|
public class CommandHandler
|
|
{
|
|
private readonly CommandService _commands;
|
|
private readonly DiscordSocketClient _client;
|
|
private readonly IServiceProvider _services;
|
|
private readonly ILogger _logger = Program.Logger;
|
|
|
|
public CommandHandler(IServiceProvider services)
|
|
{
|
|
try
|
|
{
|
|
_commands = services.GetRequiredService<CommandService>();
|
|
_client = services.GetRequiredService<DiscordSocketClient>();
|
|
_services = services;
|
|
|
|
_commands.CommandExecuted += CommandExecutedAsync;
|
|
|
|
_client.MessageReceived += MessageReceivedAsync;
|
|
|
|
_client.ReactionAdded += ReactionAddedAsync;
|
|
|
|
_client.ReactionRemoved += ReactionRemovedAsync;
|
|
|
|
_client.UserJoined += AnnounceJoinedUser;
|
|
|
|
_client.UserLeft += AnnounceLeftUser;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.Error($"CommandHandler.CommandHandler: Exception [{ex}] thrown, <[{ex.Message}]>.");
|
|
}
|
|
}
|
|
|
|
public async Task InitializeAsync()
|
|
{
|
|
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
|
|
}
|
|
|
|
public async Task MessageReceivedAsync(SocketMessage rawMessage)
|
|
{
|
|
try
|
|
{
|
|
if (!(rawMessage is SocketUserMessage message))
|
|
return;
|
|
|
|
if (message.Source != MessageSource.User)
|
|
return;
|
|
|
|
SocketCommandContext context = new SocketCommandContext(_client, message);
|
|
|
|
int argPos = 0;
|
|
|
|
string prefix = ConfigurationRepository.GetValue<string>("Discord:Prefix", context.Guild.Id, "!");
|
|
if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) ||
|
|
message.HasStringPrefix(prefix, ref argPos)))
|
|
{
|
|
ExperienceHandler.AddXp(context);
|
|
return;
|
|
}
|
|
|
|
if(Convert.ToBoolean(ConfigurationRepository.GetValue<string>("Experience:Commands", context.Guild.Id, "false")))
|
|
ExperienceHandler.AddXp(context);
|
|
|
|
await _commands.ExecuteAsync(context, argPos, _services);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.Error($"CommandHandler.MessageReceivedAsync: Exception [{ex}] thrown, <[{ex.Message}]>.");
|
|
}
|
|
}
|
|
|
|
public async Task ReactionAddedAsync(Cacheable<IUserMessage, ulong> cacheableMessage, ISocketMessageChannel socketMessageChannel, SocketReaction reaction)
|
|
{
|
|
RoleReactionHandler.HandleReactionAdded(cacheableMessage, socketMessageChannel, reaction);
|
|
}
|
|
|
|
public async Task ReactionRemovedAsync(Cacheable<IUserMessage, ulong> cacheableMessage, ISocketMessageChannel socketMessageChannel, SocketReaction reaction)
|
|
{
|
|
RoleReactionHandler.HandleReactionRemoved(cacheableMessage, socketMessageChannel, reaction);
|
|
}
|
|
|
|
public async Task AnnounceJoinedUser(SocketGuildUser user)
|
|
{
|
|
try
|
|
{
|
|
using (ChaosbotContext dbContext = new ChaosbotContext())
|
|
{
|
|
Experience newUser = new Experience();
|
|
newUser.Amount = 0;
|
|
newUser.DiscordGuildId = user.Guild.Id;
|
|
newUser.DiscordUserId = user.Id;
|
|
newUser.LastUpdated = DateTime.Now.Subtract(TimeSpan.FromMinutes(1));
|
|
newUser.Level = 1;
|
|
|
|
await dbContext.ExperiencePoints.Upsert(newUser)
|
|
.On(x => new {x.DiscordGuildId, x.DiscordUserId}).RunAsync();
|
|
}
|
|
|
|
await user.Guild.SystemChannel.SendMessageAsync($"{user.Username} has joined the server.");
|
|
|
|
|
|
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.Error(
|
|
$"{MethodBase.GetCurrentMethod().ReflectedType.FullName}: Exception [{ex}] thrown, <[{ex.Message}]>.");
|
|
}
|
|
}
|
|
|
|
public async Task AnnounceLeftUser(SocketGuildUser user)
|
|
{
|
|
try
|
|
{
|
|
using (ChaosbotContext dbContext = new ChaosbotContext())
|
|
{
|
|
IQueryable<Experience> ctxUser = dbContext.ExperiencePoints;
|
|
IQueryable<Experience> usrXp = ctxUser
|
|
.Where(p => p.DiscordGuildId.Equals(user.Guild.Id))
|
|
.Where(p => p.DiscordUserId.Equals(user.Id));
|
|
|
|
if (usrXp.Any())
|
|
{
|
|
dbContext.ExperiencePoints.Remove(usrXp.First());
|
|
await dbContext.SaveChangesAsync();
|
|
}
|
|
|
|
IQueryable<LodestoneCharacter> ctxUserLS = dbContext.LodestoneCharacter;
|
|
IQueryable<LodestoneCharacter> userChar = ctxUserLS
|
|
.Where(p => p.DiscordGuildId.Equals(user.Guild.Id))
|
|
.Where(p => p.DiscordUserId.Equals(user.Id));
|
|
|
|
if (userChar.Any())
|
|
{
|
|
dbContext.LodestoneCharacter.Remove(userChar.First());
|
|
await dbContext.SaveChangesAsync();
|
|
}
|
|
|
|
IQueryable<Raffle> ctxRaffles = dbContext.Raffles;
|
|
|
|
IQueryable<Raffle> ctxRaffleDetail = ctxRaffles
|
|
.Where(p => p.DiscordGuildId.Equals(user.Guild.Id))
|
|
.Where(p => p.DiscordUserId.Equals(user.Id));
|
|
|
|
int cur = ctxRaffleDetail.Count();
|
|
|
|
if (cur != 0)
|
|
{
|
|
dbContext.Raffles.RemoveRange(ctxRaffleDetail);
|
|
await dbContext.SaveChangesAsync();
|
|
}
|
|
|
|
Point usrPoint = new Point();
|
|
|
|
usrPoint.Amount = 0;
|
|
usrPoint.DiscordGuildId = user.Guild.Id;
|
|
usrPoint.DiscordUserId = user.Id;
|
|
|
|
await dbContext.Points.Upsert(usrPoint)
|
|
.On(x => new { x.DiscordGuildId, x.DiscordUserId}).RunAsync();
|
|
}
|
|
|
|
await user.Guild.SystemChannel.SendMessageAsync($"{user.Username} has left the server.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.Error(
|
|
$"{MethodBase.GetCurrentMethod().ReflectedType.FullName}: Exception [{ex}] thrown, <[{ex.Message}]>.");
|
|
}
|
|
}
|
|
|
|
public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandContext context, IResult result)
|
|
{
|
|
try
|
|
{
|
|
if (!command.IsSpecified)
|
|
{
|
|
_logger.Error($"Command failed to execute for [{context.User.Username}] <-> [{result.ErrorReason}]!");
|
|
return;
|
|
}
|
|
|
|
if (result.IsSuccess)
|
|
{
|
|
_logger.Info($"Command [{command.Value.Name}] executed for -> [{context.User.Username}]");
|
|
return;
|
|
}
|
|
|
|
_logger.Warn($"{context.User.Username} attempted to access {command.Value.Name} and was denied -> [{result}]");
|
|
await context.Channel.SendMessageAsync($"Sorry, {context.User.Username}, that command won't work for you.!");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.Error($"CommandHandler.CommandExecutedAsync: Exception [{ex}] thrown, <[{ex.Message}]>.");
|
|
}
|
|
}
|
|
}
|
|
} |