Пример #1
0
 internal static string CleanUserMentions(Channel channel, string text, List<User> users = null)
 {
     ulong id;
     text = _userNicknameRegex.Replace(text, new MatchEvaluator(e =>
     {
         if (e.Value.Substring(3, e.Value.Length - 4).TryToId(out id))
         {
             var user = channel.GetUserFast(id);
             if (user != null)
             {
                 if (users != null)
                     users.Add(user);
                 return '@' + user.Nickname;
             }
         }
         return e.Value; //User not found or parse failed
     }));
     return _userRegex.Replace(text, new MatchEvaluator(e =>
     {
         if (e.Value.Substring(2, e.Value.Length - 3).TryToId(out id))
         {
             var user = channel.GetUserFast(id);
             if (user != null)
             {
                 if (users != null)
                     users.Add(user);
                 return '@' + user.Name;
             }
         }
         return e.Value; //User not found or parse failed
     }));
 }
Пример #2
0
 public TypingGame(Channel channel)
 {
     this.channel = channel;
     IsActive = false;
     sw = new Stopwatch();
     finishedUserIds = new List<ulong>();
 }
Пример #3
0
        public async Task StopPoll(Channel ch) {
            NadekoBot.client.MessageReceived -= Vote;
            Poll throwaway;
            PollCommand.ActivePolls.TryRemove(e.Server, out throwaway);
            try {
                var results = participants.GroupBy(kvp => kvp.Value)
                                .ToDictionary(x => x.Key, x => x.Sum(kvp => 1))
                                .OrderBy(kvp => kvp.Value);

                int totalVotesCast = results.Sum(kvp => kvp.Value);
                if (totalVotesCast == 0) {
                    await ch.SendMessage("📄 **No votes have been cast.**");
                    return;
                }
                var closeMessage = $"--------------**POLL CLOSED**--------------\n" +
                                   $"📄 , here are the results:\n";
                foreach (var kvp in results) {
                    closeMessage += $"`{kvp.Key}.` **[{answers[kvp.Key - 1]}]** has {kvp.Value} votes.({kvp.Value * 1.0f / totalVotesCast * 100}%)\n";
                }

                await ch.SendMessage($"📄 **Total votes cast**: {totalVotesCast}\n{closeMessage}");
            } catch (Exception ex) {
                Console.WriteLine($"Error in poll game {ex}");
            }
        }
Пример #4
0
        public bool CanRun(Command command, User user, Channel channel, out string error)
        {
            error = null;

            if (channel.IsPrivate)
                return DefaultPermissionLevel <= DefaultPermChecker.GetPermissionLevel(user, channel);

            DynPermFullData data = DynPerms.GetPerms(channel.Server.Id);

            // apply default perms.
            bool retval = DefaultPermissionLevel <= DefaultPermChecker.GetPermissionLevel(user, channel);

            // if we do not have dynamic perms in place for the user's server, return the default perms.
            if (data == null || (!data.Perms.RolePerms.Any() && !data.Perms.UserPerms.Any()))
                return retval;

            /* 
              Firsly do role checks.
              Lower entries override higher entries. 
              To do that we have to iterate over the dict instead of using roles the user has as keys.
            */

            foreach (var pair in data.Perms.RolePerms)
            {
                if (user.HasRole(pair.Key))
                    retval = EvaluatePerms(pair.Value, command, retval, channel, ref error);
            }

            // users override roles, do them next.
            DynamicPermissionBlock permBlock;
            if (data.Perms.UserPerms.TryGetValue(user.Id, out permBlock))
                retval = EvaluatePerms(permBlock, command, retval, channel, ref error);

            return retval;
        }
Пример #5
0
        async Task MuteUser(Server server, Channel channel, User user, DateTime expiresOn)
        {
            try
            {
                // TODO: need to check if client has permissions and user is not the owner
                var mutedRole = server.Roles.SingleOrDefault(r => r.Name == "Muted") 
                    ?? await CreateMutedRole(server);

                var punishment = new Punishment
                {
                    Id = Guid.NewGuid(),
                    Server = server,
                    Channel = channel,
                    User = user,
                    RolesBefore = user.Roles,
                    RolesAfter = new List<Role> { mutedRole },
                    ExpiresOn = expiresOn,
                    PunishmentType = PunishmentType.Mute,
                    Actioned = false
                };

                _botServices.Defence.PunishUser(punishment);

                await _client.EditUser(user, null, null, punishment.RolesAfter);
            } 
            catch (Exception ex)
            {
                _botServices.Logging.LogError(string.Format("Failed to add '{0} to the muted role'", user.Name), ex);
                throw;
            }
        }
Пример #6
0
        /// <summary>
        /// Get a number of messages from a channel.
        /// </summary>
        /// <param name="c">The channel</param>
        /// <param name="numReq">The number of messages requested</param>
        /// <returns></returns>
        public static async Task<IEnumerable<Message>> GetMessages(Channel c, int numReq)
        {
            int currentCount = 0;
            int numToGetThisLoop = 100;
            int newMsgCount = 100;
            ulong lastMsgId;
            IEnumerable<Message> allMsgs = new List<Message>();
            IEnumerable<Message> newMsgs = new List<Message>();
            if (numReq <= 0) return null;                                         //Quit on bad request

            lastMsgId = (await c.DownloadMessages(1))[0].Id;                        //Start from last message (will be excluded)

            while (currentCount < numReq && newMsgCount == numToGetThisLoop)      //Keep going while we don't have enough, and haven't reached end of channel
            {
                if (numReq - currentCount < 100)                                  //If we need less than 100 to achieve required number
                    numToGetThisLoop = numReq - currentCount;                     //Reduce number to get this loop

                newMsgs = await c.DownloadMessages(numToGetThisLoop, lastMsgId, Relative.Before, false);    //Get N messages before that id
                newMsgCount = newMsgs.Count();                                      //Get the count we downloaded, usually 100
                currentCount += newMsgCount;                                        //Add new messages to count
                lastMsgId = newMsgs.Last().Id;                                      //Get the id to start from on next iteration
                allMsgs = allMsgs.Concat(newMsgs);                                  //Add messages to the list
            }

            return allMsgs;
        }
