//When a user has been banned, tell it them in the welcomings channel.
        public static async Task UserBannedAsync(SocketUser user, SocketGuild guild)
        {
            var server = Tools.GetServerInfo(guild.Id);

            if (server.welcomingChannel == 0)
                return;

            await Tools.ReplyAsync(user, Storage.client.GetChannel(server.welcomingChannel) as ITextChannel, 
                $"**{user.Mention}** has been banned from the server. ({user.Username})", 
                false);
        }
Esempio n. 2
0
        /// <summary>
        /// Posts any moderation actions done with the bot into the assigned mod log channel if one is assigned.
        /// Post is an embed that shares the action, target'd user, user that used the command, and reason for the command.
        /// </summary>
        /// <param name="guild">The guild the command was used in.</param>
        /// <param name="action">The moderation action that was used.</param>
        /// <param name="user">The moderator who used the command.</param>
        /// <param name="target">The user targeted by the command.</param>
        /// <param name="reason">The reason for using the command.</param>
        /// <returns></returns>
        public static async Task PostInModLog(SocketGuild guild, string action, SocketUser user, IGuildUser target, [Remainder] string reason)
        {
            //Channel to send the chat logs in
            ulong channel = Data.Data.GetModLogChannel(guild.Id);

            if (channel != 0) //If a channel has been assigned as the mod log channel
            {
                Random            ran         = new Random();
                int               color1      = ran.Next(0, 256); //Gets a random color for the embed
                int               color2      = ran.Next(0, 256);
                int               color3      = ran.Next(0, 256);
                SocketTextChannel channelPost = guild.GetTextChannel(channel);
                if (target != null) //If action was targeted at a user
                {
                    //Embedbuilder object
                    EmbedBuilder Embed = new EmbedBuilder();
                    Embed.AddField("Action:", action);
                    Embed.AddField("Targeted User:"******"{target.Username} ({target.Mention})");
                    Embed.AddField("Moderator:", $"{user.Username} ({user.Mention})");
                    Embed.AddField("Reason:", reason);

                    //Assign the author's image
                    Embed.WithThumbnailUrl(user.GetAvatarUrl());

                    //Add the timestamp to the bottom
                    Embed.WithCurrentTimestamp();

                    //Assign the color on the left side
                    Embed.WithColor(color1, color2, color3);

                    try
                    {
                        await channelPost.SendMessageAsync("", false, Embed.Build());
                    }
                    catch (Exception)
                    {
                        await user.SendMessageAsync("I do not have permission to post in the mod log. Please inform the administrator of the server.");
                    }
                }
                else //If action was not targeted at a user
                {
                    //Embedbuilder object
                    EmbedBuilder Embed = new EmbedBuilder();
                    Embed.AddField("Action:", action);
                    Embed.AddField("Moderator:", $"{user.Username} ({user.Mention})");

                    if (reason != "")
                    {
                        Embed.AddField("Reason:", reason);
                    }

                    //Assign the author's image
                    Embed.WithThumbnailUrl(user.GetAvatarUrl());
                    Embed.WithCurrentTimestamp();

                    //Assign the color on the left side
                    Embed.WithColor(color1, color2, color3);
                    try
                    {
                        await channelPost.SendMessageAsync("", false, Embed.Build());
                    }
                    catch (Exception)
                    {
                        await user.SendMessageAsync("I do not have permission to post in the mod log. Please inform the administrator of the server.");
                    }
                }
            }
        }
