Пример #1
0
        public async Task LeaveChannel(SocketCommandContext Context, IVoiceChannel _channel)
        {
            try
            {
                IAudioClient aClient;
                audioDict.TryGetValue(Context.Guild.Id, out aClient);
                if (aClient == null)
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: Bot is not connected to any Voice Channels");

                    return;
                }
                var channel = (Context.Guild as SocketGuild).CurrentUser.VoiceChannel as IVoiceChannel;
                if (channel.Id == _channel.Id)
                {
                    await aClient.StopAsync();

                    aClient.Dispose();
                    audioDict.TryRemove(Context.Guild.Id, out aClient);
                }
                else
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: You must be in the same channel as the me!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Пример #2
0
 public async Task ToggleAFK(SocketCommandContext Context, string awayMsg)
 {
     try
     {
         if (!_afkDict.ContainsKey(Context.User.Id))
         {
             //add
             await AddAfk(Context, awayMsg, false);
         }
         else
         {
             if (String.IsNullOrWhiteSpace(awayMsg))
             {
                 //remove
                 _afkStruct ignore;
                 _afkDict.TryRemove(Context.User.Id, out ignore);
                 await Context.Channel.SendMessageAsync(":white_check_mark: AFK has been removed");
             }
             else
             {
                 await AddAfk(Context, awayMsg, true);
             }
         }
         SaveDatabase();
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e, Context);
     }
 }