Пример #7
0
 private void registerPurgeCmd()
 {
     commands.CreateCommand("purge")
     .Parameter("n", ParameterType.Required)
     .Parameter("channel", ParameterType.Optional)
     .AddCheck((cm, u, ch) => u.ServerPermissions.Administrator)
     .Do(async(e) =>
     {
         int.TryParse(e.GetArg("n"), out int n);
         if (n > 100)
         {
             await e.Channel.SendMessage("Uh... I can only delete up to a hundred messages at a time. Sorry...");
             return;
         }
         else if (e.GetArg("channel") == "")
         {
             Discord.Message[] messagesToDelete = await e.Channel.DownloadMessages(n);
             await e.Channel.DeleteMessages(messagesToDelete);
         }
         else
         {
             Discord.Channel channel = e.Server.FindChannels(e.GetArg("channel")).FirstOrDefault();
             Debug.WriteLine(channel.Name);
             Discord.Message[] messagesToDelete = await channel.DownloadMessages(n);
             await channel.DeleteMessages(messagesToDelete);
         }
         await e.Channel.SendMessage("Got 'em.");
     });
 }
Пример #8
0
		internal Invite(DiscordClient client, string code, string xkcdPass, string serverId, string inviterId, string channelId)
			: base(client, code)
		{
			XkcdCode = xkcdPass;
			_server = new Reference<Server>(serverId, x =>
			{
				var server = _client.Servers[x];
				if (server == null)
				{
					server = _generatedServer = new Server(client, x);
					server.Cache();
				}
				return server;
			});
			_inviter = new Reference<User>(serverId, x =>
			{
				var inviter = _client.Users[x, _server.Id];
				if (inviter == null)
				{
					inviter = _generatedInviter = new User(client, x, _server.Id);
					inviter.Cache();
				}
				return inviter;
			});
			_channel = new Reference<Channel>(serverId, x =>
			{
				var channel = _client.Channels[x];
				if (channel == null)
				{
					channel = _generatedChannel = new Channel(client, x, _server.Id, null);
					channel.Cache();
				}
				return channel;
			});
		}
Пример #9
0
        public bool CanRun(Command command, User user, Channel channel, out string error) {
            error = null;

            if (channel.IsPrivate)
                return true;

            try {
                //is it a permission command?
                // if it is, check if the user has the correct role
                // if yes return true, if no return false
                if (command.Category == "Permissions")
                    if (user.Server.IsOwner || user.HasRole(PermissionHelper.ValidateRole(user.Server, PermissionsHandler.GetServerPermissionsRoleName(user.Server))))
                        return true;
                    else
                        throw new Exception($"You don't have the necessary role (**{PermissionsHandler._permissionsDict[user.Server].PermissionsControllerRole}**) to change permissions.");

                var permissionType = PermissionsHandler.GetPermissionBanType(command, user, channel);

                string msg;

                switch (permissionType) {
                    case PermissionsHandler.PermissionBanType.None:
                        return true;
                    case PermissionsHandler.PermissionBanType.ServerBanCommand:
                        msg = $"**{command.Text}** command has been banned from use on this **server**.";
                        break;
                    case PermissionsHandler.PermissionBanType.ServerBanModule:
                        msg = $"**{command.Category}** module has been banned from use on this **server**.";
                        break;
                    case PermissionsHandler.PermissionBanType.ChannelBanCommand:
                        msg = $"**{command.Text}** command has been banned from use on this **channel**.";
                        break;
                    case PermissionsHandler.PermissionBanType.ChannelBanModule:
                        msg = $"**{command.Category}** module has been banned from use on this **channel**.";
                        break;
                    case PermissionsHandler.PermissionBanType.RoleBanCommand:
                        msg = $"You do not have a **role** which permits you the usage of **{command.Text}** command.";
                        break;
                    case PermissionsHandler.PermissionBanType.RoleBanModule:
                        msg = $"You do not have a **role** which permits you the usage of **{command.Category}** module.";
                        break;
                    case PermissionsHandler.PermissionBanType.UserBanCommand:
                        msg = $"{user.Mention}, You have been banned from using **{command.Text}** command.";
                        break;
                    case PermissionsHandler.PermissionBanType.UserBanModule:
                        msg = $"{user.Mention}, You have been banned from using **{command.Category}** module.";
                        break;
                    default:
                        return true;
                }
                if (PermissionsHandler._permissionsDict[user.Server].Verbose) //if verbose - print errors
                    Task.Run(() => channel.SendMessage(msg));
                return false;
            } catch (Exception ex) {
                if (PermissionsHandler._permissionsDict[user.Server].Verbose) //if verbose - print errors
                    Task.Run(() => channel.SendMessage(ex.Message));
                return false;
            }
        }
