Esempio n. 1
0
        public async Task SendEmote(string trigger, IUser usr = null)
        {
            List <ApprovedEmote> foundEmotes = new List <ApprovedEmote>();
            bool hasNsfw = ((ITextChannel)Context.Channel).IsNsfw;
            bool hasUsr  = usr == null ? false : true;

            if (!hasUsr)
            {
                usr = Context.Client.CurrentUser;
            }
            if (Context.Message.Author.Id == usr.Id)
            {
                await Context.Channel.SendMessageAsync($"Why would you want to {trigger.ToLower()} yourself...?");

                return;
            }

            //Get all valid emotes for this trigger
            var list = hasNsfw ? GlobalVars.EmoteList.Values.Where(e => e.Trigger == trigger) : GlobalVars.EmoteList.Values.Where(e => e.Trigger == trigger && e.Nsfw == false);

            foreach (ApprovedEmote ae in list)
            {
                if (ae.RequiresTarget == hasUsr)
                {
                    foundEmotes.Add(ae);
                }
            }

            if (foundEmotes.Count > 0)
            {
                ApprovedEmote selected = foundEmotes[r.Next(0, foundEmotes.Count)];
                string        msg      = selected.OutputText;
                if (msg.ToLower().Contains("{author}"))
                {
                    msg = msg.Replace("{author}", Context.User.Username);
                }
                else
                {
                    msg = Context.User.Username + " " + msg;
                }
                if (usr != null)
                {
                    msg = msg.Replace("{target}", usr.Username);
                }
                await Context.Channel.SendFileAsync(selected.FilePath, "`" + msg + "`");

                var perms = Context.Guild.GetUser(Context.Client.CurrentUser.Id).GetPermissions(Context.Channel as IGuildChannel);
            }
            else
            {
                var prefix    = GlobalVars.GuildOptions.SingleOrDefault(go => go.GuildID == Context.Guild.Id).Prefix;
                var tarString = "\"{target}\"";
                var m         = await Context.Channel.SendMessageAsync($"Unknown emote, you can request this by using \n`{prefix}emote request {trigger} <imageURL> <true/false> <printed message>`\n"
                                                                       + "Insert true if you want this to be a targetted emote, false if you don't\n"
                                                                       + "Specify where you want the (optional) target's name in <printed message> by using " + tarString);

                GlobalVars.AddRandomTracker(m, 30);
            }
        }
Esempio n. 2
0
 public async Task AddOwner(ulong id)
 {
     string sql = $"INSERT INTO BotOwners (OwnerID) VALUES ({id})";
     var l = Constants._BOTOWNERS_.ToList();
     l.Add(id);
     Constants._BOTOWNERS_ = l.ToArray();
     DBControl.UpdateDB(sql);
     var m = await Context.Channel.SendMessageAsync($"User {CustomUserTypereader.GetUserFromID(id, Context.Client.Guilds).Result.Username} added as one of my Owners.");
     GlobalVars.AddRandomTracker(m, 5);
 }
Esempio n. 3
0
        public async Task RequestShip(string shipName, int amount, string coord1, string coord2)
        {
            //int amount = -1;
            //int.TryParse(amt, out amount);
            //if (amount == -1)
            //{
            //    await Context.Channel.SendMessageAsync($"Can not parse the value you entered for `Amount`. Please try again.\nYour input: {amt}");
            //    return;
            //}
            List <string> idList    = new List <string>();
            string        datestamp = DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year;

            SqlConnectionStringBuilder sBuilder = new SqlConnectionStringBuilder();

            sBuilder.InitialCatalog = GlobalVars.dbSettings.db;
            sBuilder.UserID         = GlobalVars.dbSettings.username;
            sBuilder.Password       = GlobalVars.dbSettings.password;
            sBuilder.DataSource     = GlobalVars.dbSettings.host + @"\" + GlobalVars.dbSettings.instance + "," + GlobalVars.dbSettings.port;

            SqlConnection conn = new SqlConnection
            {
                ConnectionString = sBuilder.ConnectionString
            };

            using (conn)
            {
                conn.Open();

                SqlCommand    cmd = new SqlCommand($"SELECT ReqID, ShipName, Amount, coord1, coord2 FROM ShipRequests WHERE GuildID = {Context.Guild.Id} AND Completed = 0;", conn);
                SqlDataReader dr  = cmd.ExecuteReader();

                while (dr.Read())
                {
                    if (dr.GetValue(3).ToString() == coord1 && dr.GetValue(4).ToString() == coord2)
                    {
                        var m = await Context.Channel.SendMessageAsync($"{Context.User.Mention}; this location already has a pending ship request.");

                        GlobalVars.AddRandomTracker(m);
                        return;
                    }
                    idList.Add(dr.GetValue(0).ToString());
                }
                dr.Close();

                conn.Close();
                conn.Dispose();
            }
            string ReqID = GenerateID(idList);

            string sql = $"INSERT INTO ShipRequests VALUES ('{ReqID}', {Context.Guild.Id}, {Context.User.Id}, '{shipName}', '{coord1}', '{coord2}', {amount}, '{datestamp}', 0);";

            DBControl.UpdateDB(sql);

            await Context.Channel.SendMessageAsync($"Ship request ID {ReqID} added.");
        }
Esempio n. 4
0
        public async Task SetMaxReserves(ushort amount)
        {
            GlobalVars.GuildOptions.Single(go => go.GuildID == Context.Guild.Id).MaxReserves = amount;
            var sql = $"UPDATE SBGuilds SET MaxReserves = {amount} WHERE GuildID = {Context.Guild.Id};";

            DBControl.UpdateDB(sql);

            var m = await Context.Channel.SendMessageAsync($"Updated max location reservations to {amount}.");

            GlobalVars.AddRandomTracker(m);
        }
Esempio n. 5
0
        public async Task SFWUrbDefine(params string[] term)
        {
            var             c = (ITextChannel)Context.Channel;
            RestUserMessage m;

            if (!c.IsNsfw)
            {
                m = await Context.Channel.SendMessageAsync("Urban Dictionary is NSFW-only, defaulting to Oxford Dictionary.");
                await OxfordDefine(term);

                GlobalVars.AddRandomTracker(m);
            }
        }
Esempio n. 6
0
        public async Task GetChannels(ulong guildID)
        {
            SocketGuild guild = Context.Client.GetGuild(guildID);
            if (guild == null)
            {
                var m = await Context.Channel.SendMessageAsync($"Can't find guild from ID {guildID.ToString()}");
                GlobalVars.AddRandomTracker(m);
                return;
            }
            SocketGuildUser botOwner = Context.Client.GetGuild(604753009502584834).Owner;
            if (botOwner == null)
            {
                var m = await Context.Channel.SendMessageAsync("Can't find my owner");
                GlobalVars.AddRandomTracker(m);
                return;
            }
            var dmChan = await botOwner.GetOrCreateDMChannelAsync();

            if (guild.Channels.Count == 0)
            {
                var m = await Context.Channel.SendMessageAsync("Can't find any channels");
                GlobalVars.AddRandomTracker(m);
                return;
            }

            List<EmbedBuilder> eb = new List<EmbedBuilder>();
            float neededEmbeds = (float)guild.Channels.Count / 25f;
            for (float i = 0; i < neededEmbeds; i++)
            {
                eb.Add(new EmbedBuilder());
            }
            int x = 0;
            foreach (SocketGuildChannel c in guild.Channels)
            {
                if (c.GetType() == typeof(SocketTextChannel))
                {
                    eb[x].AddField($"{c.Name}", $"__{c.Id}__");
                }
                if (eb[x].Fields.Count == 25) x++;
            }

            if (eb[0].Fields.Count == 0)
                await dmChan.SendMessageAsync($"Can't get channel list for {guild.Name} ({guildID.ToString()})");
            else
            {
                foreach (EmbedBuilder builder in eb)
                    await dmChan.SendMessageAsync($"{guild.Name}({guildID}) - {eb.IndexOf(builder)+1}/{eb.Count}", false, builder.Build());
            }
        }