Пример #3
0
        public async Task ClearQueue(SocketCommandContext Context)
        {
            try
            {
                List <SongStruct> queue = new List <SongStruct>();
                if (!queueDict.TryGetValue(Context.Guild.Id, out queue))
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: You first have to create a Queue by adding atleast one song!");
                }
                else
                {
                    queue.Clear();
                    queueDict.TryUpdate(Context.Guild.Id, queue);
                    await Context.Channel.SendMessageAsync(":put_litter_in_its_place:  Cleared the entire list.");

                    SaveDatabase();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Пример #4
0
 public async Task SetLeaveChannel(SocketCommandContext Context, IMessageChannel channel)
 {
     try
     {
         annoucementStruct str = new annoucementStruct();
         if (!updateChannelPreferenceDict.ContainsKey(Context.Guild.Id))
         {
             str.leaveID = channel.Id;
             updateChannelPreferenceDict.TryAdd(Context.Guild.Id, str);
         }
         else
         {
             updateChannelPreferenceDict.TryGetValue(Context.Guild.Id, out str);
             str.leaveID = channel.Id;
             updateChannelPreferenceDict.TryUpdate(Context.Guild.Id, str);
         }
         SaveDatabase();
         await Context.Channel.SendMessageAsync(
             $":white_check_mark: Successfully set Leave Channel to `{channel.Name}`!");
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e, Context);
     }
 }
Пример #5
0
 public async Task UserLeft(SocketGuildUser user)
 {
     try
     {
         annoucementStruct str = new annoucementStruct();
         if (updateChannelPreferenceDict.TryGetValue(user.Guild.Id, out str))
         {
             IMessageChannel channel = user.Guild.GetChannel(str.leaveID) as IMessageChannel;
             if (channel == null)
             {
                 return;
             }
             if (String.IsNullOrWhiteSpace(str.leaveMsg))
             {
                 await channel.SendMessageAsync($"`{user.Username}` has left us :frowning:");
             }
             else
             {
                 await channel.SendMessageAsync(ReplaceInfo(user, str.leaveMsg));
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e);
     }
 }
Пример #6
0
 private void LoadDatabase()
 {
     try
     {
         if (File.Exists("AnnouncementChannels.json"))
         {
             using (StreamReader sr = File.OpenText(@"AnnouncementChannels.json"))
             {
                 using (JsonReader reader = new JsonTextReader(sr))
                 {
                     var temp = jSerializer.Deserialize <ConcurrentDictionary <ulong, annoucementStruct> >(reader);
                     if (temp == null)
                     {
                         return;
                     }
                     updateChannelPreferenceDict = temp;
                 }
             }
         }
         else
         {
             File.Create("AnnouncementChannels.json").Dispose();
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         SentryService.SendError(e);
     }
 }
Пример #7
0
        public async Task RemoveLeave(SocketCommandContext Context)
        {
            try
            {
                if (!updateChannelPreferenceDict.ContainsKey(Context.Guild.Id))
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: No Announcement Channel set in this Guild!");
                }
                else
                {
                    annoucementStruct str = new annoucementStruct();
                    updateChannelPreferenceDict.TryGetValue(Context.Guild.Id, out str);
                    str.leaveID  = 0;
                    str.leaveMsg = null;
                    updateChannelPreferenceDict.TryUpdate(Context.Guild.Id, str);
                    await Context.Channel.SendMessageAsync(":white_check_mark: Leave Channel for this Guild was removed. No Announcements will be done anymore!");

                    SaveDatabase();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Пример #8
0
        public async Task RequestAuth()
        {
            try
            {
                var headers = new Dictionary <string, string>
                {
                    { "grant_type", "client_credentials" },
                    { "client_id", clientId },
                    { "client_secret", clientSecret },
                };

                using (var http = new HttpClient())
                {
                    //http.AddFakeHeaders();
                    http.DefaultRequestHeaders.Clear();
                    var formContent = new FormUrlEncodedContent(headers);
                    var response    = await http.PostAsync("https://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false);

                    var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    anilistToken = JObject.Parse(stringContent)["access_token"].ToString();
                }
                timeToUpdate = Environment.TickCount + 1700000;
                Console.WriteLine("ANILIST AUTHENTICATION SUCCESSFULL");
                await SentryService.SendMessage("ANILIST AUTHENTICATION **SUCCESSFULL**");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendMessage("ANILIST AUTHENTICATION **FAILED**");

                await SentryService.SendError(e);
            }
        }
Пример #9
0
 public async Task UserJoined(SocketGuildUser user)
 {
     try
     {
         annoucementStruct str = new annoucementStruct();
         if (updateChannelPreferenceDict.TryGetValue(user.Guild.Id, out str))
         {
             IMessageChannel channel = user.Guild.GetChannel(str.channelID) as IMessageChannel;
             if (channel == null)
             {
                 return;
             }
             if (String.IsNullOrWhiteSpace(str.message))
             {
                 await channel.SendMessageAsync($"Welcome {user.Mention} to **{user.Guild.Name}**!");
             }
             else
             {
                 await channel.SendMessageAsync(ReplaceInfo(user, str.message));
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e);
     }
 }
Пример #10
0
        //WELCOME

        public async Task SetWelcome(SocketCommandContext Context, string message)
        {
            try
            {
                annoucementStruct str = new annoucementStruct();
                if (!updateChannelPreferenceDict.ContainsKey(Context.Guild.Id))
                {
                    str.channelID = Context.Channel.Id;
                    str.message   = message;
                    updateChannelPreferenceDict.TryAdd(Context.Guild.Id, str);
                }
                else
                {
                    updateChannelPreferenceDict.TryGetValue(Context.Guild.Id, out str);
                    str.channelID = Context.Channel.Id;
                    str.message   = message;
                    updateChannelPreferenceDict.TryUpdate(Context.Guild.Id, str);
                }
                SaveDatabase();
                await Context.Channel.SendMessageAsync(
                    $":white_check_mark: Successfully set Welcome Channel to `{Context.Channel.Name}` with {(String.IsNullOrWhiteSpace(str.message) ? "the default leave message" : $"message:\n{str.message}")}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Пример #11
0
 public async Task SetLeaveMessage(SocketCommandContext Context, string message)
 {
     try
     {
         annoucementStruct str = new annoucementStruct();
         if (!updateChannelPreferenceDict.ContainsKey(Context.Guild.Id))
         {
             str.leaveMsg = message;
             updateChannelPreferenceDict.TryAdd(Context.Guild.Id, str);
         }
         else
         {
             updateChannelPreferenceDict.TryGetValue(Context.Guild.Id, out str);
             str.leaveMsg = message;
             updateChannelPreferenceDict.TryUpdate(Context.Guild.Id, str);
         }
         SaveDatabase();
         await Context.Channel.SendMessageAsync(
             $":white_check_mark: Successfully set Leave Message to `{message}` and {(str.leaveID != 0 ? ($"with Channel {((Context.Guild as SocketGuild).GetChannel(str.leaveID)).Name}") : "with no channel yet!")}");
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e, Context);
     }
 }
Пример #12
0
 public async Task checkRatelimit(IUser user)
 {
     try
     {
         if (userLimiterDict.ContainsKey(user.Id))
         {
             userRate userStruct = new userRate();
             userLimiterDict.TryGetValue(user.Id, out userStruct);
             //CHECK TIME
             if (Environment.TickCount < userStruct.timeBetween)
             {
                 userStruct.counter += 1;
                 if (userStruct.counter >= 5)
                 {
                     //ratelimit
                     if (!userStruct.messageSent)
                     {
                         userStruct.timeBetween = Environment.TickCount + timeToAdd;
                         await(await user.GetOrCreateDMChannelAsync()).SendMessageAsync(
                             "**You have been ratelimited for 20 seconds. Please do not spam commands or stars! If you continue doing so your lockout will increase in time!**\n" +
                             "If this was by mistake and you did not spam. join https://discord.gg/Pah4yj5 and @ me");
                         userStruct.timeBetween += punishTime;
                         userStruct.messageSent  = true;
                     }
                     userStruct.timeBetween += timeToAdd;
                     userLimiterDict.TryUpdate(user.Id, userStruct);
                 }
                 else
                 {
                     //add time
                     userStruct.timeBetween = Environment.TickCount + timeToAdd;
                     userLimiterDict.TryUpdate(user.Id, userStruct);
                 }
             }
             else
             {
                 //reset Ratelimit
                 userStruct.counter     = 1;
                 userStruct.timeBetween = Environment.TickCount + timeToAdd;
                 userStruct.messageSent = false;
                 userLimiterDict.TryUpdate(user.Id, userStruct);
             }
         }
         else
         {
             userRate userStruct = new userRate
             {
                 counter     = 1,
                 timeBetween = Environment.TickCount + timeToAdd,
                 messageSent = false
             };
             userLimiterDict.TryAdd(user.Id, userStruct);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e);
     }
 }
Пример #13
0
        private async Task PlayQueueAsync(IAudioClient client, SocketCommandContext Context)
        {
            try
            {
                if (queueDict.ContainsKey(Context.Guild.Id))
                {
                    List <SongStruct> queue = new List <SongStruct>();
                    queueDict.TryGetValue(Context.Guild.Id, out queue);
                    for (int i = 1; i <= queue.Count;)
                    {
                        string            name   = queue[0].name;
                        var               ffmpeg = CreateStream(name);
                        audioStream_Token strToken;
                        if (audioStreamDict.ContainsKey(client))
                        {
                            audioStreamDict.TryGetValue(client, out strToken);
                            strToken.tokenSource.Cancel();
                            strToken.tokenSource.Dispose();
                            strToken.tokenSource = new CancellationTokenSource();
                            strToken.token       = strToken.tokenSource.Token;
                            audioStreamDict.TryUpdate(client, strToken);
                        }
                        else
                        {
                            strToken.audioStream = client.CreatePCMStream(AudioApplication.Music, null, 1920);
                            strToken.tokenSource = new CancellationTokenSource();
                            strToken.token       = strToken.tokenSource.Token;
                            audioStreamDict.TryAdd(client, strToken);
                        }

                        var output = ffmpeg.StandardOutput.BaseStream; //1920, 2880, 960
                        await output.CopyToAsync(strToken.audioStream, 1920, strToken.token).ContinueWith(task =>
                        {
                            if (!task.IsCanceled && task.IsFaulted) //supress cancel exception
                            {
                                Console.WriteLine(task.Exception);
                            }
                        });

                        ffmpeg.WaitForExit();
                        await strToken.audioStream.FlushAsync();

                        queueDict.TryGetValue(Context.Guild.Id, out queue);
                        queue.RemoveAt(0);
                        queueDict.TryUpdate(Context.Guild.Id, queue);
                    }
                }
                else
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: Please add a song to the Queue first!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Пример #14
0
        public async Task GetRolesInGuild(SocketCommandContext Context)
        {
            try
            {
                if (!_availableRoles.ContainsKey(Context.Guild.Id))
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: There are no self-assignable roles in this guild!");

                    return;
                }
                List <ulong> roleIDs = new List <ulong>();
                _availableRoles.TryGetValue(Context.Guild.Id, out roleIDs);
                List <ulong> rolesToDelete = new List <ulong>();
                var          eb            = new EmbedBuilder()
                {
                    Color  = new Color(4, 97, 247),
                    Title  = $"Roles in {Context.Guild.Name}",
                    Footer = new EmbedFooterBuilder()
                    {
                        Text    = $"Requested by {Context.User.Username}#{Context.User.Discriminator}",
                        IconUrl = (Context.User.GetAvatarUrl())
                    },
                    Description = ""
                };
                foreach (var rId in roleIDs)
                {
                    var role = Context.Guild.GetRole(rId);
                    if (role == null)
                    {
                        rolesToDelete.Add(rId);
                        continue;
                    }
                    eb.Description += $"{role.Name}\n";
                }

                if (rolesToDelete.Count > 0)
                {
                    foreach (var role in rolesToDelete)
                    {
                        roleIDs.Remove(role);
                    }
                    _availableRoles.TryUpdate(Context.Guild.Id, roleIDs);
                    SaveDatabase();
                }

                await Context.Channel.SendMessageAsync("", false, eb);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await Context.Channel.SendMessageAsync(
                    $":no_entry_sign: Failed to add role. I'm probably missing the perms!");

                await SentryService.SendError(e, Context);
            }
        }
Пример #15
0
        public async Task <bool> onlyCheck(IUser user, IGuild guild, SocketCommandContext context = null, string otherContext = "No string")
        {
            try
            {
                if (userLimiterDict.ContainsKey(user.Id))
                {
                    userRate userStruct = new userRate();
                    userLimiterDict.TryGetValue(user.Id, out userStruct);
                    //CHECK TIME
                    if (Environment.TickCount < userStruct.timeBetween)
                    {
                        if (userStruct.counter >= 4)
                        {
                            //ratelimit
                            if (!userStruct.messageSent)
                            {
                                userStruct.timeBetween = Environment.TickCount + timeToAdd;
                                await(await user.GetOrCreateDMChannelAsync()).SendMessageAsync(
                                    "**You have been ratelimited for 20 seconds. Please do not spam commands! If you continue doing so your lockout will increase in time!**\n" +
                                    "If this was by mistake and you did not spam. join https://discord.gg/Pah4yj5 and @ me");
                                userStruct.timeBetween += punishTime;
                                userStruct.messageSent  = true;
                                await SentryService.SendMessage($"Rate limit occured:\n" +
                                                                $"User: {user.Username}#{user.Discriminator} \t{user.Id}\n" +
                                                                $"Guild: {guild.Name} \t {guild.Id}\n" +
                                                                $"Message: {(context == null ? otherContext : context.Message.Content)}");
                            }
                            userStruct.timeBetween += timeToAdd;
                            userLimiterDict.TryUpdate(user.Id, userStruct);
                            return(true);
                        }
                    }
                }

                return(false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                if (context != null)
                {
                    await SentryService.SendError(e, context);
                }
                else
                {
                    await SentryService.SendError(e);
                }
            }
            return(false);
        }
Пример #16
0
        public async Task CheckIfAlone(SocketUser user, SocketVoiceState stateOld, SocketVoiceState stateNew)
        {
            try
            {
                if (user.IsBot)
                {
                    return;
                }
                if (stateOld.VoiceChannel == null)
                {
                    return;
                }
                if (!stateOld.VoiceChannel.Users.Contains(((SocketGuildUser)user).Guild.CurrentUser)) //Compare the ids instead, also CurrentUser has an VoiceChannel property I think stateOld.VoiceChannel.Id == guild.CurrentUeser.VoiceChannel.Id could work
                {
                    return;
                }
                if (stateOld.VoiceChannel == (stateNew.VoiceChannel ?? null))
                {
                    return;
                }
                int users = 0;
                foreach (var u in stateOld.VoiceChannel.Users)
                {
                    if (!u.IsBot)
                    {
                        users++;
                    }
                }
                if (users < 1)
                {
                    IAudioClient aClient;
                    var          userG = (SocketGuildUser)user;
                    audioDict.TryGetValue(userG.Guild.Id, out aClient);
                    if (aClient == null)
                    {
                        return;
                    }
                    await aClient.StopAsync();

                    aClient.Dispose();
                    audioDict.TryRemove(userG.Guild.Id, out aClient);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e);
            }
        }
Пример #17
0
 private void SaveDatabase()
 {
     try
     {
         using (StreamWriter sw = File.CreateText(@"AnnouncementChannels.json"))
         {
             using (JsonWriter writer = new JsonTextWriter(sw))
             {
                 jSerializer.Serialize(writer, updateChannelPreferenceDict);
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         SentryService.SendError(e);
     }
 }
Пример #18
0
 private async Task ChangePlayingStatus()
 {
     try
     {
         Random rand = new Random();
         while (true)
         {
             if (client.ConnectionState.ToString() == "Connected")
             {
                 await client.SetGameAsync(playing[rand.Next(playing.Length - 1)]);
             }
             await Task.Delay(10000);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         await SentryService.SendError(e);
     }
 }
Пример #19
0
        public async Task PlayQueue(SocketCommandContext Context)
        {
            try
            {
                IAudioClient client;
                if (!audioDict.TryGetValue(Context.Guild.Id, out client))
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: Bot must first join a Voice Channel!");

                    return;
                }
                await Context.Channel.SendMessageAsync(":musical_note: Started playing");

                //await PlayQueueAsync(client, Context);
                await PlayQueueAsync(client, Context);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Пример #20
0
        /*
         * public async Task PlayMusic(string url, SocketCommandContext Context)
         * {
         *  IAudioClient aClient;
         *  audioDict.TryGetValue(Context.Guild.Id, out aClient);
         *  string msg = ":arrows_counterclockwise: Downloading...";
         *  if (url.Equals("rand") || url.Equals("random"))
         *  {
         *      InitializeLoader();
         *      LoadDatabse();
         *  }
         *  var msgToEdit = await Context.Channel.SendMessageAsync(msg);
         *  //Task music = new Task(() => SendAsync(aClient, url, msgToEdit));
         *  //music.Start();
         *  await SendAsync(aClient, url, msgToEdit, Context);
         * }*/

        public async Task StopMusic(SocketCommandContext Context)
        {
            try
            {
                if (audioDict.ContainsKey(Context.Guild.Id))
                {
                    IAudioClient client;
                    audioDict.TryGetValue(Context.Guild.Id, out client);

                    if (audioStreamDict.ContainsKey(client))
                    {
                        audioStream_Token strAT;
                        audioStreamDict.TryGetValue(client, out strAT);

                        strAT.tokenSource.Cancel();
                        strAT.tokenSource.Dispose();
                        strAT.tokenSource = new CancellationTokenSource();
                        strAT.token       = strAT.tokenSource.Token;
                        audioStreamDict.TryUpdate(client, strAT);
                        await Context.Channel.SendMessageAsync(":stop_button: Stopped the Music Playback!");
                    }
                    else
                    {
                        await Context.Channel.SendMessageAsync(":no_entry_sign: Currently not playing anything!");
                    }
                }
                else
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: I didn't even join a Channel yet!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Пример #21
0
        public async Task NowPlaying(SocketCommandContext Context)
        {
            try
            {
                List <SongStruct> queue = new List <SongStruct>();
                if (queueDict.TryGetValue(Context.Guild.Id, out queue))
                {
                    if (queue.Count != 0)
                    {
                        var infoJson = File.ReadAllText($"{queue[0].name}.info.json");
                        var info     = JObject.Parse(infoJson);

                        var title = info["fulltitle"];

                        var eb = new EmbedBuilder()
                        {
                            Color  = new Color(4, 97, 247),
                            Footer = new EmbedFooterBuilder()
                            {
                                Text    = $"Requested by {Context.User.Username}#{Context.User.Discriminator}",
                                IconUrl = (Context.User.GetAvatarUrl())
                            }
                        };

                        eb.AddField((efb) =>
                        {
                            int duration = 0;
                            var con      = Int32.TryParse(info["duration"].ToString(), out duration);
                            string dur   = "00:00";
                            if (con)
                            {
                                dur = Convert(duration);
                            }
                            efb.Name     = "Now playing";
                            efb.IsInline = false;
                            efb.Value    = $"[{dur}] - [{title}]({StringEncoder.Base64Decode(queue[0].name)})";
                        });

                        eb.AddField((x) =>
                        {
                            x.Name     = "Requested by";
                            x.IsInline = false;
                            x.Value    = queue[0].user;
                        });

                        await Context.Channel.SendMessageAsync("", false, eb);
                    }
                    else
                    {
                        await Context.Channel.SendMessageAsync(":no_entry_sign: Queue is empty!");
                    }
                }
                else
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: You first have to create a Queue by adding atleast one song!");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Пример #22
0
        public async Task AddRoleToList(SocketCommandContext Context, string roleName)
        {
            //Sora = 270931284489011202
            //Sora test = 276304865934704642
            try
            {
                var sora = Context.Guild.GetUser(270931284489011202);
                var role = Context.Guild.Roles.Where(x => x.Name == roleName).FirstOrDefault();
                //var soraRole = Context.Guild.Roles.Where(x => x.Name == "Sora").FirstOrDefault();
                var soraRole = sora.Roles.OrderByDescending(r => r.Position).FirstOrDefault();
                if (role == null)
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: Couldn't find specified role!");

                    return;
                }
                if (soraRole == null)
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: Couldn't find my own role! I apparently do not own any roles... Pls report this if it ever happens");

                    await SentryService.SendMessage(
                        $"Couldn't find Soras role? ;_; in {Context.Guild.Name} ({Context.Guild.Id})");

                    return;
                }
                if (soraRole.Position < role.Position)
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: Can't assign Roles that are above me in the role hirachy! **If this is NOT true, open the role hirachy and move any role up once and then back to its initial position! This will update all role positions!**");

                    return;
                }
                if (!sora.GuildPermissions.Has(GuildPermission.ManageRoles))
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: Sora needs Manage Roles permissions to add roles!");

                    return;
                }
                Console.WriteLine($"{soraRole.Position} : {role.Position}");

                if (_availableRoles.ContainsKey(Context.Guild.Id))
                {
                    List <ulong> roleIDs = new List <ulong>();
                    _availableRoles.TryGetValue(Context.Guild.Id, out roleIDs);
                    if (roleIDs.Contains(role.Id))
                    {
                        await Context.Channel.SendMessageAsync(":no_entry_sign: This role already is self-assignable");

                        return;
                    }
                    roleIDs.Add(role.Id);
                    _availableRoles.TryUpdate(Context.Guild.Id, roleIDs);
                }
                else
                {
                    List <ulong> roleIDs = new List <ulong>();
                    roleIDs.Add(role.Id);
                    _availableRoles.TryAdd(Context.Guild.Id, roleIDs);
                }
                SaveDatabase();

                await Context.Channel.SendMessageAsync($":white_check_mark: Successfully added Role `{role.Name}`");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await Context.Channel.SendMessageAsync(
                    $":no_entry_sign: Failed to add role. I'm probably missing the perms!");

                await SentryService.SendError(e, Context);
            }
        }
Пример #23
0
        public async Task IAmRole(SocketCommandContext Context, string roleName)
        {
            try
            {
                var sora = Context.Guild.GetUser(270931284489011202);
                if (!sora.GuildPermissions.Has(GuildPermission.ManageRoles))
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: Sora needs Manage Roles permissions to add roles!");

                    return;
                }
                if (!_availableRoles.ContainsKey(Context.Guild.Id))
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: There are no self-assignable roles in this guild!");

                    return;
                }

                List <ulong> roleIDs = new List <ulong>();
                _availableRoles.TryGetValue(Context.Guild.Id, out roleIDs);
                IRole        roleToAdd     = null;
                List <ulong> rolesToDelete = new List <ulong>();
                foreach (var rId in roleIDs)
                {
                    var role = Context.Guild.GetRole(rId);
                    if (role == null)
                    {
                        rolesToDelete.Add(rId);
                        continue;
                    }
                    if (role.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        roleToAdd = role;
                        break;
                    }
                }

                if (rolesToDelete.Count > 0)
                {
                    foreach (var role in rolesToDelete)
                    {
                        roleIDs.Remove(role);
                    }
                    _availableRoles.TryUpdate(Context.Guild.Id, roleIDs);
                    SaveDatabase();
                }

                if (roleToAdd == null)
                {
                    await Context.Channel.SendMessageAsync(
                        $"The role `{roleName}` could not be found! Use `<prefix>getRoles` to get a list of all self-assignable roles!");

                    return;
                }

                var soraRole = sora.Roles.OrderByDescending(r => r.Position).FirstOrDefault();
                if (soraRole.Position < roleToAdd.Position)
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: Can't assign Roles that are above me (highest role that i have) in the role hirachy! **If this is NOT true, open the role hirachy and move any role up once and then back to its initial position! This will update all role positions!**");

                    return;
                }

                var user = (Context.User as SocketGuildUser);

                foreach (var role in user.Roles)
                {
                    if (role.Name.ToLower() == roleName.ToLower())
                    {
                        await Context.Channel.SendMessageAsync(
                            ":no_entry_sign: You already have that role! Use `<prefix>iamnot <rolename>` to get remove a self-assignable role from yourself.");

                        return;
                    }
                }

                await user.AddRoleAsync(roleToAdd, null);

                await Context.Channel.SendMessageAsync(
                    $":white_check_mark: Successfully added `{roleToAdd.Name}` to your roles!");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await Context.Channel.SendMessageAsync(
                    $":no_entry_sign: Failed to add role. I'm probably missing the perms!");

                await SentryService.SendError(e, Context);
            }
        }
Пример #24
0
        public async Task AddQueue(string url, SocketCommandContext Context)
        {
            try
            {
                IAudioClient aClient;
                audioDict.TryGetValue(Context.Guild.Id, out aClient);
                if (aClient == null)
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: Bot is not connected to any Voice Channels");

                    return;
                }
                var _channel = (Context.Message.Author as IGuildUser)?.VoiceChannel;
                if (_channel == null)
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: You must be in the same Voice Channel as me!");

                    return;
                }
                var channel = (Context.Guild as SocketGuild).CurrentUser.VoiceChannel as IVoiceChannel;
                if (channel.Id != _channel.Id)
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: You must be in the same Voice Channel as the me!");

                    return;
                }

                var msg =
                    await Context.Channel.SendMessageAsync(
                        ":arrows_counterclockwise: Downloading and Adding to Queue...");

                string nameT = await Download(url, msg, Context);

                if (!nameT.Equals("f"))
                {
                    List <SongStruct> tempList   = new List <SongStruct>();
                    SongStruct        tempStruct = new SongStruct
                    {
                        name = nameT,
                        user = $"{Context.User.Username}#{Context.User.Discriminator}"
                    };
                    if (queueDict.ContainsKey(Context.Guild.Id))
                    {
                        queueDict.TryGetValue(Context.Guild.Id, out tempList);
                        tempList.Add(tempStruct);
                        queueDict.TryUpdate(Context.Guild.Id, tempList);
                    }
                    else
                    {
                        tempList.Add(tempStruct);
                        queueDict.TryAdd(Context.Guild.Id, tempList);
                    }
                    SaveDatabase();
                    //await Context.Channel.SendMessageAsync(":musical_note: Successfully Downloaded. Will play shortly");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Пример #25
0
        public async Task SkipQueueEntry(SocketCommandContext Context)
        {
            try
            {
                IAudioClient client;
                if (!audioDict.TryGetValue(Context.Guild.Id, out client))
                {
                    List <SongStruct> queue = new List <SongStruct>();
                    if (!queueDict.TryGetValue(Context.Guild.Id, out queue))
                    {
                        await Context.Channel.SendMessageAsync(
                            ":no_entry_sign: You first have to create a Queue by adding atleast one song!");
                    }
                    else
                    {
                        if (queue.Count < 1)
                        {
                            await Context.Channel.SendMessageAsync(
                                ":no_entry_sign: The queue is empty! Nothing to skip here..");

                            return;
                        }
                        queue.RemoveAt(0);
                        queueDict.TryUpdate(Context.Guild.Id, queue);
                        SaveDatabase();
                        await Context.Channel.SendMessageAsync(":track_next: Skipped first entry in Queue");
                    }
                }
                else
                {
                    List <SongStruct> queue = new List <SongStruct>();
                    if (!queueDict.TryGetValue(Context.Guild.Id, out queue))
                    {
                        await Context.Channel.SendMessageAsync(
                            ":no_entry_sign: You first have to create a Queue by adding atleast one song!");
                    }
                    else
                    {
                        if (queue.Count < 1)
                        {
                            await Context.Channel.SendMessageAsync(
                                ":no_entry_sign: The queue is empty! Nothing to skip here..");

                            return;
                        }
                        queue.RemoveAt(0);
                        queueDict.TryUpdate(Context.Guild.Id, queue);
                        SaveDatabase();
                        if (queue.Count == 0)
                        {
                            await Context.Channel.SendMessageAsync(":track_next: Queue is now empty!");
                            await StopMusic(Context);
                        }
                        else
                        {
                            await Context.Channel.SendMessageAsync(
                                ":track_next: Skipped first entry in Queue and started playing next song!");
                            await PlayQueueAsync(client, Context);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }
Пример #26
0
        public async Task QueueList(SocketCommandContext Context)
        {
            List <SongStruct> queue = new List <SongStruct>();

            if (queueDict.TryGetValue(Context.Guild.Id, out queue))
            {
                if (queue.Count != 0)
                {
                    try
                    {
                        var eb = new EmbedBuilder()
                        {
                            Color  = new Color(4, 97, 247),
                            Footer = new EmbedFooterBuilder()
                            {
                                Text    = $"Requested by {Context.User.Username}#{Context.User.Discriminator}",
                                IconUrl = (Context.User.GetAvatarUrl())
                            }
                        };

                        eb.Title = "Queue List";
                        var infoJsonT = File.ReadAllText($"{queue[0].name}.info.json");
                        var infoT     = JObject.Parse(infoJsonT);

                        var titleT = infoT["fulltitle"].ToString();
                        if (String.IsNullOrWhiteSpace(titleT))
                        {
                            titleT = "Couldn't find name";
                        }

                        eb.AddField((efb) =>
                        {
                            int duration = 0;
                            var con      = Int32.TryParse(infoT["duration"].ToString(), out duration);
                            string dur   = "00:00";
                            if (con)
                            {
                                dur = Convert(duration);
                            }
                            efb.Name     = "Now playing";
                            efb.IsInline = true;
                            efb.Value    = $"[{dur}] - **[{titleT}]({StringEncoder.Base64Decode(queue[0].name)})** \n      \t*by {queue[0].user}*";
                        });



                        int lenght = 0;
                        if (queue.Count > 11)
                        {
                            lenght = 11;
                        }
                        else
                        {
                            lenght = queue.Count;
                        }
                        for (int i = 1; i < lenght; i++)
                        {
                            eb.AddField((efb) =>
                            {
                                efb.Name     = $"#{i} by {queue[i].user}";
                                efb.IsInline = false;
                                var infoJson = File.ReadAllText($"{queue[i].name}.info.json");
                                var info     = JObject.Parse(infoJson);

                                int duration = 0;
                                var con      = Int32.TryParse(info["duration"].ToString(), out duration);
                                string dur   = "00:00";
                                if (con)
                                {
                                    dur = Convert(duration);
                                }

                                var title = info["fulltitle"].ToString();
                                if (String.IsNullOrWhiteSpace(title))
                                {
                                    title = "Couldn't find name";
                                }
                                efb.Value += $"[{dur}] - **[{title}]({StringEncoder.Base64Decode(queue[i].name)})**";    //\n      \t*by {queue[i].user}*\n";
                            });
                        }
                        if (queue.Count == 1)
                        {
                            eb.AddField((efb) =>
                            {
                                efb.Name     = "Queue";
                                efb.IsInline = false;
                                efb.Value    = "No Songs in Queue";
                            });
                        }


                        await Context.Channel.SendMessageAsync("", false, eb);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        await SentryService.SendError(e, Context);
                    }
                }
                else
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: Queue is empty!");
                }
            }
            else
            {
                await Context.Channel.SendMessageAsync(
                    ":no_entry_sign: You first have to create a Queue by adding atleast one song!");
            }
        }
Пример #27
0
        public async Task GetImdb(SocketCommandContext Context, string target, InteractiveService interactive)
        {
            try
            {
                await Context.Channel.TriggerTypingAsync();

                var movieSimple = await TheMovieDbProvider.FindMovie(target);

                if (movieSimple == null || movieSimple.Length < 1)
                {
                    await Context.Channel.SendMessageAsync(":no_entry_sign: Couldn't find movie/series");

                    return;
                }

                int index;

                if (movieSimple.Length > 1)
                {
                    string choose = "";
                    var    ebC    = new EmbedBuilder()
                    {
                        Color = new Color(4, 97, 247),
                        Title = "Enter the Index of the Movie you want more info about."
                    };
                    int count = 1;
                    foreach (var movie in movieSimple)
                    {
                        choose += $"**{count}.** {movie.title} ({(movie.release_date.Length > 4 ?  movie.release_date.Remove(4) : (string.IsNullOrWhiteSpace(movie.release_date)? "NoDate": movie.release_date))})\n";
                        count++;
                    }
                    ebC.Description = choose;
                    var msg = await Context.Channel.SendMessageAsync("", embed : ebC);

                    var response =
                        await interactive.WaitForMessage(Context.User, Context.Channel, TimeSpan.FromSeconds(20));

                    if (response == null)
                    {
                        await Context.Channel.SendMessageAsync($":no_entry_sign: Answer timed out {Context.User.Mention} (≧д≦ヾ)");

                        return;
                    }
                    if (!Int32.TryParse(response.Content, out index))
                    {
                        await Context.Channel.SendMessageAsync(":no_entry_sign: Only add the Index");

                        return;
                    }
                    if (index > (movieSimple.Length) || index < 1)
                    {
                        await Context.Channel.SendMessageAsync(":no_entry_sign: Invalid Number");

                        return;
                    }
                }
                else
                {
                    index = 1;
                }
                //var smallObj = JToken.Parse(movieSimple[index - 1]);

                var finalMovie = TheMovieDbProvider.FindFinalMovie(movieSimple[index - 1].id.ToString()).Result;



                var eb = finalMovie.GetEmbed();
                eb.WithFooter(x => {
                    x.Text    = $"Requested by {Context.User.Username}#{Context.User.Discriminator}";
                    x.IconUrl = (Context.User.GetAvatarUrl());
                });
                eb.Build();
                await Context.Channel.SendMessageAsync("", false, eb);
            }
            catch (Exception e)
            {
                await Context.Channel.SendMessageAsync(":no_entry_sign: Couldn't find IMDb entry. Try later or try another one.");

                await SentryService.SendError(e, Context);
            }
        }
Пример #28
0
        private async Task <string> Download(string path, IUserMessage msg, SocketCommandContext Context)
        {
            bool stream = false;

            /*
             * string[] id = new string[2];
             * string[] idL = path.Split('=');
             * if (idL[1] != null)
             * {
             *  if (idL[1].Contains("&"))
             *  {
             *      string[] temp = idL[1].Split('&');
             *      idL[1] = temp[0];
             *  }
             *  id[1] = idL[1];
             * }
             * else
             * {
             *  await msg.ModifyAsync(
             *      x => { x.Content = ":musical_note: Not a Valid link!"; });
             *  return "f";
             * }
             */

            // Create FFmpeg using the previous example
            //string betterPath = "https://www.youtube.com/watch?v="+id[1];

            if (path.Contains("https://www.youtube.com/watch?v=") && path.Contains('&'))
            {
                var split = path.Split('&');
                path = split[0];
            }
            string name = StringEncoder.Base64Encode(path);


            Process ytdl = new Process();

            if (!File.Exists(name + ".mp3"))
            {
                try
                {
                    var ytdlChecker = CheckerYtDl(path);
                    ytdlChecker.ErrorDataReceived += (x, y) =>
                    {
                        stream = false;
                        Console.WriteLine("YTDL CHECKER FAILED");
                    };
                    string output = ytdlChecker.StandardOutput.ReadToEnd();
                    ytdlChecker.WaitForExit();
                    if (ytdlChecker.ExitCode != 0)
                    {
                        await msg.ModifyAsync(x =>
                        {
                            x.Content =
                                ":no_entry_sign: YT-DL Error. Possible reasons: Video is blocked in Bot's country, NO LIVESTREAMS or a plain YT-DL bug. Retry once";
                        });

                        return("f");
                    }

                    //var data = JObject.Parse(output);
                    IDictionary <string, JToken> json = JObject.Parse(output);

                    if (json.ContainsKey("is_live") && !String.IsNullOrEmpty(json["is_live"].Value <string>()))
                    //if (data["is_live"].Value<string>() != null)
                    //if (String.IsNullOrEmpty(data["is_live"].Value<string>()))
                    {
                        stream = false;
                        ytdl   = YtDl("", name);
                        Console.WriteLine("YTDL CHECKER LIVE DETECTED");
                    }
                    else
                    {
                        ytdl = YtDl(path, name);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    await SentryService.SendError(e, Context);
                }
            }

            if (name != null)
            {
                Stopwatch stopwatch = Stopwatch.StartNew();
                stopwatch.Start();
                while (!File.Exists(name + ".mp3"))
                {
                    if (ytdl != null)
                    {
                        if (ytdl.HasExited)
                        {
                            break;
                        }
                    }
                    if (stopwatch.ElapsedMilliseconds > 60000)
                    {
                        stopwatch.Stop();
                        try
                        {
                            ytdl.Kill();
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            await SentryService.SendError(e, Context);
                        }
                        var dir = new DirectoryInfo(".");

                        foreach (var file in dir.EnumerateFiles("*.part"))
                        {
                            file.Delete();
                        }
                        File.Delete($"{name}.info.json");
                        await msg.ModifyAsync(x =>
                        {
                            x.Content =
                                ":no_entry_sign: The Server that hosts the Video you tried to download is way to slow. Try another, faster service!";
                        });

                        return("f");
                    }
                }
                if (File.Exists(name + ".mp3"))
                {
                    try
                    {
                        await msg.ModifyAsync(
                            x => { x.Content = ":musical_note: Successfully Downloaded."; });

                        stream = true;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        await SentryService.SendError(e, Context);
                    }
                }
                else
                {
                    await msg.ModifyAsync(x =>
                    {
                        x.Content =
                            ":no_entry_sign: Failed to Download. Possible reasons: Video is blocked in Bot's country, Video was too long, NO PLAYLISTS AND NO LIVE STREAMS!";
                    });
                }

                /*
                 * if (stream)
                 * {
                 *  //Opus Encoding
                 *
                 *  var OpusEncoder = OpusEncoding(name);
                 *  OpusEncoder.WaitForExit();
                 *  if (OpusEncoder.ExitCode != 0)
                 *  {
                 *      await msg.ModifyAsync(x =>
                 *      {
                 *          x.Content =
                 *              ":no_entry_sign: Failed to convert video to opus :/";
                 *      });
                 *      return "f";
                 *  }
                 *
                 *  if (File.Exists($"{name}.opus"))
                 *  {
                 *      File.Delete($"{name}.wav");
                 *      await msg.ModifyAsync(
                 *          x => { x.Content = ":musical_note: Successfully Downloaded and Encoded!"; });
                 *      return name;
                 *  }
                 * }*/
            }
            else
            {
                await msg.ModifyAsync(x => { x.Content = "It must be a YT link! Failed to Download."; });
            }
            if (stream)
            {
                return(name);
            }
            else
            {
                return("f");
            }
        }
Пример #29
0
        public async Task RemoveRoleFromList(SocketCommandContext Context, string roleName)
        {
            try
            {
                if (!_availableRoles.ContainsKey(Context.Guild.Id))
                {
                    await Context.Channel.SendMessageAsync(
                        ":no_entry_sign: There are no self-assignable roles in this guild!");

                    return;
                }

                List <ulong> roleIDs = new List <ulong>();
                _availableRoles.TryGetValue(Context.Guild.Id, out roleIDs);
                bool         success       = false;
                List <ulong> rolesToDelete = new List <ulong>();
                foreach (var rId in roleIDs)
                {
                    var role = Context.Guild.GetRole(rId);
                    if (role == null)
                    {
                        rolesToDelete.Add(rId);
                        continue;
                    }
                    if (role.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        roleIDs.Remove(rId);
                        if (roleIDs.Count < 1)
                        {
                            List <ulong> ignore = new List <ulong>();
                            _availableRoles.TryRemove(Context.Guild.Id, out ignore);
                        }
                        else
                        {
                            _availableRoles.TryUpdate(Context.Guild.Id, roleIDs);
                        }

                        SaveDatabase();
                        await Context.Channel.SendMessageAsync(
                            $":white_check_mark: Successfully removed Role `{role.Name}`");

                        success = true;
                        break;
                    }
                }

                if (rolesToDelete.Count > 0)
                {
                    foreach (var role in rolesToDelete)
                    {
                        roleIDs.Remove(role);
                    }
                    _availableRoles.TryUpdate(Context.Guild.Id, roleIDs);
                    SaveDatabase();
                }
                if (success)
                {
                    return;
                }

                await Context.Channel.SendMessageAsync(
                    ":no_entry_sign: Specified role could not be found! Use `<prefix>getRoles` to get a list of all self-assignable roles!");
            }
            catch (Exception e)
            {
                await Context.Channel.SendMessageAsync(
                    $":no_entry_sign: Failed to add role. I'm probably missing the perms!");

                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
        }