Пример #10
0
        public async Task Run()
        {
            var cancelToken = _client.CancelToken;

            try
            {
                while (!_client.CancelToken.IsCancellationRequested)
                {
                    foreach (var settings in _settings.AllServers)
                    {
                        foreach (var feed in settings.Value.Feeds)
                        {
                            try {
                                Discord.Channel channel           = _client.GetChannel(feed.Value.ChannelId);
                                DateTimeOffset  newestArticleTime = feed.Value.LastUpdate;
                                XmlReader       r     = XmlNodeReader.Create(feed.Key);
                                SyndicationFeed posts = SyndicationFeed.Load(r);
                                r.Close();
                                foreach (SyndicationItem item in posts.Items)
                                {
                                    if (item.LastUpdatedTime.CompareTo(feed.Value.LastUpdate) > 0)
                                    {
                                        foreach (SyndicationLink link in item.Links) //reddit only has one link. It links to the comments of the post.
                                        {
                                            _client.Log.Info("Feed", $"New article: {item.Title}");
                                            Console.WriteLine(item.Title.Text);
                                            Console.WriteLine("Article written at " + feed.Value.LastUpdate);
                                            Console.WriteLine(link.Uri.OriginalString);
                                            await channel.SendMessage(link.Uri.OriginalString);
                                        }
                                        if (item.LastUpdatedTime.CompareTo(newestArticleTime) > 0)
                                        {
                                            newestArticleTime = item.LastUpdatedTime;
                                        }
                                    }
                                    else
                                    {
                                        // break; Would be fine the Threads were sorted.
                                        // might as well do nothing and be safe.
                                    }
                                }
                                if (feed.Value.LastUpdate.CompareTo(newestArticleTime) != 0)
                                {
                                    feed.Value.LastUpdate = newestArticleTime;
                                    Console.WriteLine("Setting Updatetime to newest Article " + feed.Value.LastUpdate);
                                    await _settings.Save(settings.Key, settings.Value);
                                }
                            }
                            catch (Exception ex) when(!(ex is TaskCanceledException))
                            {
                                _client.Log.Error("Feed", ex);
                            }
                        }
                        await Task.Delay(TIME_BETWEEN_UPDATES, cancelToken);
                    }
                }
            }
            catch (TaskCanceledException) { }
        }
Пример #11
0
 internal static bool GetNsfw(Channel chan)
 {
     SQLiteDataReader reader = SQL.ExecuteReader("select nsfw from flags where channel = '" + chan.Id + "'");
     while (reader.Read())
         if (int.Parse(reader["nsfw"].ToString()) == 1)
             return true;
     return false;
 }
Пример #12
0
 public Task<Message[]> Help(Channel channel)
 {
     return client.SendMessage(channel,
         "List of commands:\n" +
         "・basics\n・birthday\n・music\n・picture\n・quote(wip)\n・timezone(wip)\n・game(wip)\n・feature request\n" +
         "Type !help <command> to learn more about the command"
     );
 }
		public Task SetChannelPermissions(Channel channel, Role role, ChannelPermissions allow = null, ChannelPermissions deny = null)
		{
			if (channel == null) throw new ArgumentNullException(nameof(channel));
			if (role == null) throw new ArgumentNullException(nameof(role));
			CheckReady();

			return SetChannelPermissions(channel, role?.Id, PermissionTarget.Role, allow, deny);
		}
		public Task RemoveChannelPermissions(Channel channel, User user)
		{
			if (channel == null) throw new ArgumentNullException(nameof(channel));
			if (user == null) throw new ArgumentNullException(nameof(user));
			CheckReady();

			return RemoveChannelPermissions(channel, user?.Id, PermissionTarget.User);
		}
Пример #15
0
 public MusicControls(Channel voiceChannel, CommandEventArgs e, float? vol) : this() {
     if (voiceChannel == null)
         throw new ArgumentNullException(nameof(voiceChannel));
     if (vol != null)
         Volume = (float)vol;
     VoiceChannel = voiceChannel;
     _e = e;
 }
		public Task SetChannelPermissions(Channel channel, User user, ChannelPermissions allow = null, ChannelPermissions deny = null)
		{
			if (channel == null) throw new ArgumentNullException(nameof(channel));
			if (user == null) throw new ArgumentNullException(nameof(user));
			CheckReady();

			return SetChannelPermissions(channel, user?.Id, PermissionTarget.User, allow, deny);
		}
		public Task SetChannelPermissions(Channel channel, Role role, DualChannelPermissions permissions = null)
		{
			if (channel == null) throw new ArgumentNullException(nameof(channel));
			if (role == null) throw new ArgumentNullException(nameof(role));
			CheckReady();

			return SetChannelPermissions(channel, role?.Id, PermissionTarget.Role, permissions?.Allow, permissions?.Deny);
		}
		public Task SetChannelPermissions(Channel channel, User user, DualChannelPermissions permissions = null)
		{
			if (channel == null) throw new ArgumentNullException(nameof(channel));
			if (user == null) throw new ArgumentNullException(nameof(user));
			CheckReady();

			return SetChannelPermissions(channel, user?.Id, PermissionTarget.User, permissions?.Allow, permissions?.Deny);
		}