Esempio n. 7
0
        public async Task RequestAug(string coord1, string coord2)
        {
            List <string> idList    = new List <string>();
            string        datestamp = DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year;

            SqlConnectionStringBuilder sBuilder = new SqlConnectionStringBuilder();

            sBuilder.InitialCatalog = GlobalVars.dbSettings.db;
            sBuilder.UserID         = GlobalVars.dbSettings.username;
            sBuilder.Password       = GlobalVars.dbSettings.password;
            sBuilder.DataSource     = GlobalVars.dbSettings.host + @"\" + GlobalVars.dbSettings.instance + "," + GlobalVars.dbSettings.port;

            SqlConnection conn = new SqlConnection
            {
                ConnectionString = sBuilder.ConnectionString
            };

            using (conn)
            {
                conn.Open();

                SqlCommand    cmd = new SqlCommand($"SELECT AugID, coord1, coord2 FROM AugRequests WHERE GuildID = {Context.Guild.Id} AND Completed = 0;", conn);
                SqlDataReader dr  = cmd.ExecuteReader();

                while (dr.Read())
                {
                    if (dr.GetValue(1).ToString() == coord1 && dr.GetValue(2).ToString() == coord2)
                    {
                        var m = await Context.Channel.SendMessageAsync($"{Context.User.Mention}; this location already has a pending augmentation request.");

                        GlobalVars.AddRandomTracker(m);
                        return;
                    }
                    idList.Add(dr.GetValue(0).ToString());
                }
                dr.Close();

                conn.Close();
                conn.Dispose();
            }
            string AugID = GenerateID(idList);

            string sql = $"INSERT INTO AugRequests VALUES ('{AugID}', {Context.Guild.Id}, {Context.User.Id}, '{coord1}', '{coord2}', '{datestamp}', 0);";

            DBControl.UpdateDB(sql);

            await Context.Channel.SendMessageAsync($"Augmentation request ID {AugID} added.");
        }
Esempio n. 8
0
        public async Task OrderOption(string orderType, string mode = "asc")
        {
            if (!GlobalVars.RegisteredMortyUsers.Contains(Context.User.Id))
            {
                string prefix = GlobalVars.GuildOptions.SingleOrDefault(x => x.GuildID == Context.Guild.Id).Prefix;
                await Context.Channel.SendMessageAsync($"{Context.User.Mention}, you haven't registered to play yet.\nPlease use the command `{prefix}mortystart` first!");

                return;
            }

            if (!new string[] { "id", "rarity", "count", "stattotal" }.Contains(orderType.ToLower()))
            {
                var m = await Context.Channel.SendMessageAsync($"{Context.User.Mention}, invalid ordering option, please check your spelling and try again.\n" +
                                                               $"Valid ordering options: `id, rarity, count, stattotal`");

                GlobalVars.AddRandomTracker(m);
                return;
            }

            var msg = $"Your mortylist will now be sorted by {orderType} in ";

            mode = mode.Trim();

            if ("asc" == mode.ToLower())
            {
                msg += "ascending order.";
            }
            else if (mode.ToLower() == "desc")
            {
                msg += "descending order.";
            }
            else
            {
                msg += "ascending order.\n(Default due to incorrect input)";
                mode = "asc";
            }

            string sql = $"UPDATE mortyUsers SET orderType = '{orderType.ToLower()}' WHERE discordID = {Context.User.Id}";

            DBControl.UpdateDB(sql);

            sql = $"UPDATE mortyUsers SET orderDir = '{mode.ToLower()}' WHERE discordID = {Context.User.Id}";
            DBControl.UpdateDB(sql);

            await Context.Channel.SendMessageAsync(msg);
        }
Esempio n. 9
0
        public async Task EditRequest(string emoteID, string paramName, [Remainder] string newValue)
        {
            if (GlobalVars.EmoteRequests.TryGetValue(emoteID, out EmoteRequest er))
            {
                string msg = "";
                switch (paramName.ToLower())
                {
                case "trigger":
                    GlobalVars.EmoteRequests.Values.Single(e => e.RequestID == er.RequestID).ChangeTrigger(newValue);
                    msg = $"Request {er.RequestID} has been edited.\nNew value for Trigger: `{newValue}`";
                    break;

                case "requirestarget":
                    GlobalVars.EmoteRequests.Values.Single(e => e.RequestID == er.RequestID).RequiresTarget = (newValue == "true" ? true : false);
                    msg = $"Request {er.RequestID} has been edited.\n{(newValue == "true" ? "Will now require a target" : "Will no longer require a target!")}";
                    break;

                case "outputtext":
                    GlobalVars.EmoteRequests.Values.Single(e => e.RequestID == er.RequestID).OutputText = newValue;
                    msg = $"Request {er.RequestID} has been edited.\nNew value for OutputText: `{newValue}`";
                    break;

                case "nsfw":
                    GlobalVars.EmoteRequests.Values.Single(e => e.RequestID == er.RequestID).Nsfw = (newValue == "true" ? true : false);
                    msg = $"Request {er.RequestID} has been edited.\n{(newValue == "true" ? "Will now be NSFW" : "Will no longer be NSFW!")}";
                    break;

                default:
                    msg = $"Invalid parameter name. Requires `trigger`, `requirestarget`, `nsfw` or `outputtext`.\nYou supplied {paramName}" +
                          $"";
                    break;
                }
                try
                {
                    var reqMsg = GlobalVars.RequestMessage.FirstOrDefault(p => p.Key == er.RequestID).Value;
                    await SendRequest(er);

                    await reqMsg.DeleteAsync();
                }
                catch { }
                var m = await Context.Channel.SendMessageAsync(msg);

                GlobalVars.AddRandomTracker(m, 10);
            }
        }
Esempio n. 10
0
        public async Task RemoveIgnore(ulong idiotID)
        {
            GlobalVars.IgnoredUsers.TryGetValue(idiotID, out IUser user);
            if (user != null)
            {
                GlobalVars.IgnoredUsers.Remove(idiotID);

                string sql = $"DELETE FROM Ignores WHERE UserID = {idiotID}";
                DBControl.UpdateDB(sql);

                await Context.Channel.SendMessageAsync($"Removed user {user.Mention} from the ignore list.\nThey can now use commands again.");
            }
            else
            {
                var msg = await Context.Channel.SendMessageAsync($"User not ignored (ID: {idiotID})");
                GlobalVars.AddRandomTracker(msg, 5);
            }
        }
