\CayciV2Bot\CayciV2Bot\Core\CommandsModule.cs

Return Back
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Newtonsoft.Json;
using CayciV2Bot.Models;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System.IO;
using Discord.Interactions;
using RunCommandsMode = Discord.Commands;
using RequireCommandsContextAttribute = Discord.Commands.RequireContextAttribute;
using CommandsContextType = Discord.Commands.ContextType;

namespace CayciV2Bot.Core
{
public class CommandsModule : ModuleBase
{
private DiscordSocketClient _client;
private IGuild Guild { get { return Context.Guild; } }
private IMessageChannel Channel { get { return Context.Channel; } }
private IGuildUser User { get { return Context.User as IGuildUser; } }
private IUserMessage Message { get { return Context.Message; } }
private readonly IConfiguration _configuration;
private readonly FunctionsModule _functionsModule;

public CommandsModule(DiscordSocketClient discordSocketClient)
{
_configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
_client = discordSocketClient;
_functionsModule = new FunctionsModule();
}

[Command("help")]
public async Task Help()
{
await Channel.TriggerTypingAsync();
await Channel.SendMessageAsync("CRYALP.com was here", true);
}

[RequireCommandsContext(CommandsContextType.Guild)]
[Command("sendmsg", RunMode = RunCommandsMode.RunMode.Async)]
public async Task SendMessageToMutualChannel([Remainder] string commandStr)
{
try
{
if (Context != null)
{
_client = Context.Client as DiscordSocketClient;
}

var message = Regex.Match(commandStr, "(?i)--message \"(.+?)\"").Groups[1].Value;

var guildName = "";
if (commandStr.Contains("--guild "))
{
guildName = Regex.Match(commandStr, "(?i)--guild \"(.+?)\"").Groups[1].Value;
}
else
{
guildName = _configuration.GetValue<string>("Cayci:MutualGuild");
}
var mutualGuild = _client.CurrentUser.MutualGuilds.FirstOrDefault(g => g.Name == guildName);

var channelName = "";
if (commandStr.Contains("--channel "))
{
channelName = Regex.Match(commandStr, "(?i)--channel \"(.+?)\"").Groups[1].Value;
}
else
{
channelName = _configuration.GetValue<string>("Cayci:MutualChannel");
}
var mutualChannel = mutualGuild.Channels.FirstOrDefault(c => c.Name == channelName);
var readyChannel = _client.GetChannel(mutualChannel.Id) as IMessageChannel;

if (commandStr.Contains("--username "))
{
var userName = Regex.Match(commandStr, "(?i)--username \"(.+?)\"").Groups[1].Value;
await mutualGuild.DownloadUsersAsync();
var userMentionSplit = userName.Split("#");
var userMention = mutualGuild.Users.FirstOrDefault(u => u.Username == userMentionSplit[0] && u.Discriminator == userMentionSplit[1]);
await readyChannel.SendMessageAsync(userMention.Mention + " " + message);
}
else
{
await readyChannel.SendMessageAsync(message);
}
}
catch (Exception ex)
{
_functionsModule.LogPrinter(ex.Message);
}
}

[Command("albionplayercontrol", RunMode = RunCommandsMode.RunMode.Async)]
public async Task AlbionPlayerControl([Remainder] string playerName)
{
try
{
if (!_functionsModule.Log(Guild, Channel, User, null, playerName))
{
throw new Exception("Logging error while logging operation to database");
}

using var _dbContext = new Entities.Models();
var albionPlayer = _dbContext.AlbionPlayer.FirstOrDefault(ap => ap.Name == playerName);
if (albionPlayer == null)
{
albionPlayer = new AlbionPlayer
{
AlbionId = await new Controllers.AlbionController().PlayerSearch(playerName),
Name = playerName,
CreationDate = DateTime.Now,
};
_dbContext.AlbionPlayer.Add(albionPlayer);
_dbContext.SaveChanges();
}

var mutualGuild = _dbContext.DiscordGuild.FirstOrDefault(g => g.DiscordId == Guild.Id);

var mutualChannel = _dbContext.DiscordChannel.FirstOrDefault(c => c.DiscordId == Channel.Id);

var albionPlayerDiscordGuild = _dbContext.AlbionPlayerDiscordGuild.FirstOrDefault(
apdg => apdg.AlbionPlayerId == albionPlayer.Id
&& apdg.DiscordGuildId == mutualGuild.Id
&& apdg.DiscordChannelId == mutualChannel.Id
);
if (albionPlayerDiscordGuild == null)
{
albionPlayerDiscordGuild = new AlbionPlayerDiscordGuild
{
AlbionPlayerId = albionPlayer.Id,
DiscordGuildId = mutualGuild.Id,
DiscordChannelId = mutualChannel.Id,
IsActive = true
};
_dbContext.AlbionPlayerDiscordGuild.Add(albionPlayerDiscordGuild);
_dbContext.SaveChanges();
}
else
{
albionPlayerDiscordGuild.IsActive = true;
_dbContext.AlbionPlayerDiscordGuild.Update(albionPlayerDiscordGuild);
_dbContext.SaveChanges();
}

await Channel.SendMessageAsync("Player added to database control list.", false);
}
catch (Exception ex)
{
await Channel.SendMessageAsync($"Search error while searching item: {playerName}", false);
_functionsModule.LogPrinter(ex.Message);
}
}

[RequireCommandsContext(CommandsContextType.Guild)]
[Command("albionplayerkillcheck", RunMode = RunCommandsMode.RunMode.Async)]
public async Task AlbionPlayerKillCheck([Remainder] string playerName)
{
try
{
using var _dbContext = new Entities.Models();
var albionPlayerDiscordGuild = _dbContext.AlbionPlayerDiscordGuild.FirstOrDefault(apdg => apdg.AlbionPlayer.Name == playerName);
if (albionPlayerDiscordGuild == null)
{
throw new Exception("Logging error while logging operation to database");
}

if (Context != null)
{
_client = Context.Client as DiscordSocketClient;
}
var discordChannel = _dbContext.DiscordChannel.FirstOrDefault(dc => dc.Id == albionPlayerDiscordGuild.DiscordChannelId);
var readyChannel = _client.GetChannel(discordChannel.DiscordId) as IMessageChannel;

var response = await new Controllers.AlbionController().PlayerCheck(playerName, "kills");
var playerKillList = JArray.Parse(response);
if (playerKillList.Count == 0)
{
await Channel.SendMessageAsync($"__{playerName.ToUpper()}__ not found on killboard database", false);
return;
}

foreach (var playerKill in playerKillList)
{
var eventId = playerKill["EventId"].ToString();
var imagePath = Environment.CurrentDirectory + "/resources/albion/events/kills/KILL_EVENT_" + eventId + ".png";
if (File.Exists(imagePath))
{
continue;
}
await readyChannel.TriggerTypingAsync();

var killerVictimInventoryImage = System.Drawing.Image.FromStream(await new Controllers.AlbionController().KillerVictimInventoryBuilder(playerKill));
killerVictimInventoryImage.Save(imagePath, System.Drawing.Imaging.ImageFormat.Png);

var imageFile = Path.GetFileName(imagePath);
var emb = new EmbedBuilder()
.WithImageUrl($"attachment://{imageFile}")
.WithTitle($"__{playerKill["Killer"]["Name"]}__ has killed __{playerKill["Victim"]["Name"]}__ \r\n{playerKill["TimeStamp"]}")
.WithUrl("https://albiononline.com/en/killboard/kill/" + eventId)
.Build();

await readyChannel.SendFileAsync(imagePath, null, false, emb);
}
}
catch (Exception ex)
{
_functionsModule.LogPrinter(ex.Message);
await Channel.SendMessageAsync($"Search error while searching __{playerName.ToUpper()}__ on killboard database", false);
}
}

[Command("albionplayerdeathcheck", RunMode = RunCommandsMode.RunMode.Async)]
public async Task AlbionPlayerDeathCheck([Remainder] string playerName)
{
try
{
using var _dbContext = new Entities.Models();
var albionPlayerDiscordGuild = _dbContext.AlbionPlayerDiscordGuild.FirstOrDefault(apdg => apdg.AlbionPlayer.Name == playerName);
if (albionPlayerDiscordGuild == null)
{
throw new Exception("Logging error while logging operation to database");
}

if (Context != null)
{
_client = Context.Client as DiscordSocketClient;
}
var discordChannel = _dbContext.DiscordChannel.FirstOrDefault(dc => dc.Id == albionPlayerDiscordGuild.DiscordChannelId);
var readyChannel = _client.GetChannel(discordChannel.DiscordId) as IMessageChannel;

var response = await new Controllers.AlbionController().PlayerCheck(playerName, "deaths");
var playerDeathList = JArray.Parse(response);
if (playerDeathList.Count == 0)
{
await Channel.SendMessageAsync($"__{playerName.ToUpper()}__ not found on killboard database", false);
return;
}

foreach (var playerDeath in playerDeathList)
{
var eventId = playerDeath["EventId"].ToString();
var imagePath = Environment.CurrentDirectory + "/resources/albion/events/deaths/DEATH_EVENT_" + eventId + ".png";
if (File.Exists(imagePath))
{
continue;
}
await readyChannel.TriggerTypingAsync();

var killerVictimInventoryImage = System.Drawing.Image.FromStream(await new Controllers.AlbionController().KillerVictimInventoryBuilder(playerDeath));
killerVictimInventoryImage.Save(imagePath, System.Drawing.Imaging.ImageFormat.Png);

var imageFile = Path.GetFileName(imagePath);
var embebMessage = new EmbedBuilder()
.WithImageUrl($"attachment://{imageFile}")
.WithTitle($"__{playerDeath["Killer"]["Name"]}__ has killed __{playerDeath["Victim"]["Name"]}__ \r\n{playerDeath["TimeStamp"]}")
.WithUrl("https://albiononline.com/en/killboard/kill/" + eventId)
.Build();

await readyChannel.SendFileAsync(imagePath, null, false, embebMessage);
}
}
catch (Exception ex)
{
_functionsModule.LogPrinter(ex.Message);
await Channel.SendMessageAsync($"Search error while searching __{playerName.ToUpper()}__ on killboard database", false);
}
}

[Command("albionmarket", RunMode = RunCommandsMode.RunMode.Async)]
public async Task AlbionMarket([Remainder] string itemName)
{
try
{
await Channel.TriggerTypingAsync();

var response = await new Controllers.AlbionController().SearchMarket(itemName);
var albionItemList = JsonConvert.DeserializeObject<List<AlbionItem>>(response);
if (albionItemList.Count == 0)
{
await Channel.SendMessageAsync($"__{itemName.ToUpper()}__ not found on market database", false);
return;
}

var embed = new EmbedBuilder();
var locationFieldValue = "";
var sellPriceMinFieldValue = "";
var updateFieldValue = "";
foreach (var albionItem in albionItemList)
{
if (albionItem.SellPriceMin > 0)
{
locationFieldValue += $"{albionItem.City} {albionItem.Quality}\n";
sellPriceMinFieldValue += string.Format("{0:N0}", albionItem.SellPriceMin) + "\n";
TimeSpan span = DateTime.Now - albionItem.SellPriceMinDate;
updateFieldValue += $"{(span.Days * 24 * 60) + (span.Hours * 60) + span.Minutes} mins, {span.Seconds} secs\n";
}
}

embed
.WithTitle(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(itemName.ToLower()))
.WithDescription(albionItemList[0].ItemId)
.WithColor(Color.Gold)
.WithThumbnailUrl(albionItemList[0].PhotoURL)
.AddField("Location", locationFieldValue, true)
.AddField("Price", sellPriceMinFieldValue, true)
.AddField("Update", updateFieldValue, true)
.WithFooter(footer => footer.Text = "cryalp.com")
.WithCurrentTimestamp();

if (!_functionsModule.Log(Guild, Channel, User, null, itemName))
{
throw new Exception("Logging error while logging operation to database");
}

await Channel.SendMessageAsync("", false, embed.Build());
}
catch (Exception ex)
{
await Channel.SendMessageAsync($"Search error while searching item: {itemName}", false);
_functionsModule.LogPrinter(ex.Message);
}
}

[Command("hello")]
public async Task Hello()
{
await Channel.TriggerTypingAsync();
await Channel.SendMessageAsync("CRYALP.com was here", true);
}

[MessageCommand("best-global-message-command")]
public async Task BestMessageCommand([Remainder] IMessage msg)
{
await Channel.TriggerTypingAsync();
await Channel.SendMessageAsync("CRYALP.com was here with message command" + msg.Content, true);
}

[UserCommand("best-global-user-command")]
public async Task BestUserCommand([Remainder] IUser user)
{
await Channel.TriggerTypingAsync();
await Channel.SendMessageAsync("CRYALP.com was here with user command" + user.Username, true);
}

[Command("playgame")]
public async Task PlayGame([Remainder] string game = "")
{
await Channel.TriggerTypingAsync();
await _client.SetGameAsync(game, "https://cryalp.com", ActivityType.Playing);
await Channel.SendMessageAsync("Woof, woof!", true);
}

[Command("fart")]
public async Task Fart()
{
await Channel.SendManifestResourceAsync(GetType().Assembly, "/resources/audio/fart.wav");
}

[Command("parse")]
public async Task Parse([Remainder] string text = "")
{
await RecognizeName(text);
}

private async Task RecognizeName(string content)
{
if (Regex.IsMatch(content, @"\bÇaycı\b"))
{
await Channel.TriggerTypingAsync();
await Message.AddReactionAsync(new Emoji("🐶"));
await Message.AddReactionAsync(new Emoji("❤️"));
}
}
}
}