Пример #19
0
 public  async void ExecuteCommand(Channel channel, Message message)
 {
     await channel.SendIsTyping();
     Thread.Sleep(5000);
     await
         channel.SendMessage(
             "What the f**k did you just f*****g say about me, you little bitch? I’ll have you know I graduated top of my class in the Navy Seals, and I’ve been involved in numerous secret raids on Al-Quaeda, and I have over 300 confirmed kills. I am trained in gorilla warfare and I’m the top sniper in the entire US armed forces. You are nothing to me but just another target. I will wipe you the f**k out with precision the likes of which has never been seen before on this Earth, mark my f*****g words. You think you can get away with saying that shit to me over the Internet? Think again, f****r. As we speak I am contacting my secret network of spies across the USA and your IP is being traced right now so you better prepare for the storm, maggot. The storm that wipes out the pathetic little thing you call your life. You’re f*****g dead, kid. I can be anywhere, anytime, and I can kill you in over seven hundred ways, and that’s just with my bare hands. Not only am I extensively trained in unarmed combat, but I have access to the entire arsenal of the United States Marine Corps and I will use it to its full extent to wipe your miserable ass off the face of the continent, you little shit. If only you could have known what unholy retribution your little “clever” comment was about to bring down upon you, maybe you would have held your f*****g tongue. But you couldn’t, you didn’t, and now you’re paying the price, you goddamn idiot. I will shit fury all over you and you will drown in it. You’re f*****g dead, kiddo.");
 }
Пример #20
0
 private async Task MoveToVoice(Channel voiceChannel, params User[] users)
 {
     foreach (User user in users.Where(user => user.Status == UserStatus.Online ||
                                               user.Status == UserStatus.Idle))
     {
         await user.Edit(voiceChannel: voiceChannel);
     }
 }
Пример #21
0
 public bool CanRun(Command command, User user, Channel channel, out string error)
 {
     error = string.Empty;
     if (user.ServerPermissions.ManageRoles)
         return true;
     error = "You do not have a permission to manage roles.";
     return false;
 }
		public Task RemoveChannelPermissions(Channel channel, Role role)
		{
			if (channel == null) throw new ArgumentNullException(nameof(channel));
			if (role == null) throw new ArgumentNullException(nameof(role));
			CheckReady();

			return RemoveChannelPermissions(channel, role?.Id, PermissionTarget.Role);
		}
		private async Task RemoveChannelPermissions(Channel channel, string userOrRoleId, PermissionTarget targetType)
		{
			try
			{
				var perms = channel.PermissionOverwrites.Where(x => x.TargetType != targetType || x.TargetId != userOrRoleId).FirstOrDefault();
				await _api.DeleteChannelPermissions(channel.Id, userOrRoleId).ConfigureAwait(false);
			}
			catch (HttpException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
		}
		public async Task<IDiscordVoiceClient> JoinVoiceServer(Channel channel)
		{
			if (channel == null) throw new ArgumentNullException(nameof(channel));
			CheckReady(); //checkVoice is done inside the voice client

			var client = await CreateVoiceClient(channel.Server).ConfigureAwait(false);
			await client.JoinChannel(channel.Id).ConfigureAwait(false);
			return client;
		}
Пример #25
0
        public MusicPlayer(Channel startingVoiceChannel, float? defaultVolume)
        {
            if (startingVoiceChannel == null)
                throw new ArgumentNullException(nameof(startingVoiceChannel));
            if (startingVoiceChannel.Type != ChannelType.Voice)
                throw new ArgumentException("Channel must be of type voice");
            Volume = defaultVolume ?? 1.0f;

            PlaybackVoiceChannel = startingVoiceChannel;
            SongCancelSource = new CancellationTokenSource();
            cancelToken = SongCancelSource.Token;

            Task.Run(async () =>
            {
                while (!Destroyed)
                {
                    try
                    {
                        if (audioClient?.State != ConnectionState.Connected)
                            audioClient = await PlaybackVoiceChannel.JoinAudio().ConfigureAwait(false);
                    }
                    catch
                    {
                        await Task.Delay(1000).ConfigureAwait(false);
                        continue;
                    }
                    CurrentSong = GetNextSong();
                    var curSong = CurrentSong;
                    if (curSong != null)
                    {
                        try
                        {
                            OnStarted(this, curSong);
                            await curSong.Play(audioClient, cancelToken).ConfigureAwait(false);
                        }
                        catch (OperationCanceledException)
                        {
                            Console.WriteLine("Song canceled");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Exception in PlaySong: {ex}");
                        }
                        OnCompleted(this, curSong);
                        curSong = CurrentSong; //to check if its null now
                        if (curSong != null)
                            if (RepeatSong)
                                playlist.Insert(0, curSong);
                            else if (RepeatPlaylist)
                                playlist.Insert(playlist.Count, curSong);
                        SongCancelSource = new CancellationTokenSource();
                        cancelToken = SongCancelSource.Token;
                    }
                    await Task.Delay(1000).ConfigureAwait(false);
                }
            });
        }
Пример #26
0
 internal static async Task<IAudioClient> JoinServer(Channel c)
 {
     try { return await Program.Audio.Join(c); }
     catch (Exception e)
     {
         Program.log.Error("Voice", "Join Server Error: " + e.Message);
         return null;
     }
 }
Пример #27
0
 internal static async Task<Discord.Audio.IDiscordVoiceClient> JoinServer(Channel c)
 {
     try { return await Program.client.JoinVoiceServer(c); }
     catch (Exception e)
     {
         Console.WriteLine("Join Voice Server Error: " + e.Message);
         return null;
     }
 }
Пример #28
0
        public void AddWarning(Channel channel, User user)
        {
            if (!_warnings.ContainsKey(user))
            {
                _warnings.Add(user, 0);
            }
            _warnings[user]++;

            NotifyUserWarned(new UserWarnedEventArgs { Channel = channel, User = user, WarningCount = _warnings[user] });
        }
Пример #29
0
        private static async Task <bool> ValidateQuery(Discord.Channel ch, string query)
        {
            if (string.IsNullOrEmpty(query.Trim()))
            {
                await ch.SendMessage("Please specify search parameters.");

                return(false);
            }
            return(true);
        }
Пример #30
0
        private static bool IsChannelOrServerFiltering(Channel channel, out Classes.ServerPermissions serverPerms)
        {
            if (!PermissionsHandler.PermissionsDict.TryGetValue(channel.Server.Id, out serverPerms)) return false;

            if (serverPerms.Permissions.FilterInvites)
                return true;

            Classes.Permissions perms;
            return serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perms) && perms.FilterInvites;
        }
