Removed extra spaces. Removed double \r\n across all code files.

This commit is contained in:
Christopher Darnell committed 2021-05-06 20:07:03 -07:00
1 parent 91d6d1531b
commit 5bb1b43e81
19 files changed
+59 -380

No files matched your search

-11
View File
@@ -9,7 +9,6 @@ using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("bot")] [Group("bot")]
@@ -23,7 +22,6 @@ namespace StarsiegeBot
public BotSettings() public BotSettings()
{ {
Console.WriteLine("Bot Setting Commands Loaded"); Console.WriteLine("Bot Setting Commands Loaded");
if (!(GuildSettings is null)) if (!(GuildSettings is null))
{ {
// guild settings have already been set... stop resetting it. // guild settings have already been set... stop resetting it.
@@ -49,12 +47,10 @@ namespace StarsiegeBot
item.SelfRoles = new Dictionary<string, Dictionary<string, int>>(); item.SelfRoles = new Dictionary<string, Dictionary<string, int>>();
item.Prefixes.Add(">"); item.Prefixes.Add(">");
// this line... is a test line. // this line... is a test line.
GuildSettings = new Dictionary<string, GuildSettings> GuildSettings = new Dictionary<string, GuildSettings>
{ {
{ "default", item } { "default", item }
}; };
// Now that we have the initial stuff in memory, write it to file. // Now that we have the initial stuff in memory, write it to file.
string output = JsonConvert.SerializeObject(GuildSettings); string output = JsonConvert.SerializeObject(GuildSettings);
File.WriteAllTextAsync(s_fileName, output); File.WriteAllTextAsync(s_fileName, output);
@@ -77,7 +73,6 @@ namespace StarsiegeBot
[Description("Reports simplified data about the server settings.")] [Description("Reports simplified data about the server settings.")]
public async Task BaseItem(CommandContext ctx) public async Task BaseItem(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
GuildSettings guild = GuildSettings[ctx.Guild.Id.ToString()]; GuildSettings guild = GuildSettings[ctx.Guild.Id.ToString()];
DiscordEmbedBuilder embed = StartEmbed(ctx.Guild.Name + " Server settings."); DiscordEmbedBuilder embed = StartEmbed(ctx.Guild.Name + " Server settings.");
embed.AddField("On/Off Items", "_ _"); embed.AddField("On/Off Items", "_ _");
@@ -93,12 +88,10 @@ namespace StarsiegeBot
embed.AddField("Levels", guild.LevelRoles.Count.ToString(), true); embed.AddField("Levels", guild.LevelRoles.Count.ToString(), true);
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
[Command("status"), RequireOwner] [Command("status"), RequireOwner]
[Description("Sets the bot's nickname on this server.")] [Description("Sets the bot's nickname on this server.")]
public async Task SetStatus(CommandContext ctx, string type, [RemainingText] string newStatus = null) public async Task SetStatus(CommandContext ctx, string type, [RemainingText] string newStatus = null)
{ {
await ctx.TriggerTypingAsync();
ActivityType aType = type.ToLower() switch ActivityType aType = type.ToLower() switch
{ {
"competing" => ActivityType.Competing, "competing" => ActivityType.Competing,
@@ -112,15 +105,12 @@ namespace StarsiegeBot
await ctx.Client.UpdateStatusAsync(act); await ctx.Client.UpdateStatusAsync(act);
await ctx.RespondAsync("Test."); await ctx.RespondAsync("Test.");
} }
[Command("username"), RequireOwner] [Command("username"), RequireOwner]
public async Task SetUsername(CommandContext ctx, [RemainingText] string newName) public async Task SetUsername(CommandContext ctx, [RemainingText] string newName)
{ {
await ctx.TriggerTypingAsync();
await ctx.Client.UpdateCurrentUserAsync(newName); await ctx.Client.UpdateCurrentUserAsync(newName);
await ctx.RespondAsync("How's my name name?"); await ctx.RespondAsync("How's my name name?");
} }
private async Task StartTimer(CancellationToken cancellationToken) private async Task StartTimer(CancellationToken cancellationToken)
{ {
await Task.Run(async () => await Task.Run(async () =>
@@ -148,7 +138,6 @@ namespace StarsiegeBot
return embed; return embed;
} }
} }
public class GuildSettings public class GuildSettings
{ {
public bool UseGlobalPrefix { get; set; } public bool UseGlobalPrefix { get; set; }
+6 -25
View File
@@ -10,7 +10,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
class Triggers class Triggers
@@ -19,14 +18,12 @@ namespace StarsiegeBot
public static DiscordMember notify; public static DiscordMember notify;
// protected string BotName { get; set; } // protected string BotName { get; set; }
private readonly BotSettings _guilds = new BotSettings(); private readonly BotSettings _guilds = new BotSettings();
public Triggers(EventId botEventId) => BotEventId = botEventId; public Triggers(EventId botEventId) => BotEventId = botEventId;
public Task CommandExecuted(CommandsNextExtension ext, CommandExecutionEventArgs e) public Task CommandExecuted(CommandsNextExtension ext, CommandExecutionEventArgs e)
{ {
// e.Context.Client.Logger.LogCritical(BotEventId, $"Client is in {e.Context.Client.Guilds.Count}"); // e.Context.Client.Logger.LogCritical(BotEventId, $"Client is in {e.Context.Client.Guilds.Count}");
// let's log the name of the command and user // let's log the name of the command and user
// e.Context.Client.Logger.LogInformation(BotEventId, $"{e.Context.User.Username} successfully executed '{e.Command.QualifiedName}'"); // e.Context.Client.Logger.LogInformation(BotEventId, $"{e.Context.User.Username} successfully executed '{e.Command.QualifiedName}'");
// since this method is not async, let's return // since this method is not async, let's return
// a completed task, so that no additional work // a completed task, so that no additional work
// is done // is done
@@ -34,22 +31,18 @@ namespace StarsiegeBot
} }
public Task MessageCreated(DiscordClient d, MessageCreateEventArgs e) public Task MessageCreated(DiscordClient d, MessageCreateEventArgs e)
{ {
// d.Logger.LogDebug(BotEventId, "MessageCreated.");
// Ignore all bots. We don't care. // Ignore all bots. We don't care.
if (e.Author.IsBot) if (e.Author.IsBot)
{ {
return Task.CompletedTask; return Task.CompletedTask;
} }
// d.Logger.LogDebug(BotEventId, "MessageCreated.");
CommandsNextExtension cnext = d.GetCommandsNext(); CommandsNextExtension cnext = d.GetCommandsNext();
DiscordMessage msg = e.Message; DiscordMessage msg = e.Message;
// Check if message has valid prefix. // Check if message has valid prefix.
// json file loaded... int cmdStart = msg.GetStringPrefixLength(d.CurrentUser.Mention.Insert(2, "!"));
int cmdStart = msg.GetStringPrefixLength("!");
List<string> prefixes = BotSettings.GuildSettings["default"].Prefixes; List<string> prefixes = BotSettings.GuildSettings["default"].Prefixes;
prefixes.Add(d.CurrentUser.Mention); // if Guild is not null, we're on a guild. Check for Guild Prefixes.
if (!(e.Guild is null)) if (!(e.Guild is null))
{ {
string gId = e.Guild.Id.ToString(); string gId = e.Guild.Id.ToString();
@@ -69,6 +62,8 @@ namespace StarsiegeBot
} }
} }
} }
// hard code the bot's mention as a possible prefix.
prefixes.Add(d.CurrentUser.Mention.Insert(2, "!"));
foreach (string item in prefixes) foreach (string item in prefixes)
{ {
cmdStart = msg.GetStringPrefixLength(item); cmdStart = msg.GetStringPrefixLength(item);
@@ -76,21 +71,16 @@ namespace StarsiegeBot
} }
// we didn't find a command prefix... Break. // we didn't find a command prefix... Break.
if (cmdStart == -1) return Task.CompletedTask; if (cmdStart == -1) return Task.CompletedTask;
// Retrieve prefix. // Retrieve prefix.
string prefix = msg.Content.Substring(0, cmdStart); string prefix = msg.Content.Substring(0, cmdStart);
string cmdString = msg.Content[cmdStart..]; string cmdString = msg.Content.Substring(cmdStart);
// Retrieve full command string. // Retrieve full command string.
Command command = cnext.FindCommand(cmdString, out string args); Command command = cnext.FindCommand(cmdString, out string args);
if (command == null) return Task.CompletedTask; if (command == null) return Task.CompletedTask;
CommandContext ctx = cnext.CreateContext(msg, prefix, command, args); CommandContext ctx = cnext.CreateContext(msg, prefix, command, args);
Task.Run(async () => await cnext.ExecuteCommandAsync(ctx)); Task.Run(async () => await cnext.ExecuteCommandAsync(ctx));
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task CommandErrored(CommandsNextExtension ext, CommandErrorEventArgs e) public Task CommandErrored(CommandsNextExtension ext, CommandErrorEventArgs e)
{ {
e.Context.Client.Logger.LogError(BotEventId, $"{e.Context.User.Username} tried executing '{e.Command?.QualifiedName ?? "<unknown command>"}' but it errored: {e.Exception.GetType()}: {e.Exception.Message ?? "<no message>"}", DateTime.Now); e.Context.Client.Logger.LogError(BotEventId, $"{e.Context.User.Username} tried executing '{e.Command?.QualifiedName ?? "<unknown command>"}' but it errored: {e.Exception.GetType()}: {e.Exception.Message ?? "<no message>"}", DateTime.Now);
@@ -101,12 +91,10 @@ namespace StarsiegeBot
{ {
output += item.ToString() + "\r\n"; output += item.ToString() + "\r\n";
} }
Console.WriteLine(output); Console.WriteLine(output);
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task InteractionCreated(DiscordClient d, InteractionCreateEventArgs e) public Task InteractionCreated(DiscordClient d, InteractionCreateEventArgs e)
{ {
// d.Logger.LogDebug(BotEventId, $"{e.Interaction.User.Username} started an interaction. {e.Interaction.Data.Name}"); // d.Logger.LogDebug(BotEventId, $"{e.Interaction.User.Username} started an interaction. {e.Interaction.Data.Name}");
@@ -152,7 +140,6 @@ namespace StarsiegeBot
// let's log the details of the error that just // let's log the details of the error that just
// occured in our client // occured in our client
d.Logger.LogError(BotEventId, e.Exception, "Exception occured"); d.Logger.LogError(BotEventId, e.Exception, "Exception occured");
// since this method is not async, let's return // since this method is not async, let's return
// a completed task, so that no additional work // a completed task, so that no additional work
// is done // is done
@@ -193,7 +180,6 @@ namespace StarsiegeBot
BotSettings.GuildSettings.Add(gId, item); BotSettings.GuildSettings.Add(gId, item);
} }
} }
// let's log the name of the guild that was just // let's log the name of the guild that was just
// sent to our client // sent to our client
d.Logger.LogInformation(BotEventId, $"Guild available: {e.Guild.Name}"); d.Logger.LogInformation(BotEventId, $"Guild available: {e.Guild.Name}");
@@ -201,7 +187,6 @@ namespace StarsiegeBot
// notify the *primary bot owner if the Guild count is above 75. So we can start bot verification process. // notify the *primary bot owner if the Guild count is above 75. So we can start bot verification process.
if (d.Guilds.Count > 75 && !(notify is null)) if (d.Guilds.Count > 75 && !(notify is null))
notify.SendMessageAsync("**__WARNING__: BOT IS IN OVER 75 SERVERS."); notify.SendMessageAsync("**__WARNING__: BOT IS IN OVER 75 SERVERS.");
// since this method is not async, let's return // since this method is not async, let's return
// a completed task, so that no additional work // a completed task, so that no additional work
// is done // is done
@@ -246,7 +231,6 @@ namespace StarsiegeBot
// notify the *primary bot owner if the Guild count is above 75. So we can start bot verification process. // notify the *primary bot owner if the Guild count is above 75. So we can start bot verification process.
if (e.Guilds.Count > 75) if (e.Guilds.Count > 75)
notify.SendMessageAsync("**__WARNING__: BOT IS IN OVER 75 SERVERS."); notify.SendMessageAsync("**__WARNING__: BOT IS IN OVER 75 SERVERS.");
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task GuildEmojisUpdated(DiscordClient d, GuildEmojisUpdateEventArgs e) public Task GuildEmojisUpdated(DiscordClient d, GuildEmojisUpdateEventArgs e)
@@ -266,7 +250,6 @@ namespace StarsiegeBot
{ {
return Task.CompletedTask; return Task.CompletedTask;
} }
string gId = e.Guild.Id.ToString(); string gId = e.Guild.Id.ToString();
if (BotSettings.GuildSettings[gId].UseWelcome && if (BotSettings.GuildSettings[gId].UseWelcome &&
!(BotSettings.GuildSettings[gId].WelcomeChannel is null) && !(BotSettings.GuildSettings[gId].WelcomeChannel is null) &&
@@ -275,7 +258,6 @@ namespace StarsiegeBot
string msg = WelcomeMessage.WelcomeMessageProcessing(BotSettings.GuildSettings[gId].WelcomeMessage, e.Member, e.Guild); string msg = WelcomeMessage.WelcomeMessageProcessing(BotSettings.GuildSettings[gId].WelcomeMessage, e.Member, e.Guild);
BotSettings.GuildSettings[gId].WelcomeChannel.SendMessageAsync(msg); BotSettings.GuildSettings[gId].WelcomeChannel.SendMessageAsync(msg);
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task GuildMemberRemoved(DiscordClient d, GuildMemberRemoveEventArgs e) public Task GuildMemberRemoved(DiscordClient d, GuildMemberRemoveEventArgs e)
@@ -382,7 +364,6 @@ namespace StarsiegeBot
{ {
// let's log the fact that this event occured // let's log the fact that this event occured
d.Logger.LogInformation(BotEventId, $"Client is ready to process events. Client is in: {d.Guilds.Count} Guilds."); d.Logger.LogInformation(BotEventId, $"Client is ready to process events. Client is in: {d.Guilds.Count} Guilds.");
// since this method is not async, let's return // since this method is not async, let's return
// a completed task, so that no additional work // a completed task, so that no additional work
// is done // is done
-3
View File
@@ -10,12 +10,10 @@ using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("ex")] [Group("ex")]
[Hidden] [Hidden]
[Description("Experimental commands. May break the bot.")] [Description("Experimental commands. May break the bot.")]
class ExperiemntalCommands : BaseCommandModule class ExperiemntalCommands : BaseCommandModule
{ {
@@ -25,7 +23,6 @@ namespace StarsiegeBot
await ctx.RespondAsync("Attempting a shutdown..."); await ctx.RespondAsync("Attempting a shutdown...");
System.Environment.Exit(0); System.Environment.Exit(0);
} }
[Command("Report")] [Command("Report")]
public async Task Report(CommandContext ctx) public async Task Report(CommandContext ctx)
{ {
-25
View File
@@ -7,7 +7,6 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
class GameCommands : BaseCommandModule class GameCommands : BaseCommandModule
@@ -21,19 +20,16 @@ namespace StarsiegeBot
"{0} slaps {1} around a bit with a rubber chicken." "{0} slaps {1} around a bit with a rubber chicken."
}; };
private List<string> _insultCopy; private List<string> _insultCopy;
public GameCommands() public GameCommands()
{ {
// Let the console know we've loaded basic commands. // Let the console know we've loaded basic commands.
Console.WriteLine("Basic Commands Loaded"); Console.WriteLine("Basic Commands Loaded");
_insultCopy = _insultMaster.ToList<string>(); _insultCopy = _insultMaster.ToList<string>();
} }
[Command("8ball"), Aliases(new string[] { "ball", "8" })] [Command("8ball"), Aliases(new string[] { "ball", "8" })]
[Description("The Magic 8-Ball is a fortune-telling or seeking advice")] [Description("The Magic 8-Ball is a fortune-telling or seeking advice")]
public async Task Eightball(CommandContext ctx, [RemainingText, Description("Your question to the 8 ball")] string remainingText = "") public async Task Eightball(CommandContext ctx, [RemainingText, Description("Your question to the 8 ball")] string remainingText = "")
{ {
await ctx.TriggerTypingAsync();
// Load all the traditional 8-Ball answers into an array. // Load all the traditional 8-Ball answers into an array.
string[] results = new string[] { "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no", "Outlook not so good.", "Very doubtful." }; string[] results = new string[] { "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no", "Outlook not so good.", "Very doubtful." };
// give the end user the randomly choosen result. // give the end user the randomly choosen result.
@@ -43,7 +39,6 @@ namespace StarsiegeBot
[Description("Gives some basic info about the bot")] [Description("Gives some basic info about the bot")]
public async Task About(CommandContext ctx) public async Task About(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
// delcare an embed builder. // delcare an embed builder.
DiscordEmbedBuilder embed = new DiscordEmbedBuilder(); DiscordEmbedBuilder embed = new DiscordEmbedBuilder();
// Title the ebemd with the bot's name and discrim. // Title the ebemd with the bot's name and discrim.
@@ -65,7 +60,6 @@ namespace StarsiegeBot
{ {
owners += owner.Username + "#" + owner.Discriminator + "\r\n"; owners += owner.Username + "#" + owner.Discriminator + "\r\n";
} }
embed.AddField("Owner(s)", owners, false); embed.AddField("Owner(s)", owners, false);
// send the data to the end user. // send the data to the end user.
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
@@ -75,7 +69,6 @@ namespace StarsiegeBot
public async Task Coinflip(CommandContext ctx) public async Task Coinflip(CommandContext ctx)
{ {
// We're going to randomly select heads or tails and then give it to the user. // We're going to randomly select heads or tails and then give it to the user.
await ctx.TriggerTypingAsync();
string[] choices = { "heads", "tails" }; string[] choices = { "heads", "tails" };
await ctx.RespondAsync(StartEmbed($"The coin landed on... {choices[Program.rnd.Next(0, choices.Length)]}")); await ctx.RespondAsync(StartEmbed($"The coin landed on... {choices[Program.rnd.Next(0, choices.Length)]}"));
} }
@@ -83,7 +76,6 @@ namespace StarsiegeBot
[Description("Shows all those that have helped with my bot(s) over the years!")] [Description("Shows all those that have helped with my bot(s) over the years!")]
public async Task Credits(CommandContext ctx) public async Task Credits(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
// just some people that have helped me build the bot. // just some people that have helped me build the bot.
string credits = "```asciidoc\r\n= CREDITS (Outdated) =\r\n" + string credits = "```asciidoc\r\n= CREDITS (Outdated) =\r\n" +
"• UndeadShadow :: Flood Protection. Keepign teh bot from killing itself, and others.\r\n" + "• UndeadShadow :: Flood Protection. Keepign teh bot from killing itself, and others.\r\n" +
@@ -102,7 +94,6 @@ namespace StarsiegeBot
public async Task Dice(CommandContext ctx, [RemainingText, Description("XdY")] string throwing = "d") public async Task Dice(CommandContext ctx, [RemainingText, Description("XdY")] string throwing = "d")
{ {
// let the end user know the bot is doing something... // let the end user know the bot is doing something...
await ctx.TriggerTypingAsync();
// in case the end user used caps, lower them. // in case the end user used caps, lower them.
throwing = throwing.ToLower(); throwing = throwing.ToLower();
// set some int items. // set some int items.
@@ -126,13 +117,11 @@ namespace StarsiegeBot
// attempt to get the number of dice being "thrown" and the number of sides those die have. // attempt to get the number of dice being "thrown" and the number of sides those die have.
bool volTest = int.TryParse(m.Groups[1].ToString(), out int volume); bool volTest = int.TryParse(m.Groups[1].ToString(), out int volume);
bool sideTest = int.TryParse(m.Groups[3].ToString(), out int sides); bool sideTest = int.TryParse(m.Groups[3].ToString(), out int sides);
// They failed? Make some stuff up... We default to a 1d6 throw. // They failed? Make some stuff up... We default to a 1d6 throw.
if (!volTest) if (!volTest)
volume = 1; volume = 1;
if (!sideTest) if (!sideTest)
sides = 6; sides = 6;
// for each die we roll, get a result. // for each die we roll, get a result.
for (int i = 0; i < volume; i++) for (int i = 0; i < volume; i++)
{ {
@@ -175,13 +164,10 @@ namespace StarsiegeBot
} }
await ctx.RespondAsync(output); await ctx.RespondAsync(output);
} }
[Command("random")] [Command("random")]
[Description("Random number generator.")] [Description("Random number generator.")]
public async Task Random(CommandContext ctx, [Description("Lowest number choice. (Inclusive)")] int min, [Description("Highest Number Choice. (Inclusive)")] int max) public async Task Random(CommandContext ctx, [Description("Lowest number choice. (Inclusive)")] int min, [Description("Highest Number Choice. (Inclusive)")] int max)
{ {
await ctx.TriggerTypingAsync();
// Find which number given is lower, which is higher. // Find which number given is lower, which is higher.
// since rnd.Nex is inclusive, exclusive, increase the max by one. // since rnd.Nex is inclusive, exclusive, increase the max by one.
int i = Math.Min(min, max); int i = Math.Min(min, max);
@@ -192,7 +178,6 @@ namespace StarsiegeBot
[Command("random")] [Command("random")]
public async Task Random(CommandContext ctx) public async Task Random(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
// some one didn't read the HELP file on Random. Explain it to them. // some one didn't read the HELP file on Random. Explain it to them.
await ctx.RespondAsync(StartEmbed($"Gives you a random number between <Option 1> and <Option 2> Try someething like `random 3 30`!")); await ctx.RespondAsync(StartEmbed($"Gives you a random number between <Option 1> and <Option 2> Try someething like `random 3 30`!"));
} }
@@ -200,7 +185,6 @@ namespace StarsiegeBot
[Description("Rock Paper Scissors")] [Description("Rock Paper Scissors")]
public async Task Rps(CommandContext ctx, [RemainingText, Description("Your choice of hand sign to use.")] string text = "") public async Task Rps(CommandContext ctx, [RemainingText, Description("Your choice of hand sign to use.")] string text = "")
{ {
await ctx.TriggerTypingAsync();
/* --- THIS FUNCTION IS A COPY AND PASTE OF RPSLS. AND ALL LOGIC IS IDENTICAL TO IT. PLEASE REFER TO THAT METHOD. --- /* --- THIS FUNCTION IS A COPY AND PASTE OF RPSLS. AND ALL LOGIC IS IDENTICAL TO IT. PLEASE REFER TO THAT METHOD. ---
// --- THIS FUNCTION IS A COPY AND PASTE OF RPSLS. AND ALL LOGIC IS IDENTICAL TO IT. PLEASE REFER TO THAT METHOD. --- // --- THIS FUNCTION IS A COPY AND PASTE OF RPSLS. AND ALL LOGIC IS IDENTICAL TO IT. PLEASE REFER TO THAT METHOD. ---
// --- THIS FUNCTION IS A COPY AND PASTE OF RPSLS. AND ALL LOGIC IS IDENTICAL TO IT. PLEASE REFER TO THAT METHOD. --- */ // --- THIS FUNCTION IS A COPY AND PASTE OF RPSLS. AND ALL LOGIC IS IDENTICAL TO IT. PLEASE REFER TO THAT METHOD. --- */
@@ -208,7 +192,6 @@ namespace StarsiegeBot
text = text.ToLower(); text = text.ToLower();
string botChoice = choices[Program.rnd.Next(0, choices.Length)]; string botChoice = choices[Program.rnd.Next(0, choices.Length)];
string result; string result;
if (text.Equals("")) if (text.Equals(""))
{ {
result = "I'm handing you a"; result = "I'm handing you a";
@@ -256,7 +239,6 @@ namespace StarsiegeBot
[Description("Rock Paper Scissors Lizard Spock")] [Description("Rock Paper Scissors Lizard Spock")]
public async Task Rpsls(CommandContext ctx, [RemainingText, Description("Your choice of hand sign to use.")] string text = "") public async Task Rpsls(CommandContext ctx, [RemainingText, Description("Your choice of hand sign to use.")] string text = "")
{ {
await ctx.TriggerTypingAsync();
// load up the correct choices. // load up the correct choices.
string[] choices = new string[] { "rock", "paper", "scissors", "lizard", "spock" }; string[] choices = new string[] { "rock", "paper", "scissors", "lizard", "spock" };
// lets work in all lower case letters. makes life easier. // lets work in all lower case letters. makes life easier.
@@ -265,7 +247,6 @@ namespace StarsiegeBot
string botChoice = choices[Program.rnd.Next(0, choices.Length)]; string botChoice = choices[Program.rnd.Next(0, choices.Length)];
// create a result string. // create a result string.
string result; string result;
// the end user didn't pick anything... lets hand them something instead. // the end user didn't pick anything... lets hand them something instead.
if (text.Equals("")) if (text.Equals(""))
{ {
@@ -337,7 +318,6 @@ namespace StarsiegeBot
// This is a redundant bot check. We really wanna make sure that we're not spamming an unprotected bot with commands, and that they are spamming us back. // This is a redundant bot check. We really wanna make sure that we're not spamming an unprotected bot with commands, and that they are spamming us back.
if (ctx.Message.Author.IsBot) if (ctx.Message.Author.IsBot)
return; return;
await ctx.TriggerTypingAsync();
// did the end user supply us something to say? no whine about it. // did the end user supply us something to say? no whine about it.
string result; string result;
if (msg != "") if (msg != "")
@@ -349,11 +329,9 @@ namespace StarsiegeBot
[Command("slap")] [Command("slap")]
public async Task Slap(CommandContext ctx, DiscordMember user = null) public async Task Slap(CommandContext ctx, DiscordMember user = null)
{ {
await ctx.TriggerTypingAsync();
// we're going to find out who we're slapping. Declare their place holders now. // we're going to find out who we're slapping. Declare their place holders now.
string user1; string user1;
string user2; string user2;
// If we have some one not slapping some one, or they're trying to slap themself, the one getting slapped is the // If we have some one not slapping some one, or they're trying to slap themself, the one getting slapped is the
// author, the one doing the slapping is the bot. // author, the one doing the slapping is the bot.
if (user == null || user.Mention == ctx.Message.Author.Mention) if (user == null || user.Mention == ctx.Message.Author.Mention)
@@ -369,7 +347,6 @@ namespace StarsiegeBot
} }
// pick a random insult, and populate the names correctly. // pick a random insult, and populate the names correctly.
int randInt = Program.rnd.Next(0, _insultCopy.Count); int randInt = Program.rnd.Next(0, _insultCopy.Count);
await ctx.RespondAsync(StartEmbed(string.Format(_insultCopy[randInt], user1, user2))); await ctx.RespondAsync(StartEmbed(string.Format(_insultCopy[randInt], user1, user2)));
_insultCopy.RemoveAt(randInt); _insultCopy.RemoveAt(randInt);
if (_insultCopy.Count == 0) if (_insultCopy.Count == 0)
@@ -377,7 +354,6 @@ namespace StarsiegeBot
_insultCopy = _insultMaster.ToList<string>(); _insultCopy = _insultMaster.ToList<string>();
} }
} }
private DiscordEmbedBuilder StartEmbed(string desc) private DiscordEmbedBuilder StartEmbed(string desc)
{ {
DiscordEmbedBuilder embed = new DiscordEmbedBuilder DiscordEmbedBuilder embed = new DiscordEmbedBuilder
@@ -387,6 +363,5 @@ namespace StarsiegeBot
}; };
return embed; return embed;
} }
} }
} }
+1 -11
View File
@@ -7,7 +7,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("Group")] [Group("Group")]
@@ -18,14 +17,11 @@ namespace StarsiegeBot
{ {
Console.WriteLine("Group Management Loaded."); Console.WriteLine("Group Management Loaded.");
} }
[GroupCommand, Aliases("view")] [GroupCommand, Aliases("view")]
public async Task ListGroups(CommandContext ctx) public async Task ListGroups(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
DiscordEmbedBuilder embed = new DiscordEmbedBuilder(); DiscordEmbedBuilder embed = new DiscordEmbedBuilder();
embed.WithTitle($"{ctx.Guild.Name} Groups"); embed.WithTitle($"{ctx.Guild.Name} Groups");
embed.WithDescription("An overview of all role groups."); embed.WithDescription("An overview of all role groups.");
foreach (KeyValuePair<string, Dictionary<string, int>> item in GuildSettings[gId].SelfRoles) foreach (KeyValuePair<string, Dictionary<string, int>> item in GuildSettings[gId].SelfRoles)
@@ -34,11 +30,9 @@ namespace StarsiegeBot
} }
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
[Command("add")] [Command("add")]
public async Task AddGroup(CommandContext ctx, [RemainingText, Description("Group to create.")] string groupName) public async Task AddGroup(CommandContext ctx, [RemainingText, Description("Group to create.")] string groupName)
{ {
await ctx.TriggerTypingAsync();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
if (GuildSettings[gId].SelfRoles.ContainsKey(groupName)) if (GuildSettings[gId].SelfRoles.ContainsKey(groupName))
{ {
@@ -51,12 +45,10 @@ namespace StarsiegeBot
await ctx.RespondAsync($"The group `{groupName}` was added."); await ctx.RespondAsync($"The group `{groupName}` was added.");
} }
} }
// TODO: Delete all roles or assign new group? // TODO: Delete all roles or assign new group?
[Command("delete")] [Command("delete")]
public async Task RemoveGroup(CommandContext ctx, [RemainingText, Description("Group to delete")] string groupName) public async Task RemoveGroup(CommandContext ctx, [RemainingText, Description("Group to delete")] string groupName)
{ {
await ctx.TriggerTypingAsync();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
if (GuildSettings[gId].SelfRoles.ContainsKey(groupName)) if (GuildSettings[gId].SelfRoles.ContainsKey(groupName))
{ {
@@ -68,14 +60,12 @@ namespace StarsiegeBot
await ctx.RespondAsync($"The group `{groupName}` doesn't exist."); await ctx.RespondAsync($"The group `{groupName}` doesn't exist.");
} }
} }
//[Command("edit")] //[Command("edit")]
//[Description("This is under construction. Does nothing yet.")] //[Description("This is under construction. Does nothing yet.")]
//public async Task EditGroup(CommandContext ctx, [RemainingText] string groupInfo) //public async Task EditGroup(CommandContext ctx, [RemainingText] string groupInfo)
//{ //{
// await ctx.TriggerTypingAsync(); //
// // string gId = ctx.Guild.Id.ToString(); // // string gId = ctx.Guild.Id.ToString();
//} //}
} }
} }
@@ -6,7 +6,6 @@ using DSharpPlus.Entities;
using System; using System;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("GroupRole"), Aliases("gr")] [Group("GroupRole"), Aliases("gr")]
@@ -18,13 +17,10 @@ namespace StarsiegeBot
{ {
Console.WriteLine("Group Role Management Loaded."); Console.WriteLine("Group Role Management Loaded.");
} }
[GroupCommand] [GroupCommand]
public async Task ListGroups(CommandContext ctx) public async Task ListGroups(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
} }
[Command("add")] [Command("add")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task AddSelfRole(CommandContext ctx, public async Task AddSelfRole(CommandContext ctx,
@@ -32,15 +28,12 @@ namespace StarsiegeBot
[Description("The price of the role for buyable roles. 0 for no cost. Free free to leave blank if not using Buyable roles.")] int price = 0, [Description("The price of the role for buyable roles. 0 for no cost. Free free to leave blank if not using Buyable roles.")] int price = 0,
[Description("What group to put the role in. If not using groups, you can leave blank."), RemainingText] string groupName = null) [Description("What group to put the role in. If not using groups, you can leave blank."), RemainingText] string groupName = null)
{ {
await ctx.TriggerTypingAsync();
price = Math.Abs(price); price = Math.Abs(price);
// Fix price. // Fix price.
// Verify group exists. // Verify group exists.
// Since we allow roles to be in several groups, dont have to verify that. // Since we allow roles to be in several groups, dont have to verify that.
// //
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
if (GuildSettings[gId].SelfRoles.ContainsKey(groupName)) if (GuildSettings[gId].SelfRoles.ContainsKey(groupName))
{ {
GuildSettings[gId].SelfRoles[groupName].Add(role.Id.ToString(), price); GuildSettings[gId].SelfRoles[groupName].Add(role.Id.ToString(), price);
@@ -49,31 +42,23 @@ namespace StarsiegeBot
else else
{ {
// group not found, `Create it?` or `Cancel`? // group not found, `Create it?` or `Cancel`?
} }
} }
[Command("delete")] [Command("delete")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task DeleteSelfRole(CommandContext ctx, public async Task DeleteSelfRole(CommandContext ctx,
[Description("The role to delete.")] DiscordRole role, [Description("The role to delete.")] DiscordRole role,
[Description("The group to remove the role from. If left blank, will remove from all groups."), RemainingText] string group = null) [Description("The group to remove the role from. If left blank, will remove from all groups."), RemainingText] string group = null)
{ {
await ctx.TriggerTypingAsync();
// Verify role is in a group. // Verify role is in a group.
// Verify group selected exists. // Verify group selected exists.
// If group null, remove from all groups? // If group null, remove from all groups?
} }
[Command("Edit")] [Command("Edit")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task EditRole(CommandContext ctx, DiscordRole role, int newPrice = 0, [RemainingText] string newGroup = null) public async Task EditRole(CommandContext ctx, DiscordRole role, int newPrice = 0, [RemainingText] string newGroup = null)
{ {
await ctx.TriggerTypingAsync();
} }
private DiscordEmbedBuilder StartEmbed(string desc) private DiscordEmbedBuilder StartEmbed(string desc)
{ {
DiscordEmbedBuilder embed = new DiscordEmbedBuilder DiscordEmbedBuilder embed = new DiscordEmbedBuilder
-10
View File
@@ -5,7 +5,6 @@ using DSharpPlus.CommandsNext.Attributes;
using System; using System;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("Level")] [Group("Level")]
@@ -17,34 +16,25 @@ namespace StarsiegeBot
{ {
Console.WriteLine("Level Management Loaded."); Console.WriteLine("Level Management Loaded.");
} }
[GroupCommand] [GroupCommand]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task ListLevels(CommandContext ctx) public async Task ListLevels(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
} }
[Command("AddLevel"), Aliases("al")] [Command("AddLevel"), Aliases("al")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task AddLevel(CommandContext ctx, int newLevelGroup) public async Task AddLevel(CommandContext ctx, int newLevelGroup)
{ {
await ctx.TriggerTypingAsync();
} }
[Command("DeleteLevel"), Aliases("dl")] [Command("DeleteLevel"), Aliases("dl")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task DeleteLevel(CommandContext ctx, int oldLevelGroup) public async Task DeleteLevel(CommandContext ctx, int oldLevelGroup)
{ {
await ctx.TriggerTypingAsync();
} }
[Command("edit")] [Command("edit")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task EditLevel(CommandContext ctx, int oldLeve, int newLevel) public async Task EditLevel(CommandContext ctx, int oldLeve, int newLevel)
{ {
await ctx.TriggerTypingAsync();
} }
} }
} }
@@ -6,7 +6,6 @@ using DSharpPlus.Entities;
using System; using System;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("LevelRole")] [Group("LevelRole")]
@@ -17,33 +16,25 @@ namespace StarsiegeBot
{ {
Console.WriteLine("Level Role Management Loaded."); Console.WriteLine("Level Role Management Loaded.");
} }
[Command("edit")] [Command("edit")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task EditRole(CommandContext ctx, int oldLevel, int newLevel, DiscordRole role) public async Task EditRole(CommandContext ctx, int oldLevel, int newLevel, DiscordRole role)
{ {
await ctx.TriggerTypingAsync();
} }
[Command("edit")] [Command("edit")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task EditRole(CommandContext ctx, int newLevel, [RemainingText] string role) public async Task EditRole(CommandContext ctx, int newLevel, [RemainingText] string role)
{ {
await ctx.TriggerTypingAsync();
} }
[Command("remove")] [Command("remove")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task RemoveRole(CommandContext ctx, DiscordRole role) public async Task RemoveRole(CommandContext ctx, DiscordRole role)
{ {
await ctx.TriggerTypingAsync();
} }
[Command("remove")] [Command("remove")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task RemoveRole(CommandContext ctx, [RemainingText] string roleName) public async Task RemoveRole(CommandContext ctx, [RemainingText] string roleName)
{ {
await ctx.TriggerTypingAsync();
} }
} }
} }
-10
View File
@@ -6,7 +6,6 @@ using DSharpPlus.Entities;
using System; using System;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("role")] [Group("role")]
@@ -17,35 +16,26 @@ namespace StarsiegeBot
{ {
Console.WriteLine("Role Management Loaded."); Console.WriteLine("Role Management Loaded.");
} }
[Command("join")] [Command("join")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task JoinSelfRole(CommandContext ctx, DiscordRole role) public async Task JoinSelfRole(CommandContext ctx, DiscordRole role)
{ {
await ctx.TriggerTypingAsync();
} }
[Command("join")] [Command("join")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task JoinSelfRole(CommandContext ctx, [RemainingText] string role) public async Task JoinSelfRole(CommandContext ctx, [RemainingText] string role)
{ {
await ctx.TriggerTypingAsync();
} }
[Command("leave")] [Command("leave")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task LeaveSelfRole(CommandContext ctx, DiscordRole role) public async Task LeaveSelfRole(CommandContext ctx, DiscordRole role)
{ {
await ctx.TriggerTypingAsync();
} }
[Command("leave")] [Command("leave")]
[Description("Work in progress. Does nothing yet.")] [Description("Work in progress. Does nothing yet.")]
public async Task LeaveSelfRole(CommandContext ctx, [RemainingText] string role) public async Task LeaveSelfRole(CommandContext ctx, [RemainingText] string role)
{ {
await ctx.TriggerTypingAsync();
} }
private bool VerifiedRole(DiscordGuild guild, DiscordRole role) private bool VerifiedRole(DiscordGuild guild, DiscordRole role)
{ {
return false; return false;
-13
View File
@@ -6,7 +6,6 @@ using System;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("prefix")] [Group("prefix")]
@@ -20,7 +19,6 @@ namespace StarsiegeBot
[GroupCommand] [GroupCommand]
public async Task GetPrefixes(CommandContext ctx) public async Task GetPrefixes(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
// store the Guild ID as a string. // store the Guild ID as a string.
string guild = ctx.Guild.Id.ToString(); string guild = ctx.Guild.Id.ToString();
// if this server doesnt have a settings for whatever reason, let them know... why am i not creating it? // if this server doesnt have a settings for whatever reason, let them know... why am i not creating it?
@@ -36,7 +34,6 @@ namespace StarsiegeBot
{ {
Description = $"{ctx.Guild.Name} Prefixes." Description = $"{ctx.Guild.Name} Prefixes."
}; };
int count = 1; int count = 1;
// for each prefix, list it in the embed as a field. Show a count. // for each prefix, list it in the embed as a field. Show a count.
foreach (string item in server.Prefixes) foreach (string item in server.Prefixes)
@@ -44,7 +41,6 @@ namespace StarsiegeBot
embed.AddField($"Prefix {count}", item, true); embed.AddField($"Prefix {count}", item, true);
count++; count++;
} }
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
} }
@@ -52,7 +48,6 @@ namespace StarsiegeBot
[Description("Adds a new prefix to the Server's list of prefixes.")] [Description("Adds a new prefix to the Server's list of prefixes.")]
public async Task AddNewPrefix(CommandContext ctx, string prefix) public async Task AddNewPrefix(CommandContext ctx, string prefix)
{ {
await ctx.TriggerTypingAsync();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
// add the prefix to the server specific settings. // add the prefix to the server specific settings.
if (GuildSettings[gId].Prefixes.Count < 25) if (GuildSettings[gId].Prefixes.Count < 25)
@@ -65,12 +60,10 @@ namespace StarsiegeBot
await ctx.RespondAsync("There is a maximum of 25 prefixes allowed."); await ctx.RespondAsync("There is a maximum of 25 prefixes allowed.");
} }
} }
[Command("delete"), Aliases("del")] [Command("delete"), Aliases("del")]
[Description("Removes the specified prefix from accepted prefixes.")] [Description("Removes the specified prefix from accepted prefixes.")]
public async Task RemovePrefix(CommandContext ctx, string prefix) public async Task RemovePrefix(CommandContext ctx, string prefix)
{ {
await ctx.TriggerTypingAsync();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
// they have only one prefix and disallow global prefixes, dont let them delete the prefix. // they have only one prefix and disallow global prefixes, dont let them delete the prefix.
if (GuildSettings[gId].Prefixes.Count == 1 && !GuildSettings[gId].UseGlobalPrefix) if (GuildSettings[gId].Prefixes.Count == 1 && !GuildSettings[gId].UseGlobalPrefix)
@@ -82,19 +75,16 @@ namespace StarsiegeBot
GuildSettings[ctx.Guild.Id.ToString()].Prefixes.Remove(prefix); GuildSettings[ctx.Guild.Id.ToString()].Prefixes.Remove(prefix);
await ctx.RespondAsync($"Removed `{prefix}` as a command prefix."); await ctx.RespondAsync($"Removed `{prefix}` as a command prefix.");
} }
[Command("global")] [Command("global")]
[Description("View or edit the status of allowing Global Prefix(es).")] [Description("View or edit the status of allowing Global Prefix(es).")]
public async Task UseGlobalPrefixes(CommandContext ctx) public async Task UseGlobalPrefixes(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
await ctx.RespondAsync($"Global Prefix usage has been turned **{(GuildSettings[ctx.Guild.Id.ToString()].UseGlobalPrefix ? "on" : "off")}**"); await ctx.RespondAsync($"Global Prefix usage has been turned **{(GuildSettings[ctx.Guild.Id.ToString()].UseGlobalPrefix ? "on" : "off")}**");
} }
[Command("global"), Aliases("g")] [Command("global"), Aliases("g")]
[Description("View or edit the status of allowing Global Prefix(es).")] [Description("View or edit the status of allowing Global Prefix(es).")]
public async Task UseGlobalPrefixes(CommandContext ctx, [Description("True or False")] bool isEnabled) public async Task UseGlobalPrefixes(CommandContext ctx, [Description("True or False")] bool isEnabled)
{ {
await ctx.TriggerTypingAsync();
// check to make sure that they aren't trying to turn off global prefixes with out first adding a server sepcific prefix. // check to make sure that they aren't trying to turn off global prefixes with out first adding a server sepcific prefix.
int prefixCount = GuildSettings[ctx.Guild.Id.ToString()].Prefixes.Count; int prefixCount = GuildSettings[ctx.Guild.Id.ToString()].Prefixes.Count;
if (prefixCount <= 0 && !isEnabled) if (prefixCount <= 0 && !isEnabled)
@@ -109,7 +99,6 @@ namespace StarsiegeBot
[Command("global")] [Command("global")]
public async Task UseGlobalPrefixes(CommandContext ctx, [Description("ON or OFF"), RemainingText] string isEnabled = null) public async Task UseGlobalPrefixes(CommandContext ctx, [Description("ON or OFF"), RemainingText] string isEnabled = null)
{ {
await ctx.TriggerTypingAsync();
isEnabled = isEnabled.ToLower(); isEnabled = isEnabled.ToLower();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
int prefixCount = GuildSettings[gId].Prefixes.Count; int prefixCount = GuildSettings[gId].Prefixes.Count;
@@ -138,11 +127,9 @@ namespace StarsiegeBot
} }
else else
{ {
} }
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
private DiscordEmbedBuilder StartEmbed(string desc) private DiscordEmbedBuilder StartEmbed(string desc)
{ {
DiscordEmbedBuilder embed = new DiscordEmbedBuilder DiscordEmbedBuilder embed = new DiscordEmbedBuilder
+35 -42
View File
@@ -11,7 +11,6 @@ using System;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
class Program class Program
@@ -26,12 +25,10 @@ namespace StarsiegeBot
DiscordColor.Rose, DiscordColor.SapGreen, DiscordColor.Sienna, DiscordColor.SpringGreen, DiscordColor.Teal, DiscordColor.Turquoise, DiscordColor.VeryDarkGray, DiscordColor.Rose, DiscordColor.SapGreen, DiscordColor.Sienna, DiscordColor.SpringGreen, DiscordColor.Teal, DiscordColor.Turquoise, DiscordColor.VeryDarkGray,
DiscordColor.Violet, DiscordColor.Wheat, DiscordColor.White, DiscordColor.Yellow, DiscordColor.Red }; DiscordColor.Violet, DiscordColor.Wheat, DiscordColor.White, DiscordColor.Yellow, DiscordColor.Red };
public static readonly Random rnd = new Random(); public static readonly Random rnd = new Random();
public DiscordClient Client { get; set; } public DiscordClient Client { get; set; }
public CommandsNextExtension Commands { get; set; } public CommandsNextExtension Commands { get; set; }
public VoiceNextExtension Voice { get; set; } public VoiceNextExtension Voice { get; set; }
public string BotName { get; protected set; } public string BotName { get; protected set; }
public static void Main(string[] args) public static void Main(string[] args)
{ {
// since we cannot make the entry method asynchronous, // since we cannot make the entry method asynchronous,
@@ -42,89 +39,90 @@ namespace StarsiegeBot
GetAwaiter(). GetAwaiter().
GetResult(); GetResult();
} }
public Program(string[] args) public Program(string[] args)
{ {
if (args.Length > 0) if (args.Length > 0)
BotName = args[0].ToLower(); BotName = args[0].ToLower();
else else
BotName = "sspdev"; BotName = "sspdev";
BotEventId = new EventId(276, BotName); BotEventId = new EventId(276, BotName);
Events = new Triggers(BotEventId); Events = new Triggers(BotEventId);
} }
public async Task RunBotAsync() public async Task RunBotAsync()
{ {
// next, let's load the values from that file // next, let's load the values from that file
// to our client's configuration // to our client's configuration
var cfg = new DiscordConfiguration var cfg = new DiscordConfiguration
{ {
Token = Environment.GetEnvironmentVariable(BotName + "Token"), Token = Environment.GetEnvironmentVariable(BotName + "Token"),
TokenType = TokenType.Bot, TokenType = TokenType.Bot,
AutoReconnect = true, AutoReconnect = true,
MinimumLogLevel = LogLevel.Debug, MinimumLogLevel = LogLevel.Debug,
Intents = DiscordIntents.All, Intents = DiscordIntents.All,
}; };
// then we want to instantiate our client // then we want to instantiate our client
Client = new DiscordClient(cfg); Client = new DiscordClient(cfg);
// next, let's hook some events, so we know // next, let's hook some events, so we know
// what's going on // what's going on
Client.UseInteractivity(new InteractivityConfiguration() Client.UseInteractivity(new InteractivityConfiguration()
{ {
PollBehaviour = PollBehaviour.KeepEmojis, PollBehaviour = PollBehaviour.KeepEmojis,
Timeout = TimeSpan.FromSeconds(15) Timeout = TimeSpan.FromSeconds(15)
}); });
// up next, let's set up our commands // up next, let's set up our commands
var ccfg = new CommandsNextConfiguration var ccfg = new CommandsNextConfiguration
{ {
// let's use the string prefix defined in config.json // let's use the string prefix defined in config.json
StringPrefixes = new[] { Environment.GetEnvironmentVariable("CommandPrefix") }, StringPrefixes = new[] { Environment.GetEnvironmentVariable("CommandPrefix") },
// enable responding in direct messages // enable responding in direct messages
EnableDms = true, EnableDms = true,
// enable mentioning the bot as a command prefix // enable mentioning the bot as a command prefix
EnableMentionPrefix = true, EnableMentionPrefix = true,
UseDefaultCommandHandler = false UseDefaultCommandHandler = false
}; };
// and hook them up // and hook them up
Commands = Client.UseCommandsNext(ccfg); Commands = Client.UseCommandsNext(ccfg);
// up next, let's register our commands // up next, let's register our commands
// These commands are available to all bots.
Commands.RegisterCommands<BotSettings>(); // Main Folder. Test Items. Commands.RegisterCommands<BotSettings>(); // Main Folder. Test Items.
Commands.RegisterCommands<ExperiemntalCommands>(); // Experimental commands file.
Commands.RegisterCommands<GameCommands>();
Commands.RegisterCommands<GroupManagement>(); // Main Folder. Test Items.
Commands.RegisterCommands<GroupRoleManagement>(); // Main Folder. Test Items.
Commands.RegisterCommands<LevelManagement>(); // Main Folder. Test Items.
Commands.RegisterCommands<LevelRoleManagement>(); // Main Folder. Test Items.
Commands.RegisterCommands<NotFacts>(); // Raven Folder.
Commands.RegisterCommands<PrefixManagement>(); Commands.RegisterCommands<PrefixManagement>();
Commands.RegisterCommands<RoleManagement>(); // Main Folder. Test Items. // These are in-dev commands. Experimental, may break things.
Commands.RegisterCommands<SnappleFacts>(); // Raven folder. if (BotName.Contains("sspdev"))
Commands.RegisterCommands<WelcomeMessage>(); // Main Folder. Test Items. {
Commands.RegisterCommands<ExperiemntalCommands>(); // Experimental commands file.
}
// These are bot specific.
if (BotName.Contains("ssp") || BotName.Contains("phoenix"))
{
Commands.RegisterCommands<WelcomeMessage>(); // Main Folder. Test Items.
}
// Server management options, reserved for PhoenixBot
if (BotName.Contains("phoenix"))
{
Commands.RegisterCommands<GroupManagement>(); // Main Folder. Test Items.
Commands.RegisterCommands<GroupRoleManagement>(); // Main Folder. Test Items.
Commands.RegisterCommands<LevelManagement>(); // Main Folder. Test Items.
Commands.RegisterCommands<LevelRoleManagement>(); // Main Folder. Test Items.
Commands.RegisterCommands<RoleManagement>(); // Main Folder. Test Items.
}
// Game related, commands of luck. Pure entertainment commands. Reserved for RavenBot.
if (BotName.Contains("raven"))
{
Commands.RegisterCommands<GameCommands>();
Commands.RegisterCommands<NotFacts>(); // Raven Folder.
Commands.RegisterCommands<SnappleFacts>(); // Raven folder.
}
// All these commands are in the STARSIEGE folder. // All these commands are in the STARSIEGE folder.
//if (BotName.Contains("ssp")) // Commands for the Starsiege Players bot, on the Starsiege Server.
//{ if (BotName.Contains("ssp"))
Commands.RegisterCommands<QuickchatHandler>(); {
Commands.RegisterCommands<Functions>(); Commands.RegisterCommands<QuickchatHandler>();
Commands.RegisterCommands<DeathMessages>(); Commands.RegisterCommands<Functions>();
Commands.RegisterCommands<GameInfo>(); Commands.RegisterCommands<DeathMessages>();
//} Commands.RegisterCommands<GameInfo>();
}
// let's enable voice // let's enable voice
Voice = Client.UseVoiceNext(); Voice = Client.UseVoiceNext();
// Hook all possible Event Handlers in the system. // Hook all possible Event Handlers in the system.
Client.ChannelCreated += Events.ChannelCreated; Client.ChannelCreated += Events.ChannelCreated;
Client.ChannelDeleted += Events.ChannelDeleted; Client.ChannelDeleted += Events.ChannelDeleted;
@@ -180,24 +178,19 @@ namespace StarsiegeBot
Client.InteractionCreated += Events.InteractionCreated; Client.InteractionCreated += Events.InteractionCreated;
Commands.CommandExecuted += Events.CommandExecuted; Commands.CommandExecuted += Events.CommandExecuted;
Commands.CommandErrored += Events.CommandErrored; Commands.CommandErrored += Events.CommandErrored;
// finally, let's connect and log in // finally, let's connect and log in
await Client.ConnectAsync(); await Client.ConnectAsync();
// and this is to prevent premature quitting // and this is to prevent premature quitting
await Task.Delay(-1); await Task.Delay(-1);
} }
// this structure will hold data from config.json // this structure will hold data from config.json
public struct ConfigJson public struct ConfigJson
{ {
[JsonProperty("token")] [JsonProperty("token")]
public string Token { get; private set; } public string Token { get; private set; }
[JsonProperty("prefix")] [JsonProperty("prefix")]
public string CommandPrefix { get; private set; } public string CommandPrefix { get; private set; }
} }
public static string YesNo(bool test) public static string YesNo(bool test)
{ {
return (test ? "Enabled" : "Disabled"); return (test ? "Enabled" : "Disabled");
-14
View File
@@ -7,8 +7,6 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("notfact")] [Group("notfact")]
@@ -17,19 +15,16 @@ namespace StarsiegeBot
private List<string> _notfacts; private List<string> _notfacts;
private bool _isEnabled; private bool _isEnabled;
private static readonly string s_fileName = "Json/notfacts.json"; private static readonly string s_fileName = "Json/notfacts.json";
public NotFacts() public NotFacts()
{ {
Console.WriteLine("NotFacts Command Loaded"); Console.WriteLine("NotFacts Command Loaded");
_isEnabled = Load(); _isEnabled = Load();
} }
[GroupCommand, Description("Get a NotFact")] [GroupCommand, Description("Get a NotFact")]
public async Task NotFact(CommandContext ctx, [Description("[Optional] A NotFact ID")] int notFactID = 0) public async Task NotFact(CommandContext ctx, [Description("[Optional] A NotFact ID")] int notFactID = 0)
{ {
if (!_isEnabled) if (!_isEnabled)
return; return;
await ctx.TriggerTypingAsync();
string output; string output;
notFactID--; notFactID--;
try try
@@ -42,21 +37,17 @@ namespace StarsiegeBot
} }
await ctx.RespondAsync(StartEmbed(output)); await ctx.RespondAsync(StartEmbed(output));
} }
[Command("count"), Aliases("c"), Description("Get a count of the NotFacts")] [Command("count"), Aliases("c"), Description("Get a count of the NotFacts")]
public async Task NotFactCount(CommandContext ctx) public async Task NotFactCount(CommandContext ctx)
{ {
if (!_isEnabled) if (!_isEnabled)
return; return;
await ctx.TriggerTypingAsync();
await ctx.RespondAsync(StartEmbed(_notfacts.Count + " NotFacts in the NotFacts Bank")); await ctx.RespondAsync(StartEmbed(_notfacts.Count + " NotFacts in the NotFacts Bank"));
} }
[Command("load"), RequireOwner, Aliases("l")] [Command("load"), RequireOwner, Aliases("l")]
public async Task Load(CommandContext ctx) public async Task Load(CommandContext ctx)
{ {
// trigger the typing. // trigger the typing.
await ctx.TriggerTypingAsync();
// start the response. // start the response.
DiscordEmbedBuilder embed = StartEmbed("Reloading NotFacts"); DiscordEmbedBuilder embed = StartEmbed("Reloading NotFacts");
// our old setting... // our old setting...
@@ -71,12 +62,10 @@ namespace StarsiegeBot
// send our results. // send our results.
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
[Command("toggle"), RequireOwner, Aliases("t")] [Command("toggle"), RequireOwner, Aliases("t")]
public async Task Enable(CommandContext ctx, [RemainingText] string isEnabled = null) public async Task Enable(CommandContext ctx, [RemainingText] string isEnabled = null)
{ {
// trigger the typing. // trigger the typing.
await ctx.TriggerTypingAsync();
// lower case teh input. // lower case teh input.
isEnabled = isEnabled.ToLower(); isEnabled = isEnabled.ToLower();
string[] turnOn = { "on", "true", "1" }; string[] turnOn = { "on", "true", "1" };
@@ -114,8 +103,6 @@ namespace StarsiegeBot
} }
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
private DiscordEmbedBuilder StartEmbed(string desc) private DiscordEmbedBuilder StartEmbed(string desc)
{ {
DiscordEmbedBuilder embed = new DiscordEmbedBuilder DiscordEmbedBuilder embed = new DiscordEmbedBuilder
@@ -125,7 +112,6 @@ namespace StarsiegeBot
}; };
return embed; return embed;
} }
private bool Load() private bool Load()
{ {
bool ret; bool ret;
-13
View File
@@ -7,8 +7,6 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("snapple"), Aliases("snap")] [Group("snapple"), Aliases("snap")]
@@ -17,13 +15,11 @@ namespace StarsiegeBot
private List<string> _facts; private List<string> _facts;
private bool _isEnabled; private bool _isEnabled;
private static readonly string s_fileName = "Json/snapple.json"; private static readonly string s_fileName = "Json/snapple.json";
public SnappleFacts() public SnappleFacts()
{ {
Console.WriteLine("Snapple Commands Loaded"); Console.WriteLine("Snapple Commands Loaded");
_isEnabled = Load(); _isEnabled = Load();
} }
[GroupCommand, Description("Get a Snapple \"Real Fact\".")] [GroupCommand, Description("Get a Snapple \"Real Fact\".")]
public async Task Snapplefact(CommandContext ctx, [Description("[Optional] A Snapple Fact ID")] int snapId = 0) public async Task Snapplefact(CommandContext ctx, [Description("[Optional] A Snapple Fact ID")] int snapId = 0)
{ {
@@ -31,7 +27,6 @@ namespace StarsiegeBot
if (!_isEnabled) if (!_isEnabled)
return; return;
// trigger typing. // trigger typing.
await ctx.TriggerTypingAsync();
// store our output. // store our output.
string output; string output;
// @neo, why is this here? // @neo, why is this here?
@@ -49,22 +44,18 @@ namespace StarsiegeBot
// give them what they want. // give them what they want.
await ctx.RespondAsync(StartEmbed(output)); await ctx.RespondAsync(StartEmbed(output));
} }
[Command("count"), Description("Get a Snapple \"Real Fact\"."), Aliases("c")] [Command("count"), Description("Get a Snapple \"Real Fact\"."), Aliases("c")]
public async Task SnappleCount(CommandContext ctx) public async Task SnappleCount(CommandContext ctx)
{ {
if (!_isEnabled) if (!_isEnabled)
return; return;
await ctx.TriggerTypingAsync();
// trigger the typing, and report how many facts are in teh bank. // trigger the typing, and report how many facts are in teh bank.
await ctx.RespondAsync(StartEmbed(_facts.Count + " facts in the Snapple \"Real Facts\" Bank")); await ctx.RespondAsync(StartEmbed(_facts.Count + " facts in the Snapple \"Real Facts\" Bank"));
} }
[Command("load"), RequireOwner, Aliases("l")] [Command("load"), RequireOwner, Aliases("l")]
public async Task Load(CommandContext ctx) public async Task Load(CommandContext ctx)
{ {
// trigger the typing. // trigger the typing.
await ctx.TriggerTypingAsync();
// start the response. // start the response.
DiscordEmbedBuilder embed = StartEmbed("Reloading Snapple Facts"); DiscordEmbedBuilder embed = StartEmbed("Reloading Snapple Facts");
// our old setting... // our old setting...
@@ -79,12 +70,10 @@ namespace StarsiegeBot
// send our results. // send our results.
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
[Command("toggle"), RequireOwner, Aliases("t")] [Command("toggle"), RequireOwner, Aliases("t")]
public async Task Enable(CommandContext ctx, [RemainingText] string isEnabled = null) public async Task Enable(CommandContext ctx, [RemainingText] string isEnabled = null)
{ {
// trigger the typing. // trigger the typing.
await ctx.TriggerTypingAsync();
// lower case teh input. // lower case teh input.
isEnabled = isEnabled.ToLower(); isEnabled = isEnabled.ToLower();
string[] turnOn = { "on", "true", "1" }; string[] turnOn = { "on", "true", "1" };
@@ -122,7 +111,6 @@ namespace StarsiegeBot
} }
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
private DiscordEmbedBuilder StartEmbed(string desc) private DiscordEmbedBuilder StartEmbed(string desc)
{ {
DiscordEmbedBuilder embed = new DiscordEmbedBuilder DiscordEmbedBuilder embed = new DiscordEmbedBuilder
@@ -132,7 +120,6 @@ namespace StarsiegeBot
}; };
return embed; return embed;
} }
private bool Load() private bool Load()
{ {
bool ret; bool ret;
-14
View File
@@ -10,7 +10,6 @@ using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot.Raven namespace StarsiegeBot.Raven
{ {
class TriviaHandler : BaseCommandModule class TriviaHandler : BaseCommandModule
@@ -26,33 +25,25 @@ namespace StarsiegeBot.Raven
json = sr.ReadToEnd(); json = sr.ReadToEnd();
Dictionary<string, Questions> tempQC = JsonConvert.DeserializeObject<Dictionary<string, Questions>>(json); Dictionary<string, Questions> tempQC = JsonConvert.DeserializeObject<Dictionary<string, Questions>>(json);
_quizQuestions = Enumerable.ToList(tempQC.Values); _quizQuestions = Enumerable.ToList(tempQC.Values);
} }
[Command("quiz")] [Command("quiz")]
[Hidden] [Hidden]
[Description("")] [Description("")]
public async Task Quiz(CommandContext ctx) public async Task Quiz(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
DiscordEmbedBuilder embed = new DiscordEmbedBuilder(); DiscordEmbedBuilder embed = new DiscordEmbedBuilder();
int[] ids = { Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count) }; int[] ids = { Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count), Program.rnd.Next(_quizQuestions.Count) };
int selection = Program.rnd.Next(ids.Length); int selection = Program.rnd.Next(ids.Length);
int mainId = ids[selection]; int mainId = ids[selection];
string[] options = { "a", "b", "c", "d" }; string[] options = { "a", "b", "c", "d" };
var correctAnswer = DiscordEmoji.FromName(ctx.Client, $":regional_indicator_{options[selection]}:"); var correctAnswer = DiscordEmoji.FromName(ctx.Client, $":regional_indicator_{options[selection]}:");
Questions myQuestion = _quizQuestions[mainId]; Questions myQuestion = _quizQuestions[mainId];
embed.Description = myQuestion.Question; embed.Description = myQuestion.Question;
embed.AddField($":regional_indicator_{options[0]}:", _quizQuestions[ids[0]].Answers[Program.rnd.Next(_quizQuestions[ids[0]].Answers.Length)], true); embed.AddField($":regional_indicator_{options[0]}:", _quizQuestions[ids[0]].Answers[Program.rnd.Next(_quizQuestions[ids[0]].Answers.Length)], true);
embed.AddField($":regional_indicator_{options[1]}:", _quizQuestions[ids[1]].Answers[Program.rnd.Next(_quizQuestions[ids[1]].Answers.Length)], true); embed.AddField($":regional_indicator_{options[1]}:", _quizQuestions[ids[1]].Answers[Program.rnd.Next(_quizQuestions[ids[1]].Answers.Length)], true);
embed.AddField("_ _", "_ _", false); embed.AddField("_ _", "_ _", false);
embed.AddField($":regional_indicator_{options[2]}:", _quizQuestions[ids[2]].Answers[Program.rnd.Next(_quizQuestions[ids[2]].Answers.Length)], true); embed.AddField($":regional_indicator_{options[2]}:", _quizQuestions[ids[2]].Answers[Program.rnd.Next(_quizQuestions[ids[2]].Answers.Length)], true);
embed.AddField($":regional_indicator_{options[3]}:", _quizQuestions[ids[3]].Answers[Program.rnd.Next(_quizQuestions[ids[3]].Answers.Length)], true); embed.AddField($":regional_indicator_{options[3]}:", _quizQuestions[ids[3]].Answers[Program.rnd.Next(_quizQuestions[ids[3]].Answers.Length)], true);
DiscordMessage message = await ctx.RespondAsync(embed); DiscordMessage message = await ctx.RespondAsync(embed);
foreach (string item in options) foreach (string item in options)
{ {
@@ -67,14 +58,12 @@ namespace StarsiegeBot.Raven
} }
else await ctx.RespondAsync("Sorry, time ran out!"); else await ctx.RespondAsync("Sorry, time ran out!");
} }
[Command("test")] [Command("test")]
[Hidden] [Hidden]
public async Task CollectionCommand(CommandContext ctx) public async Task CollectionCommand(CommandContext ctx)
{ {
DiscordMessage message = await ctx.RespondAsync("React here!"); DiscordMessage message = await ctx.RespondAsync("React here!");
var reactions = await message.CollectReactionsAsync(); var reactions = await message.CollectReactionsAsync();
var strBuilder = new StringBuilder(); var strBuilder = new StringBuilder();
Dictionary<DiscordUser, bool> winners = new Dictionary<DiscordUser, bool>(); Dictionary<DiscordUser, bool> winners = new Dictionary<DiscordUser, bool>();
Dictionary<DiscordUser, bool> losers = new Dictionary<DiscordUser, bool>(); Dictionary<DiscordUser, bool> losers = new Dictionary<DiscordUser, bool>();
@@ -100,17 +89,14 @@ namespace StarsiegeBot.Raven
winners.Remove(pair.Key); winners.Remove(pair.Key);
} }
} }
strBuilder.AppendLine("Winners are:"); strBuilder.AppendLine("Winners are:");
foreach (KeyValuePair<DiscordUser, bool> item in winners) foreach (KeyValuePair<DiscordUser, bool> item in winners)
{ {
strBuilder.AppendLine(item.Key.Mention); strBuilder.AppendLine(item.Key.Mention);
} }
await ctx.RespondAsync(strBuilder.ToString()); await ctx.RespondAsync(strBuilder.ToString());
} }
} }
public class Questions public class Questions
{ {
[JsonProperty("question")] [JsonProperty("question")]
+13 -44
View File
@@ -10,19 +10,16 @@ using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("deathmessage"), Aliases("dm")] [Group("deathmessage"), Aliases("dm")]
[Description("Gives a random death message. Or interacts with the death messages.")] [Description("Gives a random death message. Or interacts with the death messages.")]
[Cooldown(1, 2, CooldownBucketType.Guild)] [Cooldown(1, 2, CooldownBucketType.Guild)]
class DeathMessages : BaseCommandModule class DeathMessages : BaseCommandModule
{ {
private DeathMessageLines _dmLines; private DeathMessageLines _dmLines;
private bool _deathMessagesEnabled; private bool _isEnabled;
private static readonly string s_fileName = "Json/deathmessages.json"; private static readonly string s_fileName = "Json/deathmessages.json";
public DeathMessages() public DeathMessages()
{ {
Console.WriteLine("Death Message Commands Loaded."); Console.WriteLine("Death Message Commands Loaded.");
@@ -38,21 +35,19 @@ namespace StarsiegeBot
// Decode the JSON and set it to dmLines. // Decode the JSON and set it to dmLines.
_dmLines = JsonConvert.DeserializeObject<DeathMessageLines>(json); _dmLines = JsonConvert.DeserializeObject<DeathMessageLines>(json);
// Enable all the commands. // Enable all the commands.
_deathMessagesEnabled = true; _isEnabled = true;
} }
else else
{ {
// Echo out that we're missing a file. Disable the commands due to that. // Echo out that we're missing a file. Disable the commands due to that.
Console.WriteLine($" --- --- --- --- {s_fileName} is missing"); Console.WriteLine($" --- --- --- --- {s_fileName} is missing");
_deathMessagesEnabled = false; _isEnabled = false;
} }
} }
[Command("load")] [Command("load")]
[RequireOwner] [RequireOwner]
public async Task LoadDeathMessages(CommandContext ctx) public async Task LoadDeathMessages(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
if (File.Exists(s_fileName)) if (File.Exists(s_fileName))
{ {
// set some JSON text to blank. // set some JSON text to blank.
@@ -63,68 +58,56 @@ namespace StarsiegeBot
// Decode the JSON and set it to dmLines. // Decode the JSON and set it to dmLines.
_dmLines = JsonConvert.DeserializeObject<DeathMessageLines>(json); _dmLines = JsonConvert.DeserializeObject<DeathMessageLines>(json);
// Enable all the commands. // Enable all the commands.
_deathMessagesEnabled = true; _isEnabled = true;
await ctx.RespondAsync("Loading Death Messages successul."); await ctx.RespondAsync("Loading Death Messages successul.");
} }
else else
{ {
// Echo out that we're missing a file. Disable the commands due to that. // Echo out that we're missing a file. Disable the commands due to that.
await ctx.RespondAsync("Can't load Death Messages. File missing."); await ctx.RespondAsync("Can't load Death Messages. File missing.");
_deathMessagesEnabled = false; _isEnabled = false;
} }
} }
[Command("toggle"), Aliases("t")] [Command("toggle"), Aliases("t")]
[RequireOwner] [RequireOwner]
public async Task ToggleDM(CommandContext ctx, [RemainingText] string isEnabled = null) public async Task ToggleDM(CommandContext ctx, [RemainingText] string isEnabled = null)
{ {
await ctx.TriggerTypingAsync();
isEnabled = isEnabled.ToLower(); isEnabled = isEnabled.ToLower();
string output; string output;
string[] turnOn = { "on", "true", "1" }; string[] turnOn = { "on", "true", "1" };
string[] turnOff = { "off", "false", "0" }; string[] turnOff = { "off", "false", "0" };
if (File.Exists(s_fileName)) if (File.Exists(s_fileName))
{ {
if (turnOn.Contains(isEnabled)) if (turnOn.Contains(isEnabled))
{ {
_deathMessagesEnabled = true; _isEnabled = true;
} }
else if (turnOff.Contains(isEnabled)) else if (turnOff.Contains(isEnabled))
{ {
_deathMessagesEnabled = false; _isEnabled = false;
} }
else else
{ {
} }
output = $"DeathMessages Enabled: {_deathMessagesEnabled}"; output = $"DeathMessages Enabled: {_isEnabled}";
} }
else else
{ {
_deathMessagesEnabled = false; _isEnabled = false;
output = $"{s_fileName} file is missing, and it can not be enabled."; output = $"{s_fileName} file is missing, and it can not be enabled.";
} }
await ctx.RespondAsync(output); await ctx.RespondAsync(output);
} }
[GroupCommand] [GroupCommand]
public async Task DeathMessage(CommandContext ctx, [Description("Optional. Person you want to see kill you. If blank, will show generic death message.")] DiscordMember target = null) public async Task DeathMessage(CommandContext ctx, [Description("Optional. Person you want to see kill you. If blank, will show generic death message.")] DiscordMember target = null)
{ {
// We're typing! (In all honesty, this is just used to avoid the 'async task not using await' messages I get. // We're typing! (In all honesty, this is just used to avoid the 'async task not using await' messages I get.
await ctx.TriggerTypingAsync();
// IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that. // IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that.
// If disabled, let the person know the command set is disabled, and return. // If disabled, let the person know the command set is disabled, and return.
if (!_deathMessagesEnabled) if (!_isEnabled)
{ {
await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return; return;
} }
// set some basic output incase something goes south. // set some basic output incase something goes south.
string line = "Something went wrong."; string line = "Something went wrong.";
// if there is no target, we're going to "kill" the author. // if there is no target, we're going to "kill" the author.
@@ -156,24 +139,21 @@ namespace StarsiegeBot
await ctx.RespondAsync(string.Format(line, ctx.Message.Author.Mention, target.Mention)); await ctx.RespondAsync(string.Format(line, ctx.Message.Author.Mention, target.Mention));
} }
} }
[Command("inventory"), Aliases("count")] [Command("inventory"), Aliases("count")]
[Description("Gets the total of each type of death message")] [Description("Gets the total of each type of death message")]
public async Task DeathMessageCount(CommandContext ctx) public async Task DeathMessageCount(CommandContext ctx)
{ {
// IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that. // IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that.
// If disabled, let the person know the command set is disabled, and return. // If disabled, let the person know the command set is disabled, and return.
if (!_deathMessagesEnabled) if (!_isEnabled)
{ {
await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners."); await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return; return;
} }
// We're typing here! // We're typing here!
await ctx.TriggerTypingAsync();
// List all the types of Death Message types, and how many we have of each one. // List all the types of Death Message types, and how many we have of each one.
await ctx.RespondAsync($"\r\nActive: {_dmLines.Active.Length}\r\nPassive: {_dmLines.Passive.Length}\r\nGeneric: {_dmLines.Generic.Length}"); await ctx.RespondAsync($"\r\nActive: {_dmLines.Active.Length}\r\nPassive: {_dmLines.Passive.Length}\r\nGeneric: {_dmLines.Generic.Length}");
} }
[Command("Add")] [Command("Add")]
[Description("Adds a message to the Pending Death Message Queue. Generic Death Messages require just a [Killed] while any other death message requires both a [Killed] and a [Killer] tags. These will be replaced with the correct information in game, and in the usage of random DM generation.")] [Description("Adds a message to the Pending Death Message Queue. Generic Death Messages require just a [Killed] while any other death message requires both a [Killed] and a [Killer] tags. These will be replaced with the correct information in game, and in the usage of random DM generation.")]
[Cooldown(1, 2, CooldownBucketType.Guild)] [Cooldown(1, 2, CooldownBucketType.Guild)]
@@ -181,15 +161,13 @@ namespace StarsiegeBot
{ {
// IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that. // IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that.
// If disabled, let the person know the command set is disabled, and return. // If disabled, let the person know the command set is disabled, and return.
if (!_deathMessagesEnabled) if (!_isEnabled)
{ {
await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners."); await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return; return;
} }
// Let Discord know we're typing. // Let Discord know we're typing.
await ctx.TriggerTypingAsync();
// Message the owner know some one wants to add a new death message, along with a code block to that message. // Message the owner know some one wants to add a new death message, along with a code block to that message.
// if the Queue is null, make it exist. // if the Queue is null, make it exist.
if (_dmLines.Queue is null) if (_dmLines.Queue is null)
_dmLines.Queue = new List<string>(); _dmLines.Queue = new List<string>();
@@ -200,34 +178,28 @@ namespace StarsiegeBot
// Tell the person that the message has been added to a 'queue'. // Tell the person that the message has been added to a 'queue'.
await ctx.RespondAsync("Your request has been added to the pending queue of requests."); await ctx.RespondAsync("Your request has been added to the pending queue of requests.");
} }
[Command("script")] [Command("script")]
[Description("Gets a script file for all the death messages on the bot.")] [Description("Gets a script file for all the death messages on the bot.")]
public async Task DeathMessagesScript(CommandContext ctx) public async Task DeathMessagesScript(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
// IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that. // IF we're missing the Death Messages dot JSON file, we're going to get disabled... Check for that.
// If disabled, let the person know the command set is disabled, and return. // If disabled, let the person know the command set is disabled, and return.
if (!_deathMessagesEnabled) if (!_isEnabled)
{ {
await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners."); await ctx.RespondAsync("Death Messages Commands have been disabled. Please contact the bot owners.");
return; return;
} }
// If this file exists... We could do one of two things. Delete it and remake it, or serve it up. // If this file exists... We could do one of two things. Delete it and remake it, or serve it up.
if (File.Exists("deathmessages.cs")) if (File.Exists("deathmessages.cs"))
{ {
File.Delete("deathmessages.cs"); File.Delete("deathmessages.cs");
} }
// We're going to remake it. Open it. // We're going to remake it. Open it.
using StreamWriter file = new StreamWriter("deathmessages.cs"); using StreamWriter file = new StreamWriter("deathmessages.cs");
// Write out the total lines for each. Requirement for Starsiege. // Write out the total lines for each. Requirement for Starsiege.
await file.WriteLineAsync($"$deathMessage::genericCount = {_dmLines.Generic.Length};"); await file.WriteLineAsync($"$deathMessage::genericCount = {_dmLines.Generic.Length};");
await file.WriteLineAsync($"$deathMessage::activeCount = {_dmLines.Active.Length};"); await file.WriteLineAsync($"$deathMessage::activeCount = {_dmLines.Active.Length};");
await file.WriteLineAsync($"$deathMessage::passiveCount = {_dmLines.Passive.Length};\r\n"); await file.WriteLineAsync($"$deathMessage::passiveCount = {_dmLines.Passive.Length};\r\n");
// Set count to 0. Iterate over each type of Death Message, and put it into the file. // Set count to 0. Iterate over each type of Death Message, and put it into the file.
int count = 0; int count = 0;
foreach (string death in _dmLines.Generic) foreach (string death in _dmLines.Generic)
@@ -249,10 +221,8 @@ namespace StarsiegeBot
await file.WriteLineAsync(string.Format($"$deathMessage::passive{count} = \"{death}\";", "%s", "%s")); await file.WriteLineAsync(string.Format($"$deathMessage::passive{count} = \"{death}\";", "%s", "%s"));
count++; count++;
} }
// We're done writing to it... So close the file. // We're done writing to it... So close the file.
file.Close(); file.Close();
// We're going to Message Build the response. // We're going to Message Build the response.
DiscordMessageBuilder msg = new DiscordMessageBuilder(); DiscordMessageBuilder msg = new DiscordMessageBuilder();
// Open the file to upload. // Open the file to upload.
@@ -266,7 +236,6 @@ namespace StarsiegeBot
// We're done with the file, so close access to it. // We're done with the file, so close access to it.
sound.Close(); sound.Close();
} }
private async Task StoreDeathMessages() private async Task StoreDeathMessages()
{ {
string output = JsonConvert.SerializeObject(_dmLines); string output = JsonConvert.SerializeObject(_dmLines);
-22
View File
@@ -10,7 +10,6 @@ using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("functions"), Aliases("func")] [Group("functions"), Aliases("func")]
@@ -22,7 +21,6 @@ namespace StarsiegeBot
public Functions() public Functions()
{ {
Console.WriteLine("Starsiege Function Commands Loaded"); Console.WriteLine("Starsiege Function Commands Loaded");
// Check for file, if not there, disable commands. // Check for file, if not there, disable commands.
if (File.Exists(s_fileName)) if (File.Exists(s_fileName))
{ {
@@ -40,18 +38,15 @@ namespace StarsiegeBot
Console.WriteLine(" --- --- --- Functions JSON not found."); Console.WriteLine(" --- --- --- Functions JSON not found.");
} }
} }
[GroupCommand] [GroupCommand]
[Description("Gives information on desired function.")] [Description("Gives information on desired function.")]
public async Task StarsiegeFunctions(CommandContext ctx, [RemainingText, Description("The function to attempt to look up.")] string command = "") public async Task StarsiegeFunctions(CommandContext ctx, [RemainingText, Description("The function to attempt to look up.")] string command = "")
{ {
await ctx.TriggerTypingAsync();
if (!_functionsEnabled) if (!_functionsEnabled)
{ {
await ctx.RespondAsync("Function Commands have been disabled. Please contact the bot owners."); await ctx.RespondAsync("Function Commands have been disabled. Please contact the bot owners.");
return; return;
} }
// If the function command is empty make a list of commands in Starsiege. // If the function command is empty make a list of commands in Starsiege.
if (command.Equals(string.Empty)) if (command.Equals(string.Empty))
{ {
@@ -76,7 +71,6 @@ namespace StarsiegeBot
// send the output. // send the output.
await ctx.RespondAsync("List of known Functions in Starsiege: " + output); await ctx.RespondAsync("List of known Functions in Starsiege: " + output);
} }
// we have a command the want to try to find. // we have a command the want to try to find.
else if (_ssFunctions.TryGetValue(command.ToLower(), out SSFunction outItem)) else if (_ssFunctions.TryGetValue(command.ToLower(), out SSFunction outItem))
{ {
@@ -106,12 +100,9 @@ namespace StarsiegeBot
await ctx.RespondAsync("That command wasn't food, pot-head."); await ctx.RespondAsync("That command wasn't food, pot-head.");
} }
} }
[Command("count")] [Command("count")]
public async Task FunctionCount(CommandContext ctx) public async Task FunctionCount(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
// check ot make sure these commands are enabled. if disabled, report it. // check ot make sure these commands are enabled. if disabled, report it.
if (!_functionsEnabled) if (!_functionsEnabled)
{ {
@@ -121,20 +112,14 @@ namespace StarsiegeBot
// they wanted to know how many functions were documented... so tell them! // they wanted to know how many functions were documented... so tell them!
await ctx.RespondAsync($"There are {_ssFunctions.Count} functions in the known list."); await ctx.RespondAsync($"There are {_ssFunctions.Count} functions in the known list.");
} }
[Command("toggle"), Aliases("t")] [Command("toggle"), Aliases("t")]
[RequireOwner] [RequireOwner]
public async Task ToggleFunctions(CommandContext ctx, [RemainingText] string isEnabled = null) public async Task ToggleFunctions(CommandContext ctx, [RemainingText] string isEnabled = null)
{ {
await ctx.TriggerTypingAsync();
isEnabled = isEnabled.ToLower(); isEnabled = isEnabled.ToLower();
string output; string output;
string[] turnOn = { "on", "true", "1" }; string[] turnOn = { "on", "true", "1" };
string[] turnOff = { "off", "false", "0" }; string[] turnOff = { "off", "false", "0" };
if (File.Exists(s_fileName)) if (File.Exists(s_fileName))
{ {
if (turnOn.Contains(isEnabled)) if (turnOn.Contains(isEnabled))
@@ -147,7 +132,6 @@ namespace StarsiegeBot
} }
else else
{ {
} }
output = $"Functions Enabled: {_functionsEnabled}"; output = $"Functions Enabled: {_functionsEnabled}";
} }
@@ -161,8 +145,6 @@ namespace StarsiegeBot
[Command("load"), RequireOwner] [Command("load"), RequireOwner]
public async Task LoadFunctions(CommandContext ctx) public async Task LoadFunctions(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
// Check for file, if not there, disable commands. // Check for file, if not there, disable commands.
if (File.Exists(s_fileName)) if (File.Exists(s_fileName))
{ {
@@ -182,14 +164,12 @@ namespace StarsiegeBot
} }
} }
} }
public class SSFunction public class SSFunction
{ {
public string name; public string name;
public string title; public string title;
public string description; public string description;
public Fields[] fields; public Fields[] fields;
public override string ToString() public override string ToString()
{ {
string fs = ""; string fs = "";
@@ -197,8 +177,6 @@ namespace StarsiegeBot
{ {
fs += $"[{field}] "; fs += $"[{field}] ";
} }
return $"Name: {name} || Title: {title} || Desc: {description} || Fields: {{{fs}}}"; return $"Name: {name} || Title: {title} || Desc: {description} || Fields: {{{fs}}}";
} }
} }
-10
View File
@@ -7,7 +7,6 @@ using System.Collections.Generic;
using System.Net; using System.Net;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("servers")] [Group("servers")]
@@ -42,7 +41,6 @@ namespace StarsiegeBot
[GroupCommand] [GroupCommand]
public async Task Overview(CommandContext ctx) public async Task Overview(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
Update(); Update();
// setup an exit point check. // setup an exit point check.
bool exit = false; bool exit = false;
@@ -65,12 +63,10 @@ namespace StarsiegeBot
embed.AddField("Errors", _gameData.Errors.Length.ToString(), true); embed.AddField("Errors", _gameData.Errors.Length.ToString(), true);
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
[Command("Errors"), Aliases("e")] [Command("Errors"), Aliases("e")]
[Description("Lists all the errors from the server listing.")] [Description("Lists all the errors from the server listing.")]
public async Task ErrorsServer(CommandContext ctx) public async Task ErrorsServer(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
Update(); Update();
// setup an exit point check. // setup an exit point check.
bool exit = false; bool exit = false;
@@ -93,12 +89,10 @@ namespace StarsiegeBot
} }
await ctx.RespondAsync(msg); await ctx.RespondAsync(msg);
} }
[Command("Masters"), Aliases("m")] [Command("Masters"), Aliases("m")]
[Description("Gives all the master servers as a script to be improted into `master.cs`.")] [Description("Gives all the master servers as a script to be improted into `master.cs`.")]
public async Task MasterServers(CommandContext ctx) public async Task MasterServers(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
Update(); Update();
// setup an exit point check. // setup an exit point check.
bool exit = false; bool exit = false;
@@ -124,12 +118,10 @@ namespace StarsiegeBot
msg.Content += "```"; msg.Content += "```";
await ctx.RespondAsync(msg); await ctx.RespondAsync(msg);
} }
[Command("games"), Aliases("g")] [Command("games"), Aliases("g")]
[Description("Currently: Lists games that have been started (Player dropped in). End Result: Lists all games that have a player in the server (either dropped in or not)")] [Description("Currently: Lists games that have been started (Player dropped in). End Result: Lists all games that have a player in the server (either dropped in or not)")]
public async Task GameServers(CommandContext ctx, [Description("Number of players you want to check for. Game servers will need at least this meaning or more to be listed.")] int playerCount = 1) public async Task GameServers(CommandContext ctx, [Description("Number of players you want to check for. Game servers will need at least this meaning or more to be listed.")] int playerCount = 1)
{ {
await ctx.TriggerTypingAsync();
Update(); Update();
playerCount = Math.Abs(playerCount); playerCount = Math.Abs(playerCount);
// setup an exit point check. // setup an exit point check.
@@ -174,7 +166,6 @@ namespace StarsiegeBot
[JsonProperty("games")] [JsonProperty("games")]
public GameServer[] Games { get; private set; } public GameServer[] Games { get; private set; }
} }
class MasterServer class MasterServer
{ {
[JsonProperty("address")] [JsonProperty("address")]
@@ -188,7 +179,6 @@ namespace StarsiegeBot
[JsonProperty("Ping")] [JsonProperty("Ping")]
public int Ping { get; private set; } public int Ping { get; private set; }
} }
class GameServer class GameServer
{ {
[JsonProperty("GameName")] [JsonProperty("GameName")]
@@ -10,7 +10,6 @@ using System.Linq;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Aliases("qc"), Group("quickchat")] [Aliases("qc"), Group("quickchat")]
@@ -19,14 +18,11 @@ namespace StarsiegeBot
private Dictionary<string, Quickchat> _quickchats; private Dictionary<string, Quickchat> _quickchats;
private bool _isEnabled; private bool _isEnabled;
private static readonly string s_fileName = "Json/quickchats.json"; private static readonly string s_fileName = "Json/quickchats.json";
public QuickchatHandler() public QuickchatHandler()
{ {
Console.WriteLine("Quick Chat Handler Loaded"); Console.WriteLine("Quick Chat Handler Loaded");
_isEnabled = LoadQuickChatsImpl(); _isEnabled = LoadQuickChatsImpl();
} }
/** /**
* LoadQuickChatsImpl loads the quickchats.json file from the current path, * LoadQuickChatsImpl loads the quickchats.json file from the current path,
* parses the file, and populates the private quickchats dictionary. * parses the file, and populates the private quickchats dictionary.
@@ -45,17 +41,14 @@ namespace StarsiegeBot
// enable the commands. // enable the commands.
return true; return true;
} }
// else, file not found. disable commands, leave a comment in console. // else, file not found. disable commands, leave a comment in console.
Console.WriteLine(" -- --- --- Quick Chat JSON file not found."); Console.WriteLine(" -- --- --- Quick Chat JSON file not found.");
return false; return false;
} }
[Command("load"), RequireOwner] [Command("load"), RequireOwner]
[Description("[Owner Only] Reloads the QuickChat files, if they exist. Also enables QC's if the file is found.")] [Description("[Owner Only] Reloads the QuickChat files, if they exist. Also enables QC's if the file is found.")]
public async Task LoadQuickChats(CommandContext ctx) public async Task LoadQuickChats(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
string output; string output;
_isEnabled = LoadQuickChatsImpl(); _isEnabled = LoadQuickChatsImpl();
if (_isEnabled) if (_isEnabled)
@@ -68,7 +61,6 @@ namespace StarsiegeBot
} }
await ctx.RespondAsync(StartEmbed(output)); await ctx.RespondAsync(StartEmbed(output));
} }
[Command("script")] [Command("script")]
[Description("Gives the `say()` for use in the Quickchat.cs file.")] [Description("Gives the `say()` for use in the Quickchat.cs file.")]
public async Task GetQuickChatScript(CommandContext ctx, [Description("ID of Quick chat to get script for.")] int index) public async Task GetQuickChatScript(CommandContext ctx, [Description("ID of Quick chat to get script for.")] int index)
@@ -79,11 +71,8 @@ namespace StarsiegeBot
return; return;
} }
// trigger some typing on discord's side. // trigger some typing on discord's side.
await ctx.TriggerTypingAsync();
// We're good to go... If we have an index, pull it up. // We're good to go... If we have an index, pull it up.
index = Math.Abs(index); index = Math.Abs(index);
// is our index within bounds? // is our index within bounds?
if (index < _quickchats.Count) if (index < _quickchats.Count)
{ {
@@ -92,11 +81,9 @@ namespace StarsiegeBot
await ctx.RespondAsync("```" + chat.ToString() + "```"); await ctx.RespondAsync("```" + chat.ToString() + "```");
return; return;
} }
// we couldn't find it... Oh well, let the end user know. // we couldn't find it... Oh well, let the end user know.
await ctx.RespondAsync("The ID specified is out of bounds. 0-" + (_quickchats.Count - 1)); await ctx.RespondAsync("The ID specified is out of bounds. 0-" + (_quickchats.Count - 1));
} }
[Command("check")] [Command("check")]
[Description("Runs a check to see how many WAV files are missing from all QC's.")] [Description("Runs a check to see how many WAV files are missing from all QC's.")]
public async Task QuickChatCheck(CommandContext ctx) public async Task QuickChatCheck(CommandContext ctx)
@@ -106,8 +93,6 @@ namespace StarsiegeBot
{ {
return; return;
} }
await ctx.TriggerTypingAsync();
// Start a count // Start a count
int missingFiles = 0; int missingFiles = 0;
for (int i = 0; i < _quickchats.Count; i++) for (int i = 0; i < _quickchats.Count; i++)
@@ -119,11 +104,9 @@ namespace StarsiegeBot
Console.Write($"{i}, "); Console.Write($"{i}, ");
} }
} }
// Reply to the message and let the user know we're missing X files. // Reply to the message and let the user know we're missing X files.
await ctx.RespondAsync(StartEmbed($"Missing files: {missingFiles}")); await ctx.RespondAsync(StartEmbed($"Missing files: {missingFiles}"));
} }
[GroupCommand] [GroupCommand]
[Description("Gives a specific or random Quickchat. If that QC has a sound file that the bot knows, uploads the sound file too.")] [Description("Gives a specific or random Quickchat. If that QC has a sound file that the bot knows, uploads the sound file too.")]
public async Task QuickChat(CommandContext ctx, [Description("The ID of the quick Chat.")] int id = -1) public async Task QuickChat(CommandContext ctx, [Description("The ID of the quick Chat.")] int id = -1)
@@ -133,14 +116,10 @@ namespace StarsiegeBot
{ {
return; return;
} }
await ctx.TriggerTypingAsync();
string output; string output;
// Start a new Message Build. // Start a new Message Build.
DiscordMessageBuilder msg = new DiscordMessageBuilder(); DiscordMessageBuilder msg = new DiscordMessageBuilder();
Quickchat chat; Quickchat chat;
// try to get the quick chat, if it doesn't exist, return a random one // try to get the quick chat, if it doesn't exist, return a random one
try try
{ {
@@ -169,43 +148,35 @@ namespace StarsiegeBot
break; break;
} }
} }
// If the sound file to the select QC exists, upload it as well. // If the sound file to the select QC exists, upload it as well.
msg.Embed = StartEmbed(output); msg.Embed = StartEmbed(output);
if (File.Exists($"./qc/{chat.SoundFile}")) if (File.Exists($"./qc/{chat.SoundFile}"))
{ {
// Open the file. // Open the file.
FileStream sound = new FileStream($"./qc/{chat.SoundFile}", FileMode.Open, FileAccess.Read); FileStream sound = new FileStream($"./qc/{chat.SoundFile}", FileMode.Open, FileAccess.Read);
// feed it to the Message Builder. // feed it to the Message Builder.
msg.WithFile(chat.SoundFile, sound); msg.WithFile(chat.SoundFile, sound);
} }
// Send either the text QC or sound file if we have it // Send either the text QC or sound file if we have it
// msg.Content = output; // msg.Content = output;
await ctx.RespondAsync(msg); await ctx.RespondAsync(msg);
} }
[Command("search"), Aliases("s")] [Command("search"), Aliases("s")]
[Cooldown(1, 5, CooldownBucketType.Global)] [Cooldown(1, 5, CooldownBucketType.Global)]
[Description("Searches all the [T]ext and [S]ound file names for the Search input.")] [Description("Searches all the [T]ext and [S]ound file names for the Search input.")]
public async Task SearchQuickChats(CommandContext ctx, [RemainingText, Description("What to search for.")] string toSearch) public async Task SearchQuickChats(CommandContext ctx, [RemainingText, Description("What to search for.")] string toSearch)
{ {
await ctx.TriggerTypingAsync();
string output; string output;
// If we're disabled, let them know. And exit out. // If we're disabled, let them know. And exit out.
if (!_isEnabled) if (!_isEnabled)
{ {
await ctx.RespondAsync("Quick Chat Commands have been disabled. Please contact the bot owners."); await ctx.RespondAsync("Quick Chat Commands have been disabled. Please contact the bot owners.");
return; return;
} }
// We're going to build a message. // We're going to build a message.
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
DiscordMessageBuilder msg = new DiscordMessageBuilder(); DiscordMessageBuilder msg = new DiscordMessageBuilder();
int count = 0; int count = 0;
// We're going to search each QC for the stuff in toSearch. // We're going to search each QC for the stuff in toSearch.
foreach (KeyValuePair<string, Quickchat> qc in _quickchats) foreach (KeyValuePair<string, Quickchat> qc in _quickchats)
{ {
@@ -223,7 +194,6 @@ namespace StarsiegeBot
count++; count++;
} }
} }
// If we have a message return it // If we have a message return it
if (sb.Length > 0) if (sb.Length > 0)
{ {
@@ -236,20 +206,15 @@ namespace StarsiegeBot
// If message content is still nothing, report we found nothing. // If message content is still nothing, report we found nothing.
output = $"Sorry {ctx.Member.Mention}, no results were found for `{toSearch}`."; output = $"Sorry {ctx.Member.Mention}, no results were found for `{toSearch}`.";
} }
msg.Content = output; msg.Content = output;
await ctx.RespondAsync(msg); await ctx.RespondAsync(msg);
} }
[Command("flag")] [Command("flag")]
[Description("Flags a Quick Chat for moderator checking.")] [Description("Flags a Quick Chat for moderator checking.")]
public async Task FlagQC(CommandContext ctx, [Description("ID of QC to flag.")] int id, [RemainingText, Description("The reason you believe it needs flagged.")] string flagReason = "") public async Task FlagQC(CommandContext ctx, [Description("ID of QC to flag.")] int id, [RemainingText, Description("The reason you believe it needs flagged.")] string flagReason = "")
{ {
await ctx.TriggerTypingAsync();
Quickchat chat = _quickchats[id.ToString()]; Quickchat chat = _quickchats[id.ToString()];
DiscordEmbedBuilder embed; DiscordEmbedBuilder embed;
foreach (FlagEvent item in chat.Flags) foreach (FlagEvent item in chat.Flags)
{ {
if (item.UserId == ctx.Member.Id) if (item.UserId == ctx.Member.Id)
@@ -273,14 +238,11 @@ namespace StarsiegeBot
chat.IsFlagged = true; chat.IsFlagged = true;
string output = JsonConvert.SerializeObject(_quickchats); string output = JsonConvert.SerializeObject(_quickchats);
await File.WriteAllTextAsync(s_fileName, output); await File.WriteAllTextAsync(s_fileName, output);
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
} }
[Command("flag-count")] [Command("flag-count")]
public async Task FlagCount(CommandContext ctx) public async Task FlagCount(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
int count = 0; int count = 0;
foreach (KeyValuePair<string, Quickchat> chat in _quickchats) foreach (KeyValuePair<string, Quickchat> chat in _quickchats)
{ {
@@ -291,18 +253,15 @@ namespace StarsiegeBot
} }
await ctx.RespondAsync(StartEmbed($"There are {count} flagged Quick Chats.")); await ctx.RespondAsync(StartEmbed($"There are {count} flagged Quick Chats."));
} }
[Command("toggle"), Aliases("t")] [Command("toggle"), Aliases("t")]
[RequireOwner] [RequireOwner]
[Description("[Owner only] Enables or disables, or checks status of QuickChats.\r\nTo turn the feature on, use `TRUE`, `ON`, or `1`\r\nTo turn off, use `FALSE`, `OFF`, or `0`")] [Description("[Owner only] Enables or disables, or checks status of QuickChats.\r\nTo turn the feature on, use `TRUE`, `ON`, or `1`\r\nTo turn off, use `FALSE`, `OFF`, or `0`")]
public async Task ToggleQC(CommandContext ctx, [RemainingText] string isEnabled = null) public async Task ToggleQC(CommandContext ctx, [RemainingText] string isEnabled = null)
{ {
await ctx.TriggerTypingAsync();
isEnabled = isEnabled.ToLower(); isEnabled = isEnabled.ToLower();
string output; string output;
string[] turnOn = { "on", "true", "1" }; string[] turnOn = { "on", "true", "1" };
string[] turnOff = { "off", "false", "0" }; string[] turnOff = { "off", "false", "0" };
if (File.Exists(s_fileName)) if (File.Exists(s_fileName))
{ {
if (turnOn.Contains(isEnabled)) if (turnOn.Contains(isEnabled))
@@ -313,7 +272,6 @@ namespace StarsiegeBot
{ {
_isEnabled = false; _isEnabled = false;
} }
output = $"Quickchats {(_isEnabled ? "Enabled" : "Disabled")}"; output = $"Quickchats {(_isEnabled ? "Enabled" : "Disabled")}";
} }
else else
@@ -323,7 +281,6 @@ namespace StarsiegeBot
} }
await ctx.RespondAsync(StartEmbed(output)); await ctx.RespondAsync(StartEmbed(output));
} }
private DiscordEmbedBuilder StartEmbed(string description) private DiscordEmbedBuilder StartEmbed(string description)
{ {
DiscordEmbedBuilder embed = new DiscordEmbedBuilder DiscordEmbedBuilder embed = new DiscordEmbedBuilder
@@ -334,7 +291,6 @@ namespace StarsiegeBot
return embed; return embed;
} }
} }
public class Quickchat public class Quickchat
{ {
[JsonProperty("text")] [JsonProperty("text")]
@@ -354,7 +310,6 @@ namespace StarsiegeBot
public ulong UserId { get; set; } public ulong UserId { get; set; }
public string Reason { get; set; } public string Reason { get; set; }
public string Timestamp { get; set; } public string Timestamp { get; set; }
public FlagEvent(ulong UserId, string Reason, string Timestamp) public FlagEvent(ulong UserId, string Reason, string Timestamp)
{ {
this.UserId = UserId; this.UserId = UserId;
+4 -44
View File
@@ -6,53 +6,22 @@ using DSharpPlus.Entities;
using System; using System;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace StarsiegeBot namespace StarsiegeBot
{ {
[Group("welcome")] [Group("welcome")]
[RequireGuild, [RequireGuild,
RequirePermissions(Permissions.ManageChannels), RequirePermissions(Permissions.ManageChannels),
Cooldown(1, 10, CooldownBucketType.Global),
RequireNsfw,
RequireBotPermissions(Permissions.AccessChannels)
//RequireBotPermissions(Permissions.AddReactions),
//RequireBotPermissions(Permissions.Administrator),
//RequireBotPermissions(Permissions.AttachFiles),
//RequireBotPermissions(Permissions.BanMembers),
//RequireBotPermissions(Permissions.ChangeNickname),
//RequireBotPermissions(Permissions.CreateInstantInvite),
//RequireBotPermissions(Permissions.DeafenMembers),
//RequireBotPermissions(Permissions.EmbedLinks),
//RequireBotPermissions(Permissions.KickMembers),
//RequireBotPermissions(Permissions.ManageChannels),
//RequireBotPermissions(Permissions.ManageEmojis),
//RequireBotPermissions(Permissions.ManageGuild),
//RequireBotPermissions(Permissions.ManageMessages),
//RequireBotPermissions(Permissions.ManageNicknames),
//RequireBotPermissions(Permissions.ManageRoles),
//RequireBotPermissions(Permissions.ManageWebhooks),
//RequireBotPermissions(Permissions.MentionEveryone),
//RequireBotPermissions(Permissions.MoveMembers),
//RequireBotPermissions(Permissions.MuteMembers),
//RequireBotPermissions(Permissions.PrioritySpeaker),
//RequireBotPermissions(Permissions.ReadMessageHistory),
//RequireBotPermissions(Permissions.SendMessages),
//RequireBotPermissions(Permissions.SendTtsMessages),
//RequireBotPermissions(Permissions.Speak),
//RequireBotPermissions(Permissions.Stream),
//RequireBotPermissions(Permissions.UseExternalEmojis),
//RequireBotPermissions(Permissions.UseVoice),
//RequireBotPermissions(Permissions.UseVoiceDetection),
//RequireBotPermissions(Permissions.ViewAuditLog)
] ]
class WelcomeMessage : BotSettings class WelcomeMessage : BotSettings
{ {
public WelcomeMessage()
{
Console.WriteLine("Welcome Message Handler Loaded.");
}
[GroupCommand] [GroupCommand]
public async Task GeneralWelcome(CommandContext ctx) public async Task GeneralWelcome(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
DiscordEmbedBuilder embed = StartEmbed("Welcome Message Info"); DiscordEmbedBuilder embed = StartEmbed("Welcome Message Info");
if (GuildSettings[gId].WelcomeChannel is null) if (GuildSettings[gId].WelcomeChannel is null)
embed.AddField("Channel", "*None*"); embed.AddField("Channel", "*None*");
@@ -80,9 +49,7 @@ namespace StarsiegeBot
[Command("enable")] [Command("enable")]
public async Task WelcomeEnabled(CommandContext ctx, bool enable) public async Task WelcomeEnabled(CommandContext ctx, bool enable)
{ {
await ctx.TriggerTypingAsync();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
DiscordEmbedBuilder embed = StartEmbed("Welcome Message Status"); DiscordEmbedBuilder embed = StartEmbed("Welcome Message Status");
embed.AddField("Old", GuildSettings[gId].UseWelcome.ToString(), true); embed.AddField("Old", GuildSettings[gId].UseWelcome.ToString(), true);
GuildSettings[gId].UseWelcome = enable; GuildSettings[gId].UseWelcome = enable;
@@ -92,7 +59,6 @@ namespace StarsiegeBot
[Command("Channel")] [Command("Channel")]
public async Task WelcomeChannel(CommandContext ctx, DiscordChannel channel) public async Task WelcomeChannel(CommandContext ctx, DiscordChannel channel)
{ {
await ctx.TriggerTypingAsync();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
DiscordEmbedBuilder embed = StartEmbed("Welcome Message Channel"); DiscordEmbedBuilder embed = StartEmbed("Welcome Message Channel");
if (GuildSettings[gId].WelcomeChannel != null) if (GuildSettings[gId].WelcomeChannel != null)
@@ -103,7 +69,6 @@ namespace StarsiegeBot
{ {
embed.AddField("Old", "*None*"); embed.AddField("Old", "*None*");
} }
GuildSettings[gId].WelcomeChannel = channel; GuildSettings[gId].WelcomeChannel = channel;
embed.AddField("New", GuildSettings[gId].WelcomeChannel.Mention, true); embed.AddField("New", GuildSettings[gId].WelcomeChannel.Mention, true);
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
@@ -111,7 +76,6 @@ namespace StarsiegeBot
[Command("Channel")] [Command("Channel")]
public async Task WelcomeChannel(CommandContext ctx, [RemainingText] string here) public async Task WelcomeChannel(CommandContext ctx, [RemainingText] string here)
{ {
await ctx.TriggerTypingAsync();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
DiscordEmbedBuilder embed = StartEmbed("Welcome Message Channel"); DiscordEmbedBuilder embed = StartEmbed("Welcome Message Channel");
if (GuildSettings[gId].WelcomeChannel != null) if (GuildSettings[gId].WelcomeChannel != null)
@@ -122,7 +86,6 @@ namespace StarsiegeBot
{ {
embed.AddField("Old", "*None*"); embed.AddField("Old", "*None*");
} }
GuildSettings[gId].WelcomeChannel = ctx.Channel; GuildSettings[gId].WelcomeChannel = ctx.Channel;
embed.AddField("New", GuildSettings[gId].WelcomeChannel.Mention, true); embed.AddField("New", GuildSettings[gId].WelcomeChannel.Mention, true);
await ctx.RespondAsync(embed); await ctx.RespondAsync(embed);
@@ -131,7 +94,6 @@ namespace StarsiegeBot
[Description("Hello. Run `>welcome help` for more info.")] [Description("Hello. Run `>welcome help` for more info.")]
public async Task MessageOfWelcome(CommandContext ctx, [RemainingText] string msg) public async Task MessageOfWelcome(CommandContext ctx, [RemainingText] string msg)
{ {
await ctx.TriggerTypingAsync();
string gId = ctx.Guild.Id.ToString(); string gId = ctx.Guild.Id.ToString();
DiscordEmbedBuilder embed = StartEmbed("Welcome Message String"); DiscordEmbedBuilder embed = StartEmbed("Welcome Message String");
if (GuildSettings[gId].WelcomeMessage == "" || GuildSettings[gId].WelcomeMessage is null) if (GuildSettings[gId].WelcomeMessage == "" || GuildSettings[gId].WelcomeMessage is null)
@@ -146,7 +108,6 @@ namespace StarsiegeBot
[Command("Help")] [Command("Help")]
public async Task WelcomeHelp(CommandContext ctx) public async Task WelcomeHelp(CommandContext ctx)
{ {
await ctx.TriggerTypingAsync();
DiscordEmbedBuilder embed = StartEmbed("List of placeholders and their intended replacement. Channel tags can be inserted without a placeholder."); DiscordEmbedBuilder embed = StartEmbed("List of placeholders and their intended replacement. Channel tags can be inserted without a placeholder.");
embed.Title = "Welcome Message Help"; embed.Title = "Welcome Message Help";
embed.AddField("[Discrim]", "Inserts the username of the member."); embed.AddField("[Discrim]", "Inserts the username of the member.");
@@ -164,7 +125,6 @@ namespace StarsiegeBot
.Replace("[mention]", member.Mention, StringComparison.OrdinalIgnoreCase); .Replace("[mention]", member.Mention, StringComparison.OrdinalIgnoreCase);
return output; return output;
} }
private DiscordEmbedBuilder StartEmbed(string desc) private DiscordEmbedBuilder StartEmbed(string desc)
{ {
DiscordEmbedBuilder embed = new DiscordEmbedBuilder DiscordEmbedBuilder embed = new DiscordEmbedBuilder