Esempio n. 11
0
        public async Task AddIgnore(ulong idiotID)
        {
            var user = await CustomUserTypereader.GetUserFromID(idiotID, Context.Client.Guilds);
            if (user != null)
            {
                GlobalVars.IgnoredUsers.Add(idiotID, user);

                string sql = $"INSERT INTO Ignores (UserID, DateAdded) VALUES ({idiotID},'{DateTime.Now.Day}-{DateTime.Now.Month}-{DateTime.Now.Year}')";
                DBControl.UpdateDB(sql);

                await Context.Channel.SendMessageAsync($"Added user {user.Mention} to the ignore list.\nThey will now be ignored by me.");
            }
            else
            {
                var msg = await Context.Channel.SendMessageAsync($"User not found (ID: {idiotID})");
                GlobalVars.AddRandomTracker(msg, 5);
            }
        }
Esempio n. 12
0
        public async Task RemoveFriend(ulong friendID)
        {
            GlobalVars.FriendUsers.TryGetValue(friendID, out IUser user);
            if (user != null)
            {
                GlobalVars.FriendUsers.Remove(friendID);

                string sql = $"DELETE FROM Friends WHERE UserID = {friendID}";
                DBControl.UpdateDB(sql);

                await Context.Channel.SendMessageAsync($"Removed user {user.Mention} from my friends list.");
            }
            else
            {
                var msg = await Context.Channel.SendMessageAsync($"User is not a friend (ID: {friendID})");
                GlobalVars.AddRandomTracker(msg, 5);
            }
        }
Esempio n. 13
0
        public async Task AddFriend(ulong friendID)
        {
            var user = await CustomUserTypereader.GetUserFromID(friendID, Context.Client.Guilds);
            if (user != null)
            {
                GlobalVars.FriendUsers.Add(friendID, user);

                string sql = $"INSERT INTO Friends (UserID, DateAdded) VALUES ({friendID},'{DateTime.Now.Day}-{DateTime.Now.Month}-{DateTime.Now.Year}')";
                DBControl.UpdateDB(sql);

                await Context.Channel.SendMessageAsync($"Added user {user.Mention} as a friend.\nThey will no longer be timed out and will have more privileges in the future.");
            }
            else
            {
                var msg = await Context.Channel.SendMessageAsync($"User not found (ID: {friendID}");
                GlobalVars.AddRandomTracker(msg, 5);
            }
        }
Esempio n. 14
0
        public async Task SetMaxWarn(ushort maxAmount)
        {
            if (maxAmount > 0)
            {
                var sql = $"UPDATE SBGuilds SET WarnThreshold = {maxAmount} WHERE GuildID = {Context.Guild.Id}";
                DBControl.UpdateDB(sql);
                var m = await Context.Channel.SendMessageAsync($"Updated maximum number of allowed warnings, now set to {maxAmount}.");

                GlobalVars.AddRandomTracker(m);
            }
            else
            {
                var m = await Context.Channel.SendMessageAsync($"Warnings are now disabled!");

                GlobalVars.AddRandomTracker(m);
            }
            GlobalVars.GuildOptions.Single(go => go.GuildID == Context.Guild.Id).PunishThreshold = maxAmount;
        }
Esempio n. 15
0
        public async Task CompleteAug(SocketGuildUser user, string coord1 = "", string coord2 = "")
        {
            string sql = $"SELECT AugID FROM AugRequests WHERE GuildID = {Context.Guild.Id} AND UserID = {user.Id} AND coord1 = '{coord1}' AND coord2 = '{coord2}' AND Completed = 0;";

            string id = "";

            id = SearchID(sql);
            if (id == "")
            {
                var m = await Context.Channel.SendMessageAsync("There is no active augmentation request found with your parameters.");

                GlobalVars.AddRandomTracker(m);
                return;
            }
            else
            {
                await CompleteAug(id, true);
            }
        }
Esempio n. 16
0
        public async Task LeaveGuild()
        {
            if (Context.User.Id != Context.Guild.Owner.Id)
            {
                var uMsg = await Context.Channel.SendMessageAsync($"{Context.User.Mention}, NO, screw you! Only {Context.Guild.Owner.Mention} can make me leave!");

                var owner   = Context.Guild.Owner;
                var channel = await owner.GetOrCreateDMChannelAsync();

                var msgToOwner = await channel.SendMessageAsync($"Hi {Context.Guild.Owner.Username}, user {Context.User.Mention} has tried to make me leave {Context.Guild.Name} in channel: #{Context.Channel.Name}");

                GlobalVars.AddRandomTracker(uMsg);
            }
            else
            {
                await Context.Channel.SendMessageAsync($"Goodbye {Context.Guild.Owner.Mention}, apparantly {Context.User.Mention} wants me gone :sob:");

                await Context.Guild.LeaveAsync();
            }
        }
Esempio n. 17
0
        public async Task RegisterUser()
        {
            if (GlobalVars.RegisteredMortyUsers.Contains(Context.User.Id) || GlobalVars.MortyTimeouts.ContainsKey(Context.User.Id))
            {
                var m = await Context.Channel.SendMessageAsync($"Sorry {Context.User.Mention}, but you already did this!");

                GlobalVars.AddRandomTracker(m);
                return;
            }
            string sql = $"INSERT INTO mortyUsers (discordID, orderType, orderDir) VALUES ({Context.User.Id}, 'id', 'asc')";

            DBControl.UpdateDB(sql);

            GlobalVars.RegisteredMortyUsers.Add(Context.User.Id);
            GlobalVars.MortyTimeouts.Add(Context.User.Id, false);
            GlobalVars.MortyLastUse.Add(Context.User.Id, DateTime.MinValue);

            string prefix = GlobalVars.GuildOptions.SingleOrDefault(x => x.GuildID == Context.Guild.Id).Prefix;
            await Context.Channel.SendMessageAsync($"Hi {Context.User.Mention}, you can now use `{prefix}morty` in order to start gathering your Mortys!");
        }