Пример #31
0
        /*internal static string CleanRoleMentions(User user, Channel channel, string text, List<Role> roles = null)
		{
            var server = channel.Server;
            if (server == null) return text;

			return _roleRegex.Replace(text, new MatchEvaluator(e =>
			{
				if (roles != null && user.GetPermissions(channel).MentionEveryone)
					roles.Add(server.EveryoneRole);
				return e.Value;
			}));
		}*/
        
        private static string Resolve(Channel channel, string text)
        {
            if (text == null) throw new ArgumentNullException(nameof(text));

            var client = channel.Client;
            text = CleanUserMentions(channel, text);
            text = CleanChannelMentions(channel, text);
            //text = CleanRoleMentions(Channel, text);
            return text;
        }
Пример #32
0
 public override void Execute(Server server, Discord.Channel channel, Discord.User user, string parameter, Dictionary <string, string> flags)
 {
     foreach (KeyValuePair <string, string> flag in flags)
     {
         //Welcome Flag
         if (flag.Key == "welcome")
         {
             server.Welcome = flag.Value;
             channel.SendMessage("A new welcome message has been set for this server!");
         }
     }
 }
Пример #33
0
 private async Task <Discord.Channel> createNewChannel(string channelName, ChannelType type, MessageEventArgs e)
 {
     Discord.Channel channel = null;
     try
     {
         channel = await e.Server.CreateChannel(channelName, type);
     } catch (Exception)
     {
         await e.Channel.SendMessage(SystemMessages.MESSAGE_CHANNELNAMEEXCEPTION);
     }
     return(channel);
 }
Пример #34
0
        public override bool SendMessage(ChatItemId id, string message)
        {
            Discord.Channel c = GetChannelByDiscordChatId(id as DiscordChatId);
            if (c == null)
            {
                return(false);
            }

            c.SendMessage(message);

            return(true);
        }
Пример #35
0
        private bool EvaluatePerms(DynamicPermissionBlock dynPerms, Command command, bool canRunState, Channel channel,
            ref string error)
        {
            string category = command.Category.ToLowerInvariant();

            canRunState = EvalPermsExact(dynPerms.Allow.Modules, category, channel, canRunState, true, ref error);
            canRunState = EvalPermsExact(dynPerms.Deny.Modules, category, channel, canRunState, false, ref error);
            canRunState = EvalPermsCommands(dynPerms.Allow.Commands, command, channel, canRunState, true, ref error);
            canRunState = EvalPermsCommands(dynPerms.Deny.Commands, command, channel, canRunState, false, ref error);

            return canRunState;
        }
Пример #36
0
 public bool CanRun(Command command, User user, Channel channel, out string error)
 {
     if (user.Server != null)
     {
         error = "This command may only be run in a private chat.";
         return false;
     }
     else
     {
         error = null;
         return true;
     }
 }
Пример #37
0
        private static DiscordChat ChatFromDiscordChat(Discord.Channel e)
        {
            DiscordChat c;

            if (e.Server == null)
            {
                c = new DiscordChat(e.Id, ChatType.Channel);
            }
            else
            {
                c = new DiscordChat(e.Server, e.Id, ChatType.Channel);
            }
            c.Title = e.Topic;
            return(c);
        }
Пример #38
0
 private void registerBanCommand()
 {
     commands.CreateCommand("ban")
     .AddCheck((cm, u, ch) => u.ServerPermissions.Administrator)
     .Parameter("player", ParameterType.Required)
     .Parameter("reason", ParameterType.Required)
     .Do(async(e) =>
     {
         Discord.User target = e.Server.FindUsers(e.GetArg("player")).FirstOrDefault();
         if (getLogChannel(e.Server.Id) == "")
         {
             await e.Channel.SendMessage("You've gotta set a banlog channel with .setlogchannel first.");
             return;
         }
         Discord.Channel logChannel = e.Server.FindChannels(getLogChannel(e.Server.Id)).FirstOrDefault();
         await e.Server.Ban(target);
         await logChannel.SendMessage("Banned user **" + target.Name + "**. Reason given: " + e.GetArg("reason"));
     });
 }