Esempio n. 3
0
        public async Task Handle(SocketMessage msg, SocketGuild guild, CommandHandler commandHandler)
        {
            var exec = commandHandler.GetExecutingCommand(msg.Author.Id);

            if (exec == this)
            {
                if (Progress == 0)
                {
                    DateTime date_time;
                    if (DateTime.TryParseExact(msg.Content, new string[] { "d/M/yyyy H:m", "d/M/yyyy h:m tt", "d/M/yyyy h tt", "d/M/yyyy H" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out date_time))
                    {
                        this.date_time = date_time;
                        messages.Add(msg);
                        messages.Add(await msg.Channel.SendMessageAsync("Enter proposition team name/number"));
                        Progress += 1;
                    }
                    else
                    {
                        messages.Add(await msg.Channel.SendMessageAsync("Please enter a valid date and time in dd/mm/yyyy hh:mm PM/AM form"));
                    }
                }
                else if (Progress == 1)
                {
                    Prop      = msg.Content.Trim();
                    Progress += 1;
                    messages.Add(msg);
                    messages.Add(await msg.Channel.SendMessageAsync("Enter opposition team name/number"));
                }
                else if (Progress == 2)
                {
                    Opp       = msg.Content.Trim();
                    Progress += 1;
                    messages.Add(msg);
                    messages.Add(await msg.Channel.SendMessageAsync("Enter motion"));
                }
                else if (Progress == 3)
                {
                    Motion    = msg.Content.Trim();
                    Progress += 1;
                    messages.Add(msg);

                    var channel = guild.GetChannel(Clubby.Program.config.DiscordChannels["announcements"]) as SocketTextChannel;

                    if (channel != null)
                    {
                        var announcement = (await channel.SendMessageAsync(null, false,
                                                                           new EmbedBuilder()
                                                                           .WithTitle($"Announcement #{Clubby.Program.config.DiscordAnnouncements.Count}")
                                                                           .WithAuthor(msg.Author)
                                                                           .WithColor(Color.Blue)
                                                                           .WithDescription($"The next debate will take place on {date_time.DayOfWeek.ToString()}({date_time.Day}/{date_time.Month}/{date_time.Year}) at {new DateTime(date_time.TimeOfDay.Ticks).ToString("h:mm tt")}")
                                                                           .AddField("Proposition:", Prop)
                                                                           .AddField("Opposition:", Opp)
                                                                           .AddField($"The motion is:", Motion)
                                                                           .Build())).Id;

                        SchedulerEvent reminder = new SchedulerEvent();
                        reminder.channel = channel.Id;
                        reminder.message = null;
                        reminder.embed   = new EmbedBuilder().WithColor(Color.Green).WithTitle("Reminder").WithDescription($"Team {Prop} and Team {Opp} have a debate in 5 mins").AddField("Motion:", Motion);
                        reminder.name    = "Weekly Debate";

                        Debate debate = new Debate();
                        debate.Context     = "-";
                        debate.Motion      = Motion;
                        debate.Proposition = Prop;
                        debate.Opposition  = Opp;
                        debate.date        = date_time;
                        try
                        {
                            Clubby.Program.config.UnfinishedDebates.Add(Clubby.Program.config.DiscordAnnouncements.Count, debate);
                            Clubby.Program.config.scheduler.Schedule("Weeklies", Clubby.Program.config.DiscordAnnouncements.Count, reminder, date_time - TimeSpan.FromMinutes(5));

                            Clubby.Program.config.DiscordAnnouncements.Add((AnnouncementType.Weekly, announcement));
                        }
                        catch (Exception e)
                        {
                            await msg.Channel.SendError(e.Message);
                        }

                        await msg.Channel.SendOk("Announcement Made!");
                    }
                    else
                    {
                        await msg.Channel.SendError("Announcement channel not set!");
                    }

                    await(msg.Channel as SocketTextChannel).DeleteMessagesAsync(messages);

                    commandHandler.SetExecutingCommand(msg.Author.Id, null);
                }
            }
            else if (exec == null)
            {
                messages.Add(await msg.Channel.SendMessageAsync("Enter a valid date and time in dd/mm/yyyy hh:mm PM/AM form"));
                Progress += 1;
                commandHandler.SetExecutingCommand(msg.Author.Id, this);
            }
        }
Esempio n. 4
0
 public static bool TryGetTextChannel(this SocketGuild server, ulong id, out SocketTextChannel result) => (result = server.GetChannel(id) as SocketTextChannel) != null;
Esempio n. 5
0
 public static SocketTextChannel GetTextChannel(this SocketGuild server, string name) => server.TryGetTextChannel(name, out var result) ? result : throw new BotError($"Unknown text channel: `{name}`.");
Esempio n. 6
0
 public static bool TryGetChannel(this SocketGuild server, string name, out SocketGuildChannel result) => server.Channels.TryGetFirst(c => c.Name == name, out result);
Esempio n. 7
0
 public UserJoinedEventArgs(SocketGuildUser user)
 {
     User  = user;
     Guild = user.Guild;
 }
Esempio n. 8
0
        private async Task <SocketRole> GenerateRoleAsync(SocketGuild guild, string roleName)
        {
            await guild.CreateRoleAsync(roleName, color : Color.Teal);

            return(await GetRoleAsync(guild, roleName));
        }
 /// <summary>
 ///     Constructs a new <see cref="JoinedGuildNotification" /> from the given values.
 /// </summary>
 /// <param name="guild">The value to use for <see cref="Guild" />.</param>
 /// <exception cref="ArgumentNullException">Throws for <paramref name="guild" />.</exception>
 public JoinedGuildNotification(SocketGuild guild) =>
Esempio n. 10
0
 private Task _client_LeftGuild(SocketGuild arg)
 {
     GuildConfigsCache.TryRemove(arg.Id, out _);
     return(Task.CompletedTask);
 }
Esempio n. 11
0
        static async Task _client_JoinedGuild(SocketGuild arg)
        {
            tempRole = await arg.CreateRoleAsync("TempMember", Discord.GuildPermissions.None, Discord.Color.LightGrey, true, null);

            Scheduler();
        }
Esempio n. 12
0
 public async Task UpdateData(SocketGuild guild) => savedInvites = (await guild.GetInvitesAsync()).ToDictionary(x => x.Code);
Esempio n. 13
0
 private Task Client_LeftGuild(SocketGuild arg)
 {
     _log.Info("Left server: {0} [{1}]", arg?.Name, arg?.Id);
     return(Task.CompletedTask);
 }
Esempio n. 14
0
        public async Task TryRunCommand(SocketGuild guild, ITextChannel channel, IUserMessage usrMsg)
        {
            var execTime = Environment.TickCount;

            if (guild != null && guild.OwnerId != usrMsg.Author.Id)
            {
                if (await InviteFiltered(guild, usrMsg).ConfigureAwait(false))
                {
                    return;
                }

                if (await WordFiltered(guild, usrMsg).ConfigureAwait(false))
                {
                    return;
                }
            }

            if (IsBlacklisted(guild, usrMsg))
            {
                return;
            }

            var exec1 = Environment.TickCount - execTime;


            var cleverBotRan = await Task.Run(() => TryRunCleverbot(usrMsg, guild)).ConfigureAwait(false);

            if (cleverBotRan)
            {
                return;
            }

            var exec2 = Environment.TickCount - execTime;

            // maybe this message is a custom reaction
            // todo log custom reaction executions. return struct with info
            var cr = await Task.Run(() => CustomReactions.TryGetCustomReaction(usrMsg)).ConfigureAwait(false);

            if (cr != null) //if it was, don't execute the command
            {
                try
                {
                    if (guild != null)
                    {
                        PermissionCache pc = Permissions.GetCache(guild.Id);

                        int index;
                        if (
                            !pc.Permissions.CheckPermissions(usrMsg, cr.Trigger, "ActualCustomReactions",
                                                             out index))
                        {
                            //todo print in guild actually
                            var returnMsg =
                                $"Permission number #{index + 1} **{pc.Permissions[index].GetCommand(guild)}** is preventing this action.";
                            _log.Info(returnMsg);
                            return;
                        }
                    }
                    await cr.Send(usrMsg).ConfigureAwait(false);

                    if (cr.AutoDeleteTrigger)
                    {
                        try { await usrMsg.DeleteAsync().ConfigureAwait(false); } catch { }
                    }
                }
                catch (Exception ex)
                {
                    _log.Warn("Sending CREmbed failed");
                    _log.Warn(ex);
                }
                return;
            }

            var exec3 = Environment.TickCount - execTime;

            string messageContent = usrMsg.Content;

            if (guild != null)
            {
                ConcurrentDictionary <string, string> maps;
                if (Modules.Utility.Utility.CommandMapCommands.AliasMaps.TryGetValue(guild.Id, out maps))
                {
                    var keys = maps.Keys
                               .OrderByDescending(x => x.Length);

                    var lowerMessageContent = messageContent.ToLowerInvariant();
                    foreach (var k in keys)
                    {
                        string newMessageContent;
                        if (lowerMessageContent.StartsWith(k + " "))
                        {
                            newMessageContent = maps[k] + messageContent.Substring(k.Length, messageContent.Length - k.Length);
                        }
                        else if (lowerMessageContent == k)
                        {
                            newMessageContent = maps[k];
                        }
                        else
                        {
                            continue;
                        }

                        _log.Info(@"--Mapping Command--
    GuildId: {0}
    Trigger: {1}
    Mapping: {2}", guild.Id, messageContent, newMessageContent);
                        var oldMessageContent = messageContent;
                        messageContent = newMessageContent;

                        try { await usrMsg.Channel.SendConfirmAsync($"{oldMessageContent} => {newMessageContent}").ConfigureAwait(false); } catch { }
                        break;
                    }
                }
            }


            // execute the command and measure the time it took
            var exec = await Task.Run(() => ExecuteCommand(new CommandContext(_client, usrMsg), messageContent, DependencyMap.Empty, MultiMatchHandling.Best)).ConfigureAwait(false);

            execTime = Environment.TickCount - execTime;

            if (exec.Result.IsSuccess)
            {
                await CommandExecuted(usrMsg, exec.CommandInfo).ConfigureAwait(false);
                await LogSuccessfulExecution(usrMsg, exec, channel, exec1, exec2, exec3, execTime).ConfigureAwait(false);
            }
            else if (!exec.Result.IsSuccess && exec.Result.Error != CommandError.UnknownCommand)
            {
                LogErroredExecution(usrMsg, exec, channel, exec1, exec2, exec3, execTime);
                if (guild != null && exec.CommandInfo != null && exec.Result.Error == CommandError.Exception)
                {
                    if (exec.PermissionCache != null && exec.PermissionCache.Verbose)
                    {
                        try { await usrMsg.Channel.SendMessageAsync("⚠️ " + exec.Result.ErrorReason).ConfigureAwait(false); } catch { }
                    }
                }
            }
            else
            {
                if (usrMsg.Channel is IPrivateChannel)
                {
                    // rofl, gotta do this to prevent dm help message being sent to
                    // users who are voting on private polls (sending a number in a DM)
                    int vote;
                    if (int.TryParse(usrMsg.Content, out vote))
                    {
                        return;
                    }

                    await usrMsg.Channel.SendMessageAsync(Help.DMHelpString).ConfigureAwait(false);

                    await SelfCommands.HandleDmForwarding(usrMsg, ownerChannels).ConfigureAwait(false);
                }
            }
        }
Esempio n. 15
0
 public override void Initialize(SocketGuild server)
 {
     messageJoin   = "Welcome! Please enjoy your stay!";
     messageRejoin = "Welcome back! Were you get kicked or something? Anyway, enjoy your stay!";
 }
Esempio n. 16
0
        public async Task <SocketRole> GetRoleAsync(SocketGuild guild, string roleName)
        {
            var adminRole = guild.Roles.FirstOrDefault(x => x.Name == roleName);

            return(adminRole ?? await GenerateRoleAsync(guild, roleName));
        }
        public static string GetCommand(this Permissionv2 perm, string prefix, SocketGuild guild = null)
        {
            var com = "";

            switch (perm.PrimaryTarget)
            {
            case PrimaryPermissionType.User:
                com += "u";
                break;

            case PrimaryPermissionType.Channel:
                com += "c";
                break;

            case PrimaryPermissionType.Role:
                com += "r";
                break;

            case PrimaryPermissionType.Server:
                com += "s";
                break;
            }

            switch (perm.SecondaryTarget)
            {
            case SecondaryPermissionType.Module:
                com += "m";
                break;

            case SecondaryPermissionType.Command:
                com += "c";
                break;

            case SecondaryPermissionType.AllModules:
                com = "a" + com + "m";
                break;
            }

            var secName = perm.SecondaryTarget == SecondaryPermissionType.Command && !perm.IsCustomCommand ?
                          prefix + perm.SecondaryTargetName : perm.SecondaryTargetName;

            com += " " + (perm.SecondaryTargetName != "*" ? secName + " " : "") + (perm.State ? "enable" : "disable") + " ";

            switch (perm.PrimaryTarget)
            {
            case PrimaryPermissionType.User:
                com += guild?.GetUser(perm.PrimaryTargetId)?.ToString() ?? $"<@{perm.PrimaryTargetId}>";
                break;

            case PrimaryPermissionType.Channel:
                com += $"<#{perm.PrimaryTargetId}>";
                break;

            case PrimaryPermissionType.Role:
                com += guild?.GetRole(perm.PrimaryTargetId)?.ToString() ?? $"<@&{perm.PrimaryTargetId}>";
                break;

            case PrimaryPermissionType.Server:
                break;
            }

            return(prefix + com);
        }
Esempio n. 18
0
        private async Task <SocketChannel> GetChannelAsync(SocketGuild guild, string channelName)
        {
            var channel = guild.TextChannels.FirstOrDefault(x => x.Name == channelName);

            return(channel ?? await GenerateChannelAsync(guild, channelName));
        }
Esempio n. 19
0
 public GuildStats(SocketGuild socketGuild) => ID = socketGuild.Id;
Esempio n. 20
0
 public static bool TryGetServer(this DiscordSocketClient client, string name, out SocketGuild result) => client.Guilds.TryGetFirst(c => c.Name == name, out result);
Esempio n. 21
0
 private SocketTextChannel FindChannelById(SocketGuild server, ulong id)
 {
     Trace($"Trying to find channel in {server} by id: {id}");
     return((from c in server.TextChannels where c.Id == id select c).FirstOrDefault());
 }
Esempio n. 22
0
 public static SocketTextChannel GetTextChannel(this SocketGuild server, ulong id) => server.TryGetTextChannel(id, out var result) ? result : throw new BotError($"Unknown text channel id: `{id}`.");
Esempio n. 23
0
 public Server(SocketGuild guild)
 {
     this.Id    = guild.Id;
     this.Guild = guild;
 }
Esempio n. 24
0
 public static bool TryGetServer(this DiscordSocketClient client, ulong id, out SocketGuild result) => (result = client.GetGuild(id)) != null;
Esempio n. 25
0
        /*
         * private async Task OnMessageUpdated(Cacheable<IMessage, ulong> msgBefore, SocketMessage msgAfter, ISocketMessageChannel channel)
         * {
         *  var guild = (channel as SocketTextChannel)?.Guild;
         *  var message = await msgBefore.GetOrDownloadAsync();
         *  await _serverHelper.SendLogAsync(guild, "Situation Log", $"Message Edited: {msgBefore.Value.Author.Username}#{msgBefore.Value.Author.DiscriminatorValue} edited {message.ToString() ?? "A message was updated, but its content could not be retrieved from cache."}\nTo: {msgAfter.Content.ToString()}.");
         *  return;
         *
         * }*/
        /*
         * private async Task OnMessageDeleted(Cacheable<IMessage, ulong> msg, ISocketMessageChannel channel)
         * {
         *  var guild = (channel as SocketTextChannel)?.Guild;
         *  if (msg.Value.Content == null)
         *  {
         *      await _serverHelper.SendLogAsync(guild, "Situation Log", $"Message Deleted: A message was deleted, but its content could not be retrieved from cache.");
         *  }
         *  else
         *  {
         *      var message = await msg.GetOrDownloadAsync();
         *      await _serverHelper.SendLogAsync(guild, "Situation Log", $"Message Deleted: {msg.Value.Author.Username}#{msg.Value.Author.DiscriminatorValue} said {message.ToString()}.");
         *      return;
         *  }
         * }
         */

        private async Task OnLeftGuild(SocketGuild arg)
        {
            await _client.SetGameAsync($"over {_client.Guilds.Count} servers!", null, ActivityType.Watching);
        }
Esempio n. 26
0
 public async Task BotJoined(SocketGuild guild)
 {
     //Set up bot if first time running
     Xml.Setup(client.Guilds.ToList(), commands);
 }
Esempio n. 27
0
 private SocketRole GetEveryoneRole(SocketGuild guild)
 {
     return(guild.EveryoneRole);
 }
Esempio n. 28
0
 private Task _client_LeftGuild(SocketGuild arg)
 {
     _guildReactions.TryRemove(arg.Id, out _);
     return(Task.CompletedTask);
 }
Esempio n. 29
0
        private async Task <SocketCategoryChannel> GetBaseCategoryAsync(SocketGuild guild)
        {
            var baseCategory = guild.CategoryChannels.FirstOrDefault(x => x.Name == ChannelNames.Category);

            return(baseCategory ?? await GenerateBaseCategory(guild));
        }
Esempio n. 30
0
        private async Task <SocketCategoryChannel> GenerateBaseCategory(SocketGuild guild)
        {
            await guild.CreateCategoryChannelAsync(ChannelNames.Category, func : x => { x.Position = -1; });

            return(guild.CategoryChannels.FirstOrDefault(x => x.Name == ChannelNames.Category));
        }
Esempio n. 31
0
        public async Task TryRunCommand(SocketGuild guild, ISocketMessageChannel channel, IUserMessage usrMsg)
        {
            var execTime = Environment.TickCount;

            //its nice to have early blockers and early blocking executors separate, but
            //i could also have one interface with priorities, and just put early blockers on
            //highest priority. :thinking:
            foreach (var beh in _earlyBehaviors)
            {
                if (await beh.RunBehavior(_client, guild, usrMsg).ConfigureAwait(false))
                {
                    if (beh.BehaviorType == ModuleBehaviorType.Blocker)
                    {
                        _log.Info("Blocked User: [{0}] Message: [{1}] Service: [{2}]", usrMsg.Author, usrMsg.Content, beh.GetType().Name);
                    }
                    else if (beh.BehaviorType == ModuleBehaviorType.Executor)
                    {
                        _log.Info("User [{0}] executed [{1}] in [{2}]", usrMsg.Author, usrMsg.Content, beh.GetType().Name);
                    }
                    return;
                }
            }

            var exec2 = Environment.TickCount - execTime;

            string messageContent = usrMsg.Content;

            foreach (var exec in _inputTransformers)
            {
                string newContent;
                if ((newContent = await exec.TransformInput(guild, usrMsg.Channel, usrMsg.Author, messageContent).ConfigureAwait(false)) != messageContent.ToLowerInvariant())
                {
                    messageContent = newContent;
                    break;
                }
            }
            var prefix          = GetPrefix(guild?.Id);
            var isPrefixCommand = messageContent.StartsWith(".prefix", StringComparison.InvariantCultureIgnoreCase);

            // execute the command and measure the time it took
            if (messageContent.StartsWith(prefix, StringComparison.InvariantCulture) || isPrefixCommand)
            {
                var(Success, Error, Info) = await ExecuteCommandAsync(new CommandContext(_client, usrMsg), messageContent, isPrefixCommand? 1 : prefix.Length, _services, MultiMatchHandling.Best).ConfigureAwait(false);

                execTime = Environment.TickCount - execTime;

                if (Success)
                {
                    await LogSuccessfulExecution(usrMsg, channel as ITextChannel, exec2, execTime).ConfigureAwait(false);
                    await CommandExecuted(usrMsg, Info).ConfigureAwait(false);

                    return;
                }
                else if (Error != null)
                {
                    LogErroredExecution(Error, usrMsg, channel as ITextChannel, exec2, execTime);
                    if (guild != null)
                    {
                        await CommandErrored(Info, channel as ITextChannel, Error).ConfigureAwait(false);
                    }
                }
            }
            else
            {
                await OnMessageNoTrigger(usrMsg).ConfigureAwait(false);
            }

            foreach (var exec in _lateExecutors)
            {
                await exec.LateExecute(_client, guild, usrMsg).ConfigureAwait(false);
            }
        }