Esempio n. 18
0
        public async Task CheckReserves(string coord1 = "*", string coord2 = "*")
        {
            if (coord1 != "*")
            {
                try
                {
                    int.TryParse(coord1, out int x);
                }
                catch
                {
                    var m = await Context.Channel.SendMessageAsync($"Invalid parameter");

                    GlobalVars.AddRandomTracker(m);
                    return;
                }
            }
            if (coord2 != "*")
            {
                try
                {
                    int x;
                    int.TryParse(coord2, out x);
                }
                catch
                {
                    var m = await Context.Channel.SendMessageAsync($"Invalid parameter");

                    GlobalVars.AddRandomTracker(m);
                    return;
                }
            }
            SqlConnectionStringBuilder sBuilder = new SqlConnectionStringBuilder();

            sBuilder.InitialCatalog = GlobalVars.dbSettings.db;
            sBuilder.UserID         = GlobalVars.dbSettings.username;
            sBuilder.Password       = GlobalVars.dbSettings.password;
            sBuilder.DataSource     = GlobalVars.dbSettings.host + @"\" + GlobalVars.dbSettings.instance + "," + GlobalVars.dbSettings.port;

            SqlConnection conn = new SqlConnection
            {
                ConnectionString = sBuilder.ConnectionString
            };

            EmbedBuilder eb = new EmbedBuilder();

            eb.Title = $"List of reservations by coords [{coord1} {coord2}]";

            using (conn)
            {
                conn.Open();

                #region Get Reservation
                SqlCommand    cmd = new SqlCommand($"SELECT UserID, Coord1, Coord2, DateStamp FROM Reservations WHERE GuildID = {Context.Guild.Id} AND Coord1 LIKE '{coord1.Replace("*", "%")}' AND Coord2 LIKE '{coord2.Replace("*", "%")}';", conn);
                SqlDataReader dr  = cmd.ExecuteReader();

                while (dr.Read())
                {
                    ulong userID = Convert.ToUInt64(dr.GetValue(0));
                    if (userID != 0)
                    {
                        SocketGuildUser usr = Context.Guild.Users.SingleOrDefault(u => u.Id == userID);
                        eb.AddField($"Reserved by {usr} on {dr.GetValue(3)}", $"Location: /goto {dr.GetValue(1)} {dr.GetValue(2)}");
                    }
                }
                #endregion

                conn.Close();
                conn.Dispose();
            }
            eb.WithFooter($"Found {eb.Fields.Count} locations.");
            if (eb.Fields.Count > 0 && eb.Fields.Count <= 25)
            {
                await Context.Channel.SendMessageAsync(null, false, eb.Build());
            }
            else if (eb.Fields.Count > 25)
            {
                var t = eb.Fields.Count - 24;
                List <EmbedFieldBuilder> tmp = new List <EmbedFieldBuilder>();
                for (int i = 0; i < 24; i++)
                {
                    tmp.Add(eb.Fields[i]);
                }
                eb.Fields = tmp;
                eb.AddField($"*and {t} more locations.*", null);

                await Context.Channel.SendMessageAsync(null, false, eb.Build());
            }
            else
            {
                await Context.Channel.SendMessageAsync($"{Context.User.Mention}, there were no matching locations reserved in this alliance.");
            }
        }
Esempio n. 19
0
        public async Task PollCreate([Remainder] string parameters)
        {
            string[] parameterArray = parameters.Split('|');
            if (parameterArray.Length >= 4 && parameterArray.Length <= 7)
            {
                string question = parameterArray[0];
                parameterArray[0] = "";
                string timecode = parameterArray[1];
                parameterArray[1] = "";

                ulong timeSpan = 0;
                timecode = timecode.ToLower();
                if (Regex.Match(timecode, @"\d+[dhm]").Success || timecode == "test")
                {
                    if (timecode == "test")
                    {
                        timeSpan = 10;
                    }
                    else
                    {
                        int   i          = timecode.Contains('d') ? timecode.IndexOf('d') : (timecode.Contains('h') ? timecode.IndexOf('h') : timecode.IndexOf('m'));
                        ulong multiplier = 1;
                        switch (timecode.Substring(i, 1))
                        {
                        case "d":
                            multiplier = 24 * 60 * 60; break;

                        case "m":
                            multiplier = 60; break;

                        default:
                            multiplier = 60 * 60; break;
                        }
                        timeSpan = ulong.Parse(timecode.Substring(0, i)) * multiplier;
                    }
                    if (timeSpan > (7 * 24 * 60 * 60))
                    {
                        await Context.Channel.SendMessageAsync($"Timespan too large, max amount of time: 7 days *({7 * 24} hours)*"); return;
                    }
                }

                List <string> pollOptions = new List <string>();
                foreach (string s in parameterArray)
                {
                    if (s != "")
                    {
                        pollOptions.Add(s);
                    }
                }

                var m = await Context.Channel.SendMessageAsync("Poll creating...");

                Poll p = new Poll(m, question, Context.User, pollOptions.ToArray());

                EmbedBuilder eb = new EmbedBuilder();
                eb.WithAuthor($"Poll by {Context.User.Username}#{Context.User.DiscriminatorValue}", Context.User.GetAvatarUrl());
                eb.WithDescription($"**{question}**");
                eb.WithFooter($"PollID: {p.PollId}");
                eb.WithColor(0, 255, 0);
                foreach (PollOption s in p.PollOptions)
                {
                    float amt = p.PollReactions.Count(x => x.PollVote == s.Option);
                    eb.AddField($"{s.React} {s.Option}", $"{Poll.GetPercentageBar(p, s.Option)} - 0/{p.PollReactions.Count} (0,00%)");
                }

                await m.ModifyAsync(x => {
                    x.Content = "";
                    x.Embed   = eb.Build();
                });

                await p.AddAllReactions();

                GlobalVars.AddPoll(p, timeSpan);
            }
            else
            {
                var m = await Context.Channel.SendMessageAsync("Too many parameters");

                GlobalVars.AddRandomTracker(m);
            }
        }
Esempio n. 20
0
        public async Task Warn([Remainder] string arg)
        {
            var user = Context.Message.MentionedUsers.FirstOrDefault();

            if (user == null)
            {
                var m = await Context.Channel.SendMessageAsync($"You need to tell me who to warn though {Context.User.Mention}");

                GlobalVars.AddRandomTracker(m);
                return;
            }
            SqlConnectionStringBuilder sBuilder = new SqlConnectionStringBuilder();

            sBuilder.InitialCatalog = GlobalVars.dbSettings.db;
            sBuilder.UserID         = GlobalVars.dbSettings.username;
            sBuilder.Password       = GlobalVars.dbSettings.password;
            sBuilder.DataSource     = GlobalVars.dbSettings.host + @"\" + GlobalVars.dbSettings.instance + "," + GlobalVars.dbSettings.port;

            SqlConnection conn = new SqlConnection
            {
                ConnectionString = sBuilder.ConnectionString
            };

            using (conn)
            {
                conn.Open();

                short  warnCount     = 0;
                ushort warnThreshold = GlobalVars.GuildOptions.Single(go => go.GuildID == Context.Guild.Id).PunishThreshold;

                if (warnThreshold == 0)
                {
                    var m = await Context.Channel.SendMessageAsync($"You need to set a max warning threshold first!\nTry using `{Context.Message.Content.Substring(0, 1)}warn max [amount]`.");

                    GlobalVars.AddRandomTracker(m);
                    conn.Close();
                    conn.Dispose();
                    return;
                }

                SqlCommand    cmd = new SqlCommand($"SELECT WarnCount FROM SBUsers WHERE GuildID = {Context.Guild.Id} AND UserID = {user.Id};", conn);
                SqlDataReader dr  = cmd.ExecuteReader();

                while (dr.Read())
                {
                    warnCount = dr.GetInt16(0);
                }
                dr.Close();

                var sql = $"UPDATE SBUsers SET WarnCount = {++warnCount} WHERE UserID = {user.Id};";
                DBControl.UpdateDB(sql);

                conn.Close();
                conn.Dispose();

                if (warnCount >= warnThreshold)
                {
                    await Context.Channel.SendMessageAsync($"{Context.User.Mention}, {user.Mention} has {warnCount} out of {warnThreshold} warnings, time to punish!");
                }
                else
                {
                    await Context.Channel.SendMessageAsync($"{user.Mention}, you have been warned.\nYou are now at {warnCount} out of {warnThreshold} warnings.");
                }
            }
        }