Пример #39
0
        /*
         * ██╗███╗   ██╗████████╗███████╗██████╗ ███╗   ██╗ █████╗ ██╗
         * ██║████╗  ██║╚══██╔══╝██╔════╝██╔══██╗████╗  ██║██╔══██╗██║
         * ██║██╔██╗ ██║   ██║   █████╗  ██████╔╝██╔██╗ ██║███████║██║
         * ██║██║╚██╗██║   ██║   ██╔══╝  ██╔══██╗██║╚██╗██║██╔══██║██║
         * ██║██║ ╚████║   ██║   ███████╗██║  ██║██║ ╚████║██║  ██║███████╗
         * ╚═╝╚═╝  ╚═══╝   ╚═╝   ╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝╚═╝  ╚═╝╚══════╝
         */
        // The following two functions adapted from code recieved from Katazz Trofee
        // Function to handle sending audio
        public async void SendAudio(Discord.Channel chnl, Discord.Channel txtchnl, Server server)
        {
            // Join a channel
            if (chnl.Type == ChannelType.Voice)
            {
                // We use GetService to find the AudioService that we installed earlier.
                // Join the Voice Channel, and return the IAudioClient.
                try
                {
                    vClient = await client.GetService <AudioService>().Join(chnl);
                }
                catch (Exception ex)
                {
                    // Display the exception if the client fails to join the voice channel.
                    Console.WriteLine($"[{server}] Failed to join voice channel: {ex}");
                }
            }
            // Play the queue.
            while (queue.Count != 0)
            {
                // Send the first item in the queue.
                await Task.Run(() => SendAudioTask(location + "/sounds/" + queue[0] + ".mp3"));

                // Remove the item that was just played from the queue.
                queue.RemoveAt(0);
            }
            //await Task.Run(() => SendAudioTask(filePath));
            if (badfile)
            {
                // If file is bad, inform the console and user. Then set the badfile flag.
                Console.WriteLine($"[{server}] Couldn't play soundbyte; Bad file {queue[0]}");
                await txtchnl.SendMessage("Bad file - " + queue[0].Substring(queue[0].LastIndexOf('/')));

                badfile = false;
            }
            // Leave the channel
            if (vClient != null)
            {
                await vClient.Disconnect();
            }
        }
Пример #40
0
 private void registerSayCommand()
 {
     commands.CreateCommand("say")
     .AddCheck((cm, u, ch) => u.ServerPermissions.Administrator)
     .Parameter("channel", ParameterType.Required)
     .Parameter("message", ParameterType.Required)
     .Do(async(e) =>
     {
         Discord.Channel channel = e.Server.FindChannels(e.GetArg("channel")).FirstOrDefault();
         int delay  = 0;
         int length = e.GetArg("message").Length;
         do
         {
             delay  += 333;
             length -= 5;
         } while (length >= 5);
         await channel.SendIsTyping();
         await Task.Delay(delay);
         await channel.SendMessage(e.GetArg("message"));
         discord.Log.Log(LogSeverity.Info, "Message sent", "Send message \"" + e.GetArg("message") + "\" on guild " + e.Server.Name + ".");
     });
 }
Пример #41
0
        private async void PmLogs(CommandEventArgs e)
        {
            int messages = 5;

            try
            {
                messages = int.Parse(e.Args[0]);
            }
            catch (Exception)
            {
            }

            Discord.Channel chan = await _client.CreatePrivateChannel(GlobalSettings.Users.DevId);

            string[] logdata = File.ReadAllLines(Path.GetFullPath(@".\config\UmiBot.log"));

            for (int i = logdata.Count() - messages; i < logdata.Count(); i++)
            {
                await chan.SendMessage(logdata[i]);
            }
            await chan.SendMessage("Logs sent!");
        }
Пример #42
0
        private async void GetMe(CommandEventArgs e)
        {
            // Discord caches images so we need to force a new image get
            var duck = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

            try
            {
                id = Read(e.Args[0]);

                if (String.IsNullOrWhiteSpace(id))
                {
                    throw new SystemException();
                }

                if (String.Compare(e.Args[0], "Risk", true) == 0)
                {
                    Discord.Channel chan = await _client.CreatePrivateChannel(GlobalSettings.Users.DevId);

                    await chan.SendMessage($"{e.User.Name} just used SS GET in {e.Server.Name}");
                }

                result = $"https://deresute.me/{id}/medium.png?{duck}";
            }
            catch (Exception)
            {
                if (Regex.IsMatch(e.Args[0], "^[0-9]{9}$"))
                {
                    result = $"https://deresute.me/{e.Args[0]}/medium.png?{duck}";
                }
                else
                {
                    result = "not found; try again (๑◕︵◕๑)";
                }
            }

            await e.Channel.SendMessage($"{result}");
        }
Пример #43
0
 public static ChannelPermissions All(Channel channel) => All(channel.Type, channel.IsPrivate);
Пример #44
0
        public async void RemoveMessages(Discord.Server server)
        {
            if (server.Id != DiscordIds.AtlasId)
            {
                SettingsRepo      settingsRepo = new SettingsRepo(new SettingsContext());
                Discord.Channel   channel      = server.GetChannel(settingsRepo.GetLfgChannel(server.Id));
                Discord.Message[] temp         = await channel.DownloadMessages(100);

                bool found = false;
                try
                {
                    while (temp.Length > 1 && temp.Last().Text != "queue has been cleared!")
                    {
                        await channel.DeleteMessages(temp);

                        found = true;
                        temp  = await channel.DownloadMessages(100);
                    }
                }
                catch
                {
                    found = true;
                }
                if (found == true)
                {
                    await channel.SendMessage("Queue has been cleared!");
                }
            }
            else if (server.Id == DiscordIds.AtlasId)
            {
                List <Channel> channels = new List <Channel>();
                foreach (var channel in server.TextChannels)
                {
                    if (channel.Name.Contains("queue"))
                    {
                        channels.Add(channel);
                    }
                }
                foreach (var channel in channels)
                {
                    Discord.Message[] temp = await channel.DownloadMessages();

                    bool found = false;
                    try
                    {
                        while (temp.Length > 1 && temp.Last().Text != "queue has been cleared!")
                        {
                            await channel.DeleteMessages(temp);

                            found = true;
                            temp  = await channel.DownloadMessages();
                        }
                    }
                    catch
                    {
                        found = true;
                    }
                    if (found)
                    {
                        await channel.SendMessage("Queue has been cleared!");
                    }
                }
            }
        }
