\CayciV2Bot\CayciV2Bot\Core\BotModule.cs
Return Back
using System;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
namespace CayciV2Bot.Core
{
public class BotModule : IHostedService, IDisposable
{
private readonly IConfiguration _configuration;
private readonly DiscordSocketClient _client;
private readonly CommandService _commandService;
private readonly IServiceProvider _services;
private readonly SettingsModule _settings;
private readonly ILogger<BotModule> _logger;
private readonly CommandsModule _commandsModule;
private readonly FunctionsModule _functionsModule;
public BotModule(CommandService commandService, IServiceProvider services, SettingsModule settings, ILogger<BotModule> logger, IConfiguration configuration)
{
_configuration = configuration;
_client = new DiscordSocketClient(new DiscordSocketConfig()
{
GatewayIntents = GatewayIntents.Guilds | GatewayIntents.GuildMessages | GatewayIntents.GuildMessageTyping | GatewayIntents.GuildMessageReactions
| GatewayIntents.GuildMembers | GatewayIntents.MessageContent
| GatewayIntents.DirectMessages | GatewayIntents.DirectMessageTyping | GatewayIntents.DirectMessageReactions
| GatewayIntents.GuildVoiceStates,
AlwaysDownloadUsers = true,
LogLevel = LogSeverity.Verbose
});
_commandService = commandService;
_services = services;
_settings = settings;
_logger = logger;
_logger.LogInformation("Started CayciV2Bot");
_commandsModule = new CommandsModule(_client);
_functionsModule = new FunctionsModule();
}
public async Task RunAsync()
{
_client.Log += Log;
_client.Ready += Ready;
_client.MessageReceived += MessageReceived;
_commandService.Log += Log;
_commandService.CommandExecuted += CommandExecuted;
_client.SlashCommandExecuted += SlashCommandExecuted;
_client.MessageCommandExecuted += MessageCommandExecuted;
_client.UserCommandExecuted += UserCommandExecuted;
var assembly = GetType().Assembly;
await _commandService.AddModulesAsync(assembly, _services);
await _client.LoginAsync(TokenType.Bot, _settings.Token);
await _client.StartAsync();
}
private async Task CommandExecuted(Optional<CommandInfo> command, ICommandContext context, IResult result)
{
if (!command.IsSpecified)
{
await context.Channel.SendMessageAsync("Woofa!", true);
await context.Message.AddReactionAsync(new Emoji("🐶"));
//return;
}
if (!result.IsSuccess)
{
await Log(new LogMessage(LogSeverity.Error, nameof(CommandExecuted), $"Error: {result.ErrorReason}"));
return;
}
if (command.Value.Name != "parse")
{
// react to message
await context.Message.AddReactionAsync(new Emoji("🐶"));
}
}
private async Task SlashCommandExecuted(SocketSlashCommand command)
{
await command.RespondAsync($"You executed {command.Data.Name}");
}
private async Task MessageCommandExecuted(SocketMessageCommand command)
{
await command.RespondAsync($"You executed {command.Data.Name}");
}
private async Task UserCommandExecuted(SocketUserCommand command)
{
//var context = new SocketCommandContext(_client, message);
//await _commandService.ExecuteAsync(context, command.Data.Name, _services);
await command.RespondAsync($"You executed {command.Data.Name}");
}
private async Task BuildGlobalCommands()
{
var globalCommand = new SlashCommandBuilder();
globalCommand.WithName("best-global-command");
globalCommand.WithDescription("This is my first global slash command");
var globalMessageCommand = new MessageCommandBuilder();
globalMessageCommand.WithName("best-global-message-command");
var globalUserCommand = new UserCommandBuilder();
globalUserCommand.WithName("best-global-user-command");
await _client.BulkOverwriteGlobalApplicationCommandsAsync(new ApplicationCommandProperties[]
{
globalCommand.Build(),
globalUserCommand.Build(),
globalMessageCommand.Build()
});
}
private async void ControlKillDeath()
{
while (true)
{
try
{
Thread.Sleep(300 * 1000);
using var _dbContext = new Entities.Models();
foreach (var albionPlayerDiscordGuild in _dbContext.AlbionPlayerDiscordGuild.ToList())
{
var albionPlayer = _dbContext.AlbionPlayer.FirstOrDefault(ap => ap.Id == albionPlayerDiscordGuild.AlbionPlayerId);
await _commandsModule.AlbionPlayerKillCheck(albionPlayer.Name);
await _commandsModule.AlbionPlayerDeathCheck(albionPlayer.Name);
}
}
catch (Exception ex)
{
{
_functionsModule.LogPrinter(ex.Message);
}
}
}
}
private async void CallBack()
{
const int callBackMessageMinute = 1;
var lastTime = DateTime.Now.AddMinutes(-callBackMessageMinute);
while (true)
{
try
{
Thread.Sleep(30 * 1000);
using var httpClient = new HttpClient();
var uriString = "https://localhost/Home/Callback";
var uriBuilder = new UriBuilder(uriString);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
uriBuilder.Query = query.ToString();
uriString = uriBuilder.ToString();
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("User-Agent", "CRYALP.com");
var httpResponse = await httpClient.GetAsync(uriString);
httpResponse.EnsureSuccessStatusCode();
var callBackResponse = await httpResponse.Content.ReadAsStringAsync();
if (DateTime.Now >= lastTime.AddMinutes(callBackMessageMinute))
{
var asd = $"--message \"CallBack Response: {callBackResponse}\"";
await _commandsModule.SendMessageToMutualChannel(asd);
lastTime = DateTime.Now;
}
}
catch (Exception ex)
{
_functionsModule.LogPrinter(ex.Message);
}
}
}
private async Task Ready()
{
try
{
await BuildGlobalCommands();
await _client.SetStatusAsync(UserStatus.DoNotDisturb);
ConfigModule.Game = "cryalp.com | çaycı help";
await _client.SetGameAsync(ConfigModule.Game, "https://cryalp.com", ActivityType.Playing);
await _commandsModule.SendMessageToMutualChannel($"--message \"I'm Back at {DateTime.Now}\"");
var callBackThread = new Thread(new ThreadStart(CallBack));
callBackThread.Start();
var controlKillDeathThread = new Thread(new ThreadStart(ControlKillDeath));
controlKillDeathThread.Start();
}
catch (Exception ex)
{
_functionsModule.LogPrinter(ex.Message);
}
}
private async Task MessageReceived(SocketMessage message)
{
try
{
if (message is not SocketUserMessage userMessage || message.Author.IsBot)
{
return;
}
var match = Regex.Match(userMessage.Content, "^" + _configuration.GetValue<string>("Cayci:Prefix") + "?\\s+", RegexOptions.IgnoreCase);
int? pos = null;
if (match.Success)
{
pos = match.Length;
}
else
{
var dmChannel = await userMessage.Author.CreateDMChannelAsync();
if (userMessage.Channel.Id == dmChannel.Id)
{
pos = 0;
}
}
var context = new SocketCommandContext(_client, userMessage);
if (pos.HasValue)
{
_functionsModule.LogPrinter(userMessage.Content[pos.Value..]);
await _commandService.ExecuteAsync(context, userMessage.Content[pos.Value..], _services);
}
else
{
await _commandService.ExecuteAsync(context, "parse " + userMessage.Content, _services);
}
}
catch (Exception ex)
{
var reply = await message.Channel.SendMessageAsync($"Error: {ex.Message}", false);
await reply.AddReactionAsync(new Emoji("😱"));
_functionsModule.LogPrinter(ex.Message);
}
}
private Task Log(LogMessage message)
{
_logger.Log(GetLogLevel(message.Severity), message.Exception, message.Source + ":" + message.Message);
_functionsModule.LogPrinter($"Cayci log: {message.Message}");
return Task.CompletedTask;
}
private static LogLevel GetLogLevel(LogSeverity severity)
{
return severity switch
{
LogSeverity.Critical => LogLevel.Critical,
LogSeverity.Error => LogLevel.Error,
LogSeverity.Warning => LogLevel.Warning,
LogSeverity.Info => LogLevel.Information,
LogSeverity.Verbose => LogLevel.Trace,
LogSeverity.Debug => LogLevel.Debug,
_ => throw new NotImplementedException(nameof(severity) + "=" + severity.ToString()),
};
}
public async Task StopAsync()
{
await _commandsModule.SendMessageToMutualChannel($"--message \"I'm Stopping at {DateTime.Now}\"");
await _client.SetGameAsync(null);
await _client.SetStatusAsync(UserStatus.Offline);
_client.Log -= Log;
_client.Ready -= Ready;
_client.MessageReceived -= MessageReceived;
_commandService.Log -= Log;
_commandService.CommandExecuted -= CommandExecuted;
await _client.StopAsync();
}
async Task IHostedService.StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Running Cayci as hosted service");
await RunAsync();
}
async Task IHostedService.StopAsync(CancellationToken cancellationToken)
{
await StopAsync();
_logger.LogInformation("Stopping Cayci as hosted service");
}
public void Dispose()
{
_client.Dispose();
}
}
}
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
namespace CayciV2Bot.Core
{
public class BotModule : IHostedService, IDisposable
{
private readonly IConfiguration _configuration;
private readonly DiscordSocketClient _client;
private readonly CommandService _commandService;
private readonly IServiceProvider _services;
private readonly SettingsModule _settings;
private readonly ILogger<BotModule> _logger;
private readonly CommandsModule _commandsModule;
private readonly FunctionsModule _functionsModule;
public BotModule(CommandService commandService, IServiceProvider services, SettingsModule settings, ILogger<BotModule> logger, IConfiguration configuration)
{
_configuration = configuration;
_client = new DiscordSocketClient(new DiscordSocketConfig()
{
GatewayIntents = GatewayIntents.Guilds | GatewayIntents.GuildMessages | GatewayIntents.GuildMessageTyping | GatewayIntents.GuildMessageReactions
| GatewayIntents.GuildMembers | GatewayIntents.MessageContent
| GatewayIntents.DirectMessages | GatewayIntents.DirectMessageTyping | GatewayIntents.DirectMessageReactions
| GatewayIntents.GuildVoiceStates,
AlwaysDownloadUsers = true,
LogLevel = LogSeverity.Verbose
});
_commandService = commandService;
_services = services;
_settings = settings;
_logger = logger;
_logger.LogInformation("Started CayciV2Bot");
_commandsModule = new CommandsModule(_client);
_functionsModule = new FunctionsModule();
}
public async Task RunAsync()
{
_client.Log += Log;
_client.Ready += Ready;
_client.MessageReceived += MessageReceived;
_commandService.Log += Log;
_commandService.CommandExecuted += CommandExecuted;
_client.SlashCommandExecuted += SlashCommandExecuted;
_client.MessageCommandExecuted += MessageCommandExecuted;
_client.UserCommandExecuted += UserCommandExecuted;
var assembly = GetType().Assembly;
await _commandService.AddModulesAsync(assembly, _services);
await _client.LoginAsync(TokenType.Bot, _settings.Token);
await _client.StartAsync();
}
private async Task CommandExecuted(Optional<CommandInfo> command, ICommandContext context, IResult result)
{
if (!command.IsSpecified)
{
await context.Channel.SendMessageAsync("Woofa!", true);
await context.Message.AddReactionAsync(new Emoji("🐶"));
//return;
}
if (!result.IsSuccess)
{
await Log(new LogMessage(LogSeverity.Error, nameof(CommandExecuted), $"Error: {result.ErrorReason}"));
return;
}
if (command.Value.Name != "parse")
{
// react to message
await context.Message.AddReactionAsync(new Emoji("🐶"));
}
}
private async Task SlashCommandExecuted(SocketSlashCommand command)
{
await command.RespondAsync($"You executed {command.Data.Name}");
}
private async Task MessageCommandExecuted(SocketMessageCommand command)
{
await command.RespondAsync($"You executed {command.Data.Name}");
}
private async Task UserCommandExecuted(SocketUserCommand command)
{
//var context = new SocketCommandContext(_client, message);
//await _commandService.ExecuteAsync(context, command.Data.Name, _services);
await command.RespondAsync($"You executed {command.Data.Name}");
}
private async Task BuildGlobalCommands()
{
var globalCommand = new SlashCommandBuilder();
globalCommand.WithName("best-global-command");
globalCommand.WithDescription("This is my first global slash command");
var globalMessageCommand = new MessageCommandBuilder();
globalMessageCommand.WithName("best-global-message-command");
var globalUserCommand = new UserCommandBuilder();
globalUserCommand.WithName("best-global-user-command");
await _client.BulkOverwriteGlobalApplicationCommandsAsync(new ApplicationCommandProperties[]
{
globalCommand.Build(),
globalUserCommand.Build(),
globalMessageCommand.Build()
});
}
private async void ControlKillDeath()
{
while (true)
{
try
{
Thread.Sleep(300 * 1000);
using var _dbContext = new Entities.Models();
foreach (var albionPlayerDiscordGuild in _dbContext.AlbionPlayerDiscordGuild.ToList())
{
var albionPlayer = _dbContext.AlbionPlayer.FirstOrDefault(ap => ap.Id == albionPlayerDiscordGuild.AlbionPlayerId);
await _commandsModule.AlbionPlayerKillCheck(albionPlayer.Name);
await _commandsModule.AlbionPlayerDeathCheck(albionPlayer.Name);
}
}
catch (Exception ex)
{
{
_functionsModule.LogPrinter(ex.Message);
}
}
}
}
private async void CallBack()
{
const int callBackMessageMinute = 1;
var lastTime = DateTime.Now.AddMinutes(-callBackMessageMinute);
while (true)
{
try
{
Thread.Sleep(30 * 1000);
using var httpClient = new HttpClient();
var uriString = "https://localhost/Home/Callback";
var uriBuilder = new UriBuilder(uriString);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
uriBuilder.Query = query.ToString();
uriString = uriBuilder.ToString();
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Add("User-Agent", "CRYALP.com");
var httpResponse = await httpClient.GetAsync(uriString);
httpResponse.EnsureSuccessStatusCode();
var callBackResponse = await httpResponse.Content.ReadAsStringAsync();
if (DateTime.Now >= lastTime.AddMinutes(callBackMessageMinute))
{
var asd = $"--message \"CallBack Response: {callBackResponse}\"";
await _commandsModule.SendMessageToMutualChannel(asd);
lastTime = DateTime.Now;
}
}
catch (Exception ex)
{
_functionsModule.LogPrinter(ex.Message);
}
}
}
private async Task Ready()
{
try
{
await BuildGlobalCommands();
await _client.SetStatusAsync(UserStatus.DoNotDisturb);
ConfigModule.Game = "cryalp.com | çaycı help";
await _client.SetGameAsync(ConfigModule.Game, "https://cryalp.com", ActivityType.Playing);
await _commandsModule.SendMessageToMutualChannel($"--message \"I'm Back at {DateTime.Now}\"");
var callBackThread = new Thread(new ThreadStart(CallBack));
callBackThread.Start();
var controlKillDeathThread = new Thread(new ThreadStart(ControlKillDeath));
controlKillDeathThread.Start();
}
catch (Exception ex)
{
_functionsModule.LogPrinter(ex.Message);
}
}
private async Task MessageReceived(SocketMessage message)
{
try
{
if (message is not SocketUserMessage userMessage || message.Author.IsBot)
{
return;
}
var match = Regex.Match(userMessage.Content, "^" + _configuration.GetValue<string>("Cayci:Prefix") + "?\\s+", RegexOptions.IgnoreCase);
int? pos = null;
if (match.Success)
{
pos = match.Length;
}
else
{
var dmChannel = await userMessage.Author.CreateDMChannelAsync();
if (userMessage.Channel.Id == dmChannel.Id)
{
pos = 0;
}
}
var context = new SocketCommandContext(_client, userMessage);
if (pos.HasValue)
{
_functionsModule.LogPrinter(userMessage.Content[pos.Value..]);
await _commandService.ExecuteAsync(context, userMessage.Content[pos.Value..], _services);
}
else
{
await _commandService.ExecuteAsync(context, "parse " + userMessage.Content, _services);
}
}
catch (Exception ex)
{
var reply = await message.Channel.SendMessageAsync($"Error: {ex.Message}", false);
await reply.AddReactionAsync(new Emoji("😱"));
_functionsModule.LogPrinter(ex.Message);
}
}
private Task Log(LogMessage message)
{
_logger.Log(GetLogLevel(message.Severity), message.Exception, message.Source + ":" + message.Message);
_functionsModule.LogPrinter($"Cayci log: {message.Message}");
return Task.CompletedTask;
}
private static LogLevel GetLogLevel(LogSeverity severity)
{
return severity switch
{
LogSeverity.Critical => LogLevel.Critical,
LogSeverity.Error => LogLevel.Error,
LogSeverity.Warning => LogLevel.Warning,
LogSeverity.Info => LogLevel.Information,
LogSeverity.Verbose => LogLevel.Trace,
LogSeverity.Debug => LogLevel.Debug,
_ => throw new NotImplementedException(nameof(severity) + "=" + severity.ToString()),
};
}
public async Task StopAsync()
{
await _commandsModule.SendMessageToMutualChannel($"--message \"I'm Stopping at {DateTime.Now}\"");
await _client.SetGameAsync(null);
await _client.SetStatusAsync(UserStatus.Offline);
_client.Log -= Log;
_client.Ready -= Ready;
_client.MessageReceived -= MessageReceived;
_commandService.Log -= Log;
_commandService.CommandExecuted -= CommandExecuted;
await _client.StopAsync();
}
async Task IHostedService.StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Running Cayci as hosted service");
await RunAsync();
}
async Task IHostedService.StopAsync(CancellationToken cancellationToken)
{
await StopAsync();
_logger.LogInformation("Stopping Cayci as hosted service");
}
public void Dispose()
{
_client.Dispose();
}
}
}