Esempio n. 21
0
        public async Task SpawnMorty()
        {
            if (!GlobalVars.RegisteredMortyUsers.Contains(Context.User.Id))
            {
                string prefix = GlobalVars.GuildOptions.SingleOrDefault(x => x.GuildID == Context.Guild.Id).Prefix;
                await Context.Channel.SendMessageAsync($"{Context.User.Mention}, you haven't registered to play yet.\nPlease use the command `{prefix}mortystart` first!");

                return;
            }

            if (GlobalVars.MortyTimeouts[Context.User.Id])
            {
                int timeLeft        = Convert.ToInt32((GlobalVars.MortyLastUse[Context.User.Id].AddMinutes(30) - DateTime.Now).TotalSeconds);
                int timeLeftMinutes = 0;
                while (timeLeft >= 60)
                {
                    timeLeftMinutes++;
                    timeLeft -= 60;
                }
                var m = await Context.Channel.SendMessageAsync(
                    $"{Context.User.Mention}, your portal gun is out of energy. Please wait for it to recharge!\n"
                    + $"Time left: {timeLeftMinutes}min, {timeLeft}s.");

                GlobalVars.AddRandomTracker(m);
                return;
            }

            Random r      = new Random();
            int    rand   = r.Next(1, 101);
            string rarity =
                rand <= 60 ? "Common" :
                rand <= 80 ? "Rare" :
                rand <= 84 ? "Epic" :
                rand <= 85 ? "Exotic" : "None";

            List <Character> WeightedList = rarity == "None" ? null : GlobalVars.GameObj.MortyList.Where(x => x.Rarity == rarity).ToList();
            Character        c            = WeightedList?[r.Next(WeightedList.Count())];

            if (c != null)
            {
                string sql =
                    $"INSERT INTO ownedMortys (userID, mortyID) VALUES (" +
                    $"(SELECT userID FROM mortyUsers WHERE discordID = {Context.User.Id})," +
                    $"{c.CharID - 1})";
                DBControl.UpdateDB(sql);

                EmbedBuilder eb    = new EmbedBuilder();
                string       cName = c.CharName.Replace("'", "").Replace(" ", "").Replace("-", "");
                if (cName.ToLower() == "morty")
                {
                    cName = "MortyDefault";
                }
                else
                {
                    string t = "Morty" + cName.Replace("Morty", "");
                    cName = t;
                }
                string fileName = $"{Constants._WORKDIR_}\\Assets\\{c.CharID}-{cName}.png";

                eb.WithAuthor("Pocket Mortys");
                eb.WithImageUrl($"attachment://{c.CharID}-{cName}.png");
                eb.WithTitle($"{Context.User} has found a [#{c.CharID}] {c.CharName}");
                eb.WithDescription($"" +
                                   $"**Type**: {c.Type}\n" +
                                   $"**Rarity**: {c.Rarity}\n" +
                                   $"**Dimension**: {c.Dimension}\n" +
                                   $"**Base Hitpoints**: {c.HP}\n" +
                                   $"**Base Attack**: {c.ATK}\n" +
                                   $"**Base Defense**: {c.DEF}\n" +
                                   $"**Base Speed**: {c.SPD}\n" +
                                   $"**Base Stat Total**: {c.StatTotal}");
                eb.WithFooter("pocketmortys.net");

                switch (c.Dimension)
                {
                case "Mortyland":
                    eb.WithColor(57, 214, 33);
                    break;

                case "Plumbubo Prime 51b":
                    eb.WithColor(252, 102, 252);
                    break;

                case "Mortopia":
                    eb.WithColor(252, 216, 56);
                    break;

                case "GF Mortanic":
                    eb.WithColor(170, 193, 204);
                    break;

                default:
                    eb.WithColor(53, 53, 53);
                    break;
                }

                await Context.Channel.SendFileAsync(fileName, null, false, eb.Build());
            }
            else
            {
                await Context.Channel.SendMessageAsync($"{Context.User.Mention}, it seems like you were looking in the wrong dimensions...\nYou couldn't find any Mortys!");
            }

            GlobalVars.MortyTimeouts[Context.User.Id] = true;
            GlobalVars.MortyLastUse[Context.User.Id]  = DateTime.Now;

            Timer ti = new Timer();

            void handler(object sender, ElapsedEventArgs e)
            {
                ti.Stop();
                GlobalVars.MortyTimeouts[Context.User.Id] = false;
                ti.Dispose();
            }

            ti.StartTimer(handler, 1800000);
        }
Esempio n. 22
0
        private async Task DoLookup(Character c, int ID = -1, string name = "[Invalid ID/Name]")
        {
            if (c != null)
            {
                EmbedBuilder eb    = new EmbedBuilder();
                string       cName = c.CharName.Replace("'", "").Replace(" ", "").Replace("-", "").Replace(".", "");
                if (cName.ToLower() == "morty")
                {
                    cName = "MortyDefault";
                }
                else
                {
                    string t = "Morty" + cName.Replace("Morty", "");
                    cName = t;
                }
                string fileName = $"{Constants._WORKDIR_}\\Assets\\{c.CharID}-{cName}.png";

                eb.WithAuthor("Pocket Mortys");
                eb.WithImageUrl($"attachment://{c.CharID}-{cName}.png");
                eb.WithTitle($"**Base stats for** [#{c.CharID}] {c.CharName}");
                eb.WithDescription($"" +
                                   $"**Type**: {c.Type}\n" +
                                   $"**Rarity**: {c.Rarity}\n" +
                                   $"**Dimension**: {c.Dimension}\n" +
                                   $"**Base Hitpoints**: {c.HP}\n" +
                                   $"**Base Attack**: {c.ATK}\n" +
                                   $"**Base Defense**: {c.DEF}\n" +
                                   $"**Base Speed**: {c.SPD}\n" +
                                   $"**Base Stat Total**: {c.StatTotal}");
                eb.WithFooter("pocketmortys.net");

                switch (c.Dimension)
                {
                case "Mortyland":
                    eb.WithColor(57, 214, 33);
                    break;

                case "Plumbubo Prime 51b":
                    eb.WithColor(252, 102, 252);
                    break;

                case "Mortopia":
                    eb.WithColor(252, 216, 56);
                    break;

                case "GF Mortanic":
                    eb.WithColor(170, 193, 204);
                    break;

                default:
                    eb.WithColor(53, 53, 53);
                    break;
                }

                await Context.Channel.SendFileAsync(fileName, null, false, eb.Build());
            }
            else
            {
                string[] Messages = new string[]
                {
                    "Oh jeez, I couldn't find that Morty!",
                    "This Morty seems to have been swallowed by Dimension 404..."
                };
                var msg = await Context.Channel.SendMessageAsync($"{Messages[new Random().Next(0,Messages.Length)]}\n*(Make sure you didn't make a mistake!Invalid ID/Name)*");

                GlobalVars.AddRandomTracker(msg);
            }
        }