Пример #45
0
        private async void parseInput(string input, MessageEventArgs e)
        {
            string[] toParse  = input.Split(' ');
            string   command  = toParse[0];
            int      inputLen = toParse.Length;
            Server   server   = e.Server;

            if (e.Channel.IsPrivate)
            {
                return;
            }
            else if (command == "")
            {
                return;
            }
            else if (inputLen == 1)
            {
                if (command == Constants.COMMAND_HELP)
                {
                    await e.Channel.SendMessage("Testing Testing 1 2 3");
                }
                else if (command == Constants.COMMAND_DEVTESTNEWLINE)
                {
                    string sentence = "```";
                    for (int i = 0; i < 5; i++)
                    {
                        sentence += i + ") " + "Satsuo" + "\n";
                    }
                    sentence += "```";
                    await e.Channel.SendMessage(sentence);
                }
                else if (command == Constants.COMMAND_LISTUSERS)
                {
                    foreach (Discord.User user in e.Channel.Users)
                    {
                        //TODO: Check for users in a voice channel and only list those
                        await e.Channel.SendMessage(user.ToString());

                        await user.SendMessage("Will this work?");
                    }
                }
                else if (command == Constants.COMMAND_GITHUB)
                {
                    await e.Channel.SendMessage(Constants.URL_GITHUB);
                }
                else if (command == Constants.COMMAND_LISTSERVERSWITHGAMES)
                {
                    if (!PartyGames.Any())
                    {
                        await e.Channel.SendMessage("No server is running a game right now!");
                    }
                    else
                    {
                        for (int i = 0; i < PartyGames.Count(); i++)
                        {
                            Game game = PartyGames.ElementAt(i);
                            await e.Channel.SendMessage("Server " + game.getGameServerID().ToString() + " running game type " + game.getGameType() + " on text channel " +
                                                        game.getTextChannelID().ToString() + " and on voice channel " + game.getVoiceChannelID().ToString());
                        }
                    }
                }
                else if (command == Constants.COMMAND_JOINPARTYGAME)
                {
                    Game game = ServerStartingGame(server);
                    if (game != null)
                    {
                        if (game.playerAlreadyJoined(e.User))
                        {
                            await e.Channel.SendMessage(SystemMessages.MESSAGE_GAMEALREADYJOINED);
                        }
                        else
                        {
                            bool added = await addToRole(game.getPlayerRole(), e.User, e);

                            if (added)
                            {
                                game.addPlayer(e.User);
                                await e.Channel.SendMessage(e.User.NicknameMention + " has joined the " + game.getGameType() + " game. Click " + client.GetChannel(game.getTextChannelID()).Mention + " to enter the text channel.");
                            }
                        }
                    }
                    else
                    {
                        await e.Channel.SendMessage(SystemMessages.MESSAGE_GAMESTARTEDORNONE);
                    }
                }
                else if (command == Constants.COMMAND_LEAVEPARTYGAME)
                {
                    Game game = ServerStartingGame(server);
                    if (game != null)
                    {
                        if (game.playerAlreadyJoined(e.User))
                        {
                            game.removePlayer(e.User);
                            await e.Channel.SendMessage(e.User.NicknameMention + " has left the " + game.getGameType() + " game.");
                        }
                        else
                        {
                            await e.Channel.SendMessage("You haven't even joined the game!");
                        }
                    }
                    else
                    {
                        await e.Channel.SendMessage(SystemMessages.MESSAGE_GAMESTARTEDNOLEAVE);
                    }
                }
                else if (commandRollDice(command))
                {
                    string value = command.Remove(0, 2);
                    if (isValidDiceRoll(value))
                    {
                        int rollValue = getDiceRoll(value);
                        await e.Channel.SendMessage(e.User.Mention + " rolled a d" + value + " and got: " + rollValue);

                        return;
                    }
                    else
                    {
                        await e.Channel.SendMessage("USAGE: !d#, where # is between 1-" + Int32.MaxValue + ".");

                        return;
                    }
                }
                //The Secret Santa module
                else if (command == Constants.COMMAND_STARTSECRETSANTA)
                {
                    if (secretSanta == null)
                    {
                        secretSanta = new SecretSanta(server, client);
                        await e.Channel.SendMessage("The Secret Santa module has been initialized!");
                    }
                }
            }
            else if (inputLen > 1)
            {
                if (command == Constants.COMMAND_SETGAME)
                {
                    string game = input.Remove(0, Constants.COMMAND_SETGAME.Length + 1);
                    client.SetGame(game);
                }
                else if (command == Constants.COMMAND_CREATECHANNEL)
                {
                    string channelname = input.Remove(0, Constants.COMMAND_CREATECHANNEL.Length + 1);
                    await createNewChannel(channelname, ChannelType.Text, e);
                }
                else if (command == Constants.COMMAND_TTS)
                {
                    string message = input.Remove(0, Constants.COMMAND_TTS.Length + 1);
                    await e.Channel.SendTTSMessage(message);
                }
                else if (command == Constants.COMMAND_SETROLE)
                {
                    string            rolename    = input.Remove(0, Constants.COMMAND_SETROLE.Length + 1);
                    ServerPermissions permissions = new ServerPermissions(true);
                    try {
                        await addToRole(rolename, permissions, e.User, e);
                    }
                    catch (Exception) {
                        return;
                    }
                }
                else if (command == Constants.COMMAND_STARTDND)
                {
                    if (!isHostingGame)
                    {
                        Discord.Channel   text, voice = null;
                        Discord.Role      gamerole    = null;
                        string            channelname = input.Remove(0, Constants.COMMAND_STARTDND.Length + 1);
                        ServerPermissions permissions = new ServerPermissions();
                        gamerole = await addToRole(Constants.GAME_DNDGAME, permissions, e.User, e);

                        if (gamerole != null)
                        {
                            text = await createNewChannel(channelname, ChannelType.Text, e);

                            if (text != null)
                            {
                                isHostingGame = true;
                                voice         = await createNewChannel(channelname + " Voice", ChannelType.Voice, e);

                                ChannelPermissionOverrides memberPermOverride = new ChannelPermissionOverrides(PermValue.Deny, PermValue.Deny, PermValue.Allow,
                                                                                                               PermValue.Allow, PermValue.Allow, PermValue.Deny, PermValue.Allow, PermValue.Deny, PermValue.Allow, PermValue.Deny, PermValue.Deny,
                                                                                                               PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny);
                                ChannelPermissionOverrides everyonePermOverride = new ChannelPermissionOverrides(PermValue.Deny, PermValue.Deny, PermValue.Allow,
                                                                                                                 PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny,
                                                                                                                 PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny);
                                await text.AddPermissionsRule(gamerole, memberPermOverride);

                                await text.AddPermissionsRule(e.Server.EveryoneRole, everyonePermOverride);

                                Game DnDGame = new DnDGame(server, text, voice, e.Channel, gamerole, client, e.User.Id);
                                DnDGame.addPlayer(e.User);
                                PartyGames.Add(DnDGame);

                                await setChannelToTop(text);
                                await setChannelToTop(voice);

                                await e.Channel.SendMessage(DnDGame.getGameType() + SystemMessages.MESSAGE_GAMECREATED + text.Mention);

                                Console.WriteLine("Game was created at server: " + server.Id);
                            }
                            else
                            {
                                await gamerole.Delete();
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine(SystemMessages.MESSAGE_GAMEHASSTARTED);
                    }
                }
                else if (command == Constants.COMMAND_STARTRESISTANCE)
                {
                    bool createGame = false;
                    if (!PartyGames.Any())
                    {
                        createGame = true;
                    }
                    Game game = null;
                    if (!createGame && PartyGames.Any())
                    {
                        int i = 0; bool found = false;
                        while (i < PartyGames.Count())
                        {
                            game = PartyGames.ElementAt(i);
                            if (game.getGameServerID() == server.Id)
                            {
                                found = true;
                            }
                            i++;
                        }
                        createGame = found ? false : true;
                    }
                    if (createGame && !isHostingGame)
                    {
                        Discord.Channel   text, voice = null;
                        Discord.Role      gamerole    = null;
                        string            channelname = input.Remove(0, Constants.COMMAND_STARTRESISTANCE.Length + 1);
                        ServerPermissions permissions = new ServerPermissions();
                        gamerole = await addToRole(Constants.GAME_RESISTANCE, permissions, e.User, e);

                        if (gamerole != null)
                        {
                            text = await createNewChannel(channelname, ChannelType.Text, e);

                            if (text != null)
                            {
                                isHostingGame = true;
                                voice         = await createNewChannel(channelname + " Voice", ChannelType.Voice, e);

                                ChannelPermissionOverrides memberPermOverride = new ChannelPermissionOverrides(PermValue.Deny, PermValue.Deny, PermValue.Allow,
                                                                                                               PermValue.Allow, PermValue.Allow, PermValue.Deny, PermValue.Allow, PermValue.Deny, PermValue.Allow, PermValue.Deny, PermValue.Deny,
                                                                                                               PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny);
                                ChannelPermissionOverrides everyonePermOverride = new ChannelPermissionOverrides(PermValue.Deny, PermValue.Deny, PermValue.Allow,
                                                                                                                 PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny,
                                                                                                                 PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny);
                                await text.AddPermissionsRule(gamerole, memberPermOverride);

                                await text.AddPermissionsRule(e.Server.EveryoneRole, everyonePermOverride);

                                Game resistanceGame = new ResistanceGame(server, text, voice, e.Channel, gamerole, client, e.User.Id);
                                resistanceGame.addPlayer(e.User);
                                PartyGames.Add(resistanceGame);

                                await setChannelToTop(text);
                                await setChannelToTop(voice);

                                await e.Channel.SendMessage(resistanceGame.getGameType() + SystemMessages.MESSAGE_GAMECREATED + text.Mention);

                                Console.WriteLine("Game was created at server: " + server.Id);
                            }
                            else
                            {
                                await gamerole.Delete();
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine(SystemMessages.MESSAGE_GAMEHASSTARTED);
                    }
                }
                else if (command == Constants.COMMAND_FLOODMESSAGE)
                {
                    int repeat;
                    if (Int32.TryParse(toParse[1], out repeat))
                    {
                        string message = input.Remove(0, Constants.COMMAND_FLOODMESSAGE.Length + toParse[1].Length + 2);
                        for (int i = 0; i < repeat; i++)
                        {
                            await e.Channel.SendMessage(message);
                        }
                    }
                    else
                    {
                        await e.Channel.SendMessage("Invalid use of command, nerd");
                    }
                }
            }
            if (Constants.TESTBUILD)
            {
                await e.Channel.SendMessage("Length of input: " + inputLen);
            }
        }
Пример #46
0
 private async Task setChannelToTop(Discord.Channel channel)
 {
     await channel.Edit(null, null, 0);
 }