Esempio n. 23
0
        public async Task RequestEmote(string trigger, string url, bool RequiresTarget, [Remainder] string msg)
        {
            if (msg == "")
            {
                msg = $"is {trigger}";
            }
            EmoteRequest er       = new EmoteRequest(Context.Message.Author, trigger, RequiresTarget, msg, false);
            string       finalURL = "";

            string[] imgFileTypes = { ".jpg", ".jpeg", ".gif", ".png" };
            foreach (string s in imgFileTypes)
            {
                if (url.Substring(url.Length - s.Length, s.Length) == s)
                {
                    finalURL         = url;
                    er.FileExtension = s;
                }
            }
            if (finalURL == "")
            {
                finalURL = url.Contains("tenor") ? ImageLogger.GetTenorGIF(url) : url.Contains("gfycat") ? ImageLogger.GetGfyCatAsync(url) : "";
                foreach (string s in imgFileTypes)
                {
                    if (finalURL.Substring(finalURL.Length - s.Length, s.Length) == s)
                    {
                        er.FileExtension = s;
                    }
                }
            }

            if (finalURL != "")
            {
                string dir = RequestLocation.Substring(0, RequestLocation.Length - 1);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                using (var c = new WebClient())
                {
                    try
                    {
                        c.DownloadFile(finalURL, RequestLocation + er.FileName);
                    }
                    catch (Exception ex) { }
                    while (c.IsBusy)
                    {
                    }
                }

                GlobalVars.EmoteRequests.Add(er.RequestID, er);



                try
                {
                    await SendRequest(er);

                    var m = await Context.Channel.SendMessageAsync($"Emote requested, emote ID: {er.RequestID}");

                    GlobalVars.AddRandomTracker(m, 15);
                    var perms = Context.Guild.GetUser(Context.Client.CurrentUser.Id).GetPermissions(Context.Channel as IGuildChannel);
                    if (perms.ManageMessages)
                    {
                        try { await Context.Message.DeleteAsync(); }
                        catch { }
                    }
                }
                catch (Discord.Net.HttpException ex)
                {
                    if (ex.DiscordCode == 40005)
                    {
                        var m = await Context.Channel.SendMessageAsync($"{Context.User.Mention}, the filesize is too large (~{new FileInfo(RequestLocation + er.FileName).Length / 1048576}MB). Max filesize: 8MB\nPlease resize your image or use another.");

                        GlobalVars.AddRandomTracker(m, 15);
                        File.Delete(RequestLocation + er.FileName);
                        GlobalVars.EmoteRequests.Remove(er.RequestID);
                    }
                    await Program.Client_Log(new LogMessage(LogSeverity.Error, "Emote Request", ex.Message, ex));
                }
            }
            else
            {
                var m = await Context.Channel.SendMessageAsync("Could not get the download URL for this image.");

                GlobalVars.AddRandomTracker(m, 20);
            }
        }
Esempio n. 24
0
        public async Task ConvertCurrency(string convertAmt, string StartUnit, string EndUnit)
        {
            if (!GlobalVars.CurrencyList.Keys.Contains(StartUnit.ToUpper()))
            {
                var msg = await Context.Channel.SendMessageAsync($"The provided start unit ({StartUnit}) was not recognized.");

                GlobalVars.AddRandomTracker(msg);
                return;
            }
            if (!GlobalVars.CurrencyList.Keys.Contains(EndUnit.ToUpper()))
            {
                var msg = await Context.Channel.SendMessageAsync($"The provided end unit ({EndUnit}) was not recognized.");

                GlobalVars.AddRandomTracker(msg);
                return;
            }

            double amtToConvert = 0d;
            bool   hasDot       = false;

            #region Errorchecking
            try
            {
                if (convertAmt.Contains(','))
                {
                    amtToConvert = double.Parse(convertAmt.Replace(@",", @"."));
                }
                else
                {
                    amtToConvert = double.Parse(convertAmt);
                    hasDot       = true;
                }
            }
            catch
            {
                var msg = await Context.Channel.SendMessageAsync($"{Context.User.Mention} -> Something went wrong while reading your number, your entry: {convertAmt}");

                GlobalVars.AddRandomTracker(msg);
                return;
            }
            #endregion

            double valuesToSend = 0d;

            var toUSD = amtToConvert * GlobalVars.CurrencyList[StartUnit.ToUpper()].ValueInUSD;
            valuesToSend = GlobalVars.CurrencyList[EndUnit.ToUpper()].ValueInUSD / toUSD;

            NumberFormatInfo ni = new CultureInfo("sv-SE", false).NumberFormat;
            string           r  = valuesToSend.ToString("N6", ni);
            if (r.Contains(','))
            {
                for (int i = r.Length - 1; i > 0; i--)
                {
                    if (!r.Contains(','))
                    {
                        break;
                    }
                    if (r[i] == '0' || r[i] == ',')
                    {
                        var rArray = r.ToList();
                        rArray.RemoveAt(i);
                        r = string.Join("", rArray);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            if (r.Contains(',') && hasDot)
            {
                r = r.Replace(@",", @".");
            }
            await Context.Channel.SendMessageAsync($"`{convertAmt} {GlobalVars.CurrencyList[StartUnit.ToUpper()].FullName} ≈ {r} {GlobalVars.CurrencyList[EndUnit.ToUpper()].FullName}`");
        }
Esempio n. 25
0
        public async Task ConvertWgt(string convertAmt, string StartUnit, string EndUnit)
        {
            StartUnit = StartUnit.ToLower();
            if (StartUnit == "pound" || StartUnit == "pounds")
            {
                StartUnit = "lbs";
            }
            if (StartUnit == "ounce")
            {
                StartUnit = "oz";
            }
            if (StartUnit == "stone")
            {
                StartUnit = "st";
            }

            EndUnit = EndUnit.ToLower();
            if (EndUnit == "pound" || EndUnit == "pounds")
            {
                EndUnit = "lbs";
            }
            if (EndUnit == "ounce")
            {
                EndUnit = "oz";
            }
            if (EndUnit == "stone")
            {
                EndUnit = "st";
            }

            double amtToConvert = 0d;
            bool   hasDot       = false;

            #region Errorchecking
            if (!SupportedUnitsWgt.Contains(StartUnit))
            {
                var msg = await Context.Channel.SendMessageAsync($"{Context.User.Mention} -> Your start unit is incorrect, supported units: {string.Join(" - ", SupportedUnitsWgt)}");

                GlobalVars.AddRandomTracker(msg);
                return;
            }
            if (!SupportedUnitsWgt.Contains(EndUnit))
            {
                var msg = await Context.Channel.SendMessageAsync($"{Context.User.Mention} -> Your end unit is incorrect, supported units: {string.Join(" - ", SupportedUnitsWgt)}");

                GlobalVars.AddRandomTracker(msg);
                return;
            }

            try
            {
                if (convertAmt.Contains(','))
                {
                    amtToConvert = double.Parse(convertAmt.Replace(@",", @"."));
                }
                else
                {
                    amtToConvert = double.Parse(convertAmt);
                    hasDot       = true;
                }
            }
            catch
            {
                var msg = await Context.Channel.SendMessageAsync($"{Context.User.Mention} -> Something went wrong while reading your number, your entry: {convertAmt}");

                GlobalVars.AddRandomTracker(msg);
                return;
            }
            #endregion

            double valuesToSend = 0d;
            switch (EndUnit)
            {
            case "kg":
                valuesToSend = ConvertHelpers.ToKilos(amtToConvert, StartUnit);
                break;

            case "g":
                valuesToSend = ConvertHelpers.ToG(amtToConvert, StartUnit);
                break;

            case "dg":
                valuesToSend = ConvertHelpers.ToDg(amtToConvert, StartUnit);
                break;

            case "cg":
                valuesToSend = ConvertHelpers.ToCg(amtToConvert, StartUnit);
                break;

            case "mg":
                valuesToSend = ConvertHelpers.ToMg(amtToConvert, StartUnit);
                break;

            case "st":
                valuesToSend = ConvertHelpers.ToStone(amtToConvert, StartUnit);
                break;

            case "lbs":
                valuesToSend = ConvertHelpers.ToLbs(amtToConvert, StartUnit);
                break;

            case "oz":
                valuesToSend = ConvertHelpers.ToOz(amtToConvert, StartUnit);
                break;

            default: break;
            }

            NumberFormatInfo ni = new CultureInfo("sv-SE", false).NumberFormat;
            string           r  = valuesToSend.ToString("N6", ni);
            if (r.Contains(','))
            {
                for (int i = r.Length - 1; i > 0; i--)
                {
                    if (!r.Contains(','))
                    {
                        break;
                    }
                    if (r[i] == '0' || r[i] == ',')
                    {
                        var rArray = r.ToList();
                        rArray.RemoveAt(i);
                        r = string.Join("", rArray);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            if (r.Contains(',') && hasDot)
            {
                r = r.Replace(@",", @".");
            }
            await Context.Channel.SendMessageAsync($"`{convertAmt} {StartUnit} ≈ {r} {EndUnit}`");
        }
Esempio n. 26
0
        public async Task ConvertCF(string convertAmt, string StartUnit, string EndUnit)
        {
            StartUnit = StartUnit.ToUpper();
            EndUnit   = EndUnit.ToUpper();
            double amtToConvert = 0d;
            bool   hasDot       = false;

            #region Errorchecking
            if (!("CFK").Contains(StartUnit))
            {
                var msg = await Context.Channel.SendMessageAsync($"{Context.User.Mention} -> Your start unit is incorrect, please use *C*, *F* or *K*");

                GlobalVars.AddRandomTracker(msg);
                return;
            }
            if (!("CFK").Contains(EndUnit))
            {
                var msg = await Context.Channel.SendMessageAsync($"{Context.User.Mention} -> Your end unit is incorrect, please use *C*, *F* or *K*");

                GlobalVars.AddRandomTracker(msg);
                return;
            }
            if (StartUnit == EndUnit)
            {
                var msg = await Context.Channel.SendMessageAsync($"{Context.User.Mention} -> Why would you want to convert to the same unit measure?");

                GlobalVars.AddRandomTracker(msg);
                return;
            }

            try
            {
                if (convertAmt.Contains(','))
                {
                    amtToConvert = double.Parse(convertAmt.Replace(@",", @"."));
                }
                else
                {
                    amtToConvert = double.Parse(convertAmt);
                    hasDot       = true;
                }
            }
            catch
            {
                var msg = await Context.Channel.SendMessageAsync($"{Context.User.Mention} -> Something went wrong while reading your number, your entry: {convertAmt}");

                GlobalVars.AddRandomTracker(msg);
                return;
            }
            #endregion

            double resultValue = 0d;
            if (EndUnit == "F")
            {
                resultValue = ConvertHelpers.ToFahrenheit(amtToConvert, StartUnit);
            }
            else if (EndUnit == "C")
            {
                resultValue = ConvertHelpers.ToCelcius(amtToConvert, StartUnit);
            }
            else
            {
                resultValue = ConvertHelpers.ToKelvin(amtToConvert, StartUnit);
            }

            NumberFormatInfo ni = new CultureInfo("sv-SE", false).NumberFormat;
            string           r  = resultValue.ToString("N6", ni);
            if (r.Contains(','))
            {
                for (int i = r.Length - 1; i > 0; i--)
                {
                    if (!r.Contains(','))
                    {
                        break;
                    }
                    if (r[i] == '0' || r[i] == ',')
                    {
                        var rArray = r.ToList();
                        rArray.RemoveAt(i);
                        r = string.Join("", rArray);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            if (r.Contains(',') && hasDot)
            {
                r = r.Replace(@",", @".");
            }
            await Context.Channel.SendMessageAsync($"`{convertAmt} °{StartUnit} ≈ {r} °{EndUnit}`");
        }
Esempio n. 27
0
        public async Task OxfordDefine(params string[] term)
        {
            string       WEBSERVICE_URL = "https://od-api.oxforddictionaries.com:443/api/v2/lemmas/en/" + string.Join(' ', term).ToLower();
            string       jsonResponse   = "";
            OxfordEntry  oxfEntry       = new OxfordEntry();
            OxfordLemma  oxfLemma       = new OxfordLemma();
            EmbedBuilder builder        = new EmbedBuilder {
                Title = "Oxford Dictionary Definitions"
            };

            try
            {
                var webRequest = WebRequest.Create(WEBSERVICE_URL);
                if (webRequest != null)
                {
                    webRequest.Method      = "GET";
                    webRequest.Timeout     = 12000;
                    webRequest.ContentType = "application/json";
                    webRequest.Headers.Add("app_id", _OXFORDID_);
                    webRequest.Headers.Add("app_key", _OXFORDKEY_);

                    using (Stream s = webRequest.GetResponse().GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(s))
                        {
                            jsonResponse = sr.ReadToEnd();
                            oxfLemma     = JsonConvert.DeserializeObject <OxfordLemma>(jsonResponse);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await LogWriter.WriteLogFile($"ERROR: Exception thrown : {ex.Message}");

                await LogWriter.WriteLogFile($"{ex.StackTrace}");

                Console.WriteLine($"Exception: {ex.Message}");
            }

            if (oxfLemma.Results != null)
            {
                string newTerm = oxfLemma.Results.First(lex => lex.LexicalEntries[0].Text != null).LexicalEntries[0].Text.ToLower();
                WEBSERVICE_URL = "https://od-api.oxforddictionaries.com:443/api/v2/entries/en-gb/" + newTerm;

                try
                {
                    var webRequest = WebRequest.Create(WEBSERVICE_URL);
                    if (webRequest != null)
                    {
                        webRequest.Method      = "GET";
                        webRequest.Timeout     = 12000;
                        webRequest.ContentType = "application/json";
                        webRequest.Headers.Add("app_id", _OXFORDID_);
                        webRequest.Headers.Add("app_key", _OXFORDKEY_);

                        using (Stream s = webRequest.GetResponse().GetResponseStream())
                        {
                            using (StreamReader sr = new StreamReader(s))
                            {
                                jsonResponse = sr.ReadToEnd();
                                oxfEntry     = JsonConvert.DeserializeObject <OxfordEntry>(jsonResponse);
                                var actualRes = oxfEntry.Results[0].LexicalEntries.First(e => e.Entries[0].Senses[0].Definitions != null).Entries[0].Senses[0];
                                builder.AddField(newTerm, actualRes.Definitions[0]);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    await LogWriter.WriteLogFile($"ERROR: Exception thrown : {ex.Message}");

                    await LogWriter.WriteLogFile($"{ex.StackTrace}");

                    Console.WriteLine($"Exception: {ex.Message}");
                }
            }

            if (builder.Fields.Count == 0)
            {
                var             c = (ITextChannel)Context.Channel;
                RestUserMessage m;
                if (c.IsNsfw)
                {
                    m = await Context.Channel.SendMessageAsync("Failed to find this on the Oxford Dictionary, trying again on Urban Dictionary.");
                    await UrbDefine(term);

                    GlobalVars.AddRandomTracker(m);
                }
                else
                {
                    await Context.Channel.SendMessageAsync("Nothing found, try again in a channel marked NSFW.");
                }
                return;
            }
            else
            {
                await Context.Channel.SendMessageAsync(null, false, builder.Build());
            }
        }
Esempio n. 28
0
        public async Task ListCommands([Remainder] string arg = "")
        {
            var prefix = Context.Message.Content.Substring(0, 1);

            EmbedBuilder eb = new EmbedBuilder();

            eb.WithColor(Color.Blue);
            if (arg == "")
            {
                eb.Title = "Currently available command categories";
                eb.AddField("Reserve", $"For more commands: {prefix}help reserve");
                eb.AddField("NAP", $"For more commands: {prefix}help nap");
                eb.AddField("Aug", $"For more commands: {prefix}help aug");
                eb.AddField("Ship", $"For more commands: {prefix}help ship");
                eb.AddField("Misc", $"For more commands: {prefix}help misc");
            }
            else
            {
                #region Add Commands to EmbedBuilder
                switch (arg.ToLower())
                {
                case "reserve":
                    #region Reserve commands
                    eb.AddField($"{prefix}reserve [coord1] [coord2]", $"Reserve a station.");
                    eb.AddField($"{prefix}reserve list <@User>", $"List all reserved locations by yourself or by [@User]");
                    eb.AddField($"{prefix}reserve check <coord1> <coord2>", $"Check which stations have been reserved by members of your alliance\nOptional parameters: coordinates.");
                    eb.AddField($"{prefix}reserve remove [coord1] [coord2]", $"Remove a location you have reserved in the past.");
                    #endregion
                    break;

                case "nap":
                    #region NAP commands
                    eb.AddField($"{prefix}nap list", $"View all active Non-Aggression Pacts for your Alliance.");
                    eb.AddField($"{prefix}nap add [AllianceName] <AllianceTag>", $"Add a new active Non-Aggression Pact.\n**NOTE:** Make sure you replaces any whitespace in the Alliance's name with an underscore (_)");
                    eb.AddField($"{prefix}nap remove [AllianceName]", $"Remove an inactive Non-Aggression Pact.");
                    #endregion
                    break;

                case "aug":
                    #region Aug commands
                    eb.AddField($"{prefix}aug request [coord1] [coord2]", "Put in a request for an augmentation on your outposts.");
                    eb.AddField($"{prefix}aug search <amount>", "Get the [amount] oldest augmentation requests.");
                    eb.AddField($"{prefix}aug search [@User] <amount>", "Get the [amount] oldest augmentation requests by [@User]");
                    eb.AddField($"{prefix}aug complete [ID]", $"Mark an augmentation request as being completed. (ID can be found using {prefix}aug search)");
                    eb.AddField($"{prefix}aug complete [@User] [coord1] [coord2]", "Mark an augmentation request on location [coord1,coord2] by [@User] as completed.");
                    #endregion
                    break;

                case "ship":
                    #region Ship commands
                    eb.AddField($"{prefix}ship request [ship name] [amount] [coord1] [coord2]", "Put in a request for ships on your outposts.");
                    eb.AddField($"{prefix}ship search <amount>", "Get the [amount] oldest ship requests.");
                    eb.AddField($"{prefix}ship search [@User] <amount>", "Get the [amount] oldest ship requests by [@User]");
                    eb.AddField($"{prefix}ship complete [ID]", $"Mark a ship request as being completed. (ID can be found using {prefix}ship search)");
                    eb.AddField($"{prefix}ship complete [@User] [coord1] [coord2]", "Mark a ship request on location [coord1,coord2] by [@User] as completed.");
                    #endregion
                    break;

                case "misc":
                    #region Misc commands
                    eb.AddField($"{prefix}userinfo [@User]", "Get information for a user in this alliance.");
                    eb.AddField($"{prefix}reserve max [amount]", $"Set a maximum on howmany locations each user can reserve.\n*(Administrator permissions required)*");
                    eb.AddField($"{prefix}warn max [amount]", $"Set the maximum amount of warnings a user can receive before facing consequences.\n*(Administrator permission required)*");
                    eb.AddField($"{prefix}warn [@User]", $"Add a warning to [@User]'s record, also displays current amount of warnings.\n*(Administrator permission required)*");
                    eb.AddField($"{prefix}prefix [New Prefix]", $"Change the prefix to which the bot responds here!\n*(Administrator permission required)*");
                    #endregion
                    break;

                default:
                    var m = await Context.Channel.SendMessageAsync($"Unknown Help topic: \"{arg}\"");

                    GlobalVars.AddRandomTracker(m);
                    return;
                }
                #endregion
            }
            await Context.Channel.SendMessageAsync(null, false, eb.Build());
        }
Esempio n. 29
0
        public async Task Roll(string roll)
        {
            Regex regex = new Regex(@"^(\d+)[dD](\d+)([\+\-]?)(\d*)");

            if (!regex.IsMatch(roll))
            {
                var m = await Context.Channel.SendMessageAsync($"Invalid roll format.");

                GlobalVars.AddRandomTracker(m);
                return;
            }
            var    match    = regex.Match(roll);
            int    amt      = int.Parse(match.Groups[1].Value);
            int    size     = int.Parse(match.Groups[2].Value);
            int    modifier = 0;
            string modSign  = match.Groups[3].Value;

            if (modSign == "+")
            {
                modifier += int.Parse(match.Groups[4].Value);
            }
            else if (modSign == "-")
            {
                modifier -= int.Parse(match.Groups[4].Value);
            }
            else
            {
                modSign = "";
            }


            if (((long)amt * (long)size + (long)modifier) > int.MaxValue)
            {
                var m = await Context.Channel.SendMessageAsync($"A roll this size could end up breaking my poor brain, please divide your rolls or choose lower values.");

                GlobalVars.AddRandomTracker(m);
                return;
            }

            string result = "";
            int    total  = 0;

            for (int i = 0; i < amt; i++)
            {
                if (i > 0)
                {
                    result += ", ";
                }
                int t = r.Next(1, size + 1);
                total += t;

                if (t == size)
                {
                    result += $"**__{t.ToString()}__**";
                }
                else if (t == 1)
                {
                    result += $"__{t.ToString()}__";
                }
                else
                {
                    result += t.ToString();
                }
            }

            await Context.Channel.SendMessageAsync($"{Context.User.Mention} has rolled {(total+modifier).ToString()} {(modifier != 0 ? $"*({total.ToString()} + {(modifier > 0 ? modifier.ToString() : $"({modifier.ToString()})")})*" : "")}: ({result}). ");
        }