コード例 #1
0
        public static async Task GIRUBotInitializationTasks()
        {
            try
            {
                ITextChannel chnl = null;

                while (chnl == null)
                {
                    chnl = _client.GetChannel(Global.Config.MeleeSlasherMainChannel) as ITextChannel;
                    if (chnl != null)
                    {
                        await chnl.SendMessageAsync("GIRUBotV3 starting...");


                        var exceptionHandlerReady = ExceptionHandler.InitContext(_client);
                        if (exceptionHandlerReady)
                        {
                            await chnl.SendMessageAsync("Reporting systems online");
                        }

                        await chnl.SendMessageAsync("Ready");
                    }

                    Task.Delay(1000).Wait();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to initialize GIRUBot {ex.Message}");
                throw ex;
            }
        }
コード例 #2
0
        private async Task <bool> EnsureBotPermissions(ITextChannel channel)
        {
            var guildUser = await channel.Guild.GetCurrentUserAsync();

            var permissions = guildUser.GetPermissions(channel);

            // If we can't send messages at all, just bail immediately.
            // TODO: can you have ManageMessages and *not* SendMessages? What happens then?
            if (!permissions.SendMessages && !permissions.ManageMessages)
            {
                return(false);
            }

            if (!permissions.ManageWebhooks)
            {
                // todo: PKError-ify these
                await channel.SendMessageAsync(
                    $"{Emojis.Error} PluralKit does not have the *Manage Webhooks* permission in this channel, and thus cannot proxy messages. Please contact a server administrator to remedy this.");

                return(false);
            }

            if (!permissions.ManageMessages)
            {
                await channel.SendMessageAsync(
                    $"{Emojis.Error} PluralKit does not have the *Manage Messages* permission in this channel, and thus cannot delete the original trigger message. Please contact a server administrator to remedy this.");

                return(false);
            }

            return(true);
        }
コード例 #3
0
        public async Task ExecuteGiveaway(GiveawayEntry entry, ulong serverId)
        {
            IGuild guild = await m_client.GetGuildAsync(serverId);

            ServerEntry  server  = m_db.GetServerEntry(serverId);
            ITextChannel channel = await guild.GetTextChannelAsync(entry.ChannelId);

            IUserMessage message = await channel.GetMessageAsync(entry.ReactionMessageId) as IUserMessage;

            var asyncparticipants     = message.GetReactionUsersAsync(new Emoji(server.GiveawayReactionEmote), int.MaxValue);
            IEnumerable <IUser> users = await asyncparticipants.FlattenAsync();

            List <IUser> participants = users.Where(user => user.Id != m_client.CurrentUser.Id).ToList();

            List <IUser> winners = new List <IUser>();

            if (participants.Count <= 0)
            {
                await channel.SendMessageAsync($"No one participated for {entry.Content}");
            }
            else
            {
                for (int i = 0; i < entry.Count; i++)
                {
                    IUser winner;
                    do
                    {
                        winner = participants[m_random.Next(0, participants.Count)];
                    } while(winners.Contains(winner) && entry.Count < participants.Count);
                    winners.Add(winner);
                }

                await channel.SendMessageAsync($"{string.Join(' ', winners.Select(winner => winner.Mention))} won **{entry.Content}**!");
            }
        }
コード例 #4
0
        public async Task KickAsync([Summary("The user to kick.")] IGuildUser target, [Optional] string reason)
        {
            IDMChannel dmchannel = await target.CreateDMChannelAsync();                                                                         //  Stores a dmchannel with the target

            ITextChannel logchannel = await Context.Guild.GetTextChannelAsync(246572485292720139) as ITextChannel;                              //  Stores the logchannel

            await dmchannel.SendMessageAsync($"You have been kicked from {target.Guild.ToString()}.");                                          //  Sends a message in the dmchannel

            await logchannel.SendMessageAsync($"USER: {target} ID: {target.Id} has been KICKED.");                                              //  Sends text to the logchannel


            if (!string.IsNullOrWhiteSpace(reason))                                                                                             //  Checks to see if the input parameter 'reason' is null or whitespace
            {
                await dmchannel.SendMessageAsync($"Reason: {reason}.");                                                                         //  Sends the reason parameter to the dmchannel

                await logchannel.SendMessageAsync($"REASON: {reason}.");                                                                        //  Sends the reason parameter to the logchannel
            }

            await dmchannel.SendMessageAsync($"If you would like to appeal this kick, send a message to: {Context.User.Mention}.");             //  Sends text to the dmchannel

            await dmchannel.SendMessageAsync(Format.Italics("this is an automated message."));                                                  //  Sends text to the dmchannel in the italics format


            await target.KickAsync();                                                                                                           //  Calls the KickAsync function on the target

            await Context.Channel.SendMessageAsync($"Kicked user: {target}.");                                                                  //  Sends a message to the channel to say that the user has been kicked

            await Context.Channel.SendFileAsync("Gifs/Admin_Kicks_User.gif");                                                                   //  Sends a gif to the channel
        }
コード例 #5
0
        private async Task <bool> EnsureBotPermissions(ITextChannel channel)
        {
            var guildUser = await channel.Guild.GetCurrentUserAsync();

            var permissions = guildUser.GetPermissions(channel);

            if (!permissions.ManageWebhooks)
            {
                // todo: PKError-ify these
                await channel.SendMessageAsync(
                    $"{Emojis.Error} PluralKit does not have the *Manage Webhooks* permission in this channel, and thus cannot proxy messages. Please contact a server administrator to remedy this.");

                return(false);
            }

            if (!permissions.ManageMessages)
            {
                await channel.SendMessageAsync(
                    $"{Emojis.Error} PluralKit does not have the *Manage Messages* permission in this channel, and thus cannot delete the original trigger message. Please contact a server administrator to remedy this.");

                return(false);
            }

            return(true);
        }
コード例 #6
0
        public async Task <string> GetRolesId(IGuildUser user, ITextChannel chan, string[] args)
        {
            if (user.Id != user.Guild.OwnerId)
            {
                await chan.SendMessageAsync("Only " + (await user.Guild.GetOwnerAsync()).ToString() + " can do this command.");

                return(null);
            }
            if (args.Length == 0)
            {
                await chan.SendMessageAsync("You must provide the roles that will be considered as staff.");

                return(null);
            }
            if (args[0].ToLower() == "none")
            {
                return("None");
            }
            var roles = args.Select(x => DiscordUtils.Utils.GetRole(x, chan.Guild));

            if (roles.Any(x => x == null))
            {
                await chan.SendMessageAsync("One of the role you gave isn't a valid one.");

                return(null);
            }
            return(string.Join("|", roles.Select(x => x.Id.ToString())));
        }
コード例 #7
0
            private async Task TrackStream(ITextChannel channel, string username, FollowedStream.FollowedStreamType type)
            {
                username = username.ToLowerInvariant().Trim();
                var stream = new FollowedStream
                {
                    GuildId   = channel.Guild.Id,
                    ChannelId = channel.Id,
                    Username  = username,
                    Type      = type,
                };
                bool exists;

                using (var uow = DbHandler.UnitOfWork())
                {
                    exists = uow.GuildConfigs.For(channel.Guild.Id).FollowedStreams.Where(fs => fs.ChannelId == channel.Id && fs.Username.ToLowerInvariant().Trim() == username).Any();
                }
                if (exists)
                {
                    await channel.SendMessageAsync($":anger: I am already following `{username}` ({type}) stream on this channel.").ConfigureAwait(false);

                    return;
                }
                StreamStatus data;

                try
                {
                    data = await GetStreamStatus(stream).ConfigureAwait(false);
                }
                catch
                {
                    await channel.SendMessageAsync(":anger: Stream probably doesn't exist.").ConfigureAwait(false);

                    return;
                }
                var msg = $"Stream is currently **{(data.IsLive ? "ONLINE" : "OFFLINE")}** with **{data.Views}** viewers";

                if (data.IsLive)
                {
                    if (type == FollowedStream.FollowedStreamType.Hitbox)
                    {
                        msg += $"\n`Here is the Link:`【 http://www.hitbox.tv/{stream.Username}/ 】";
                    }
                    else if (type == FollowedStream.FollowedStreamType.Twitch)
                    {
                        msg += $"\n`Here is the Link:`【 http://www.twitch.tv/{stream.Username}/ 】";
                    }
                    else if (type == FollowedStream.FollowedStreamType.Beam)
                    {
                        msg += $"\n`Here is the Link:`【 https://beam.pro/{stream.Username}/ 】";
                    }
                }
                using (var uow = DbHandler.UnitOfWork())
                {
                    uow.GuildConfigs.For(channel.Guild.Id).FollowedStreams.Add(stream);
                    await uow.CompleteAsync();
                }
                msg = $":ok: I will notify this channel when status changes.\n{msg}";
                await channel.SendMessageAsync(msg).ConfigureAwait(false);
            }
コード例 #8
0
        internal static async Task UserLeftAsync(SocketGuildUser User)
        {
            await CleanUpAsync(User);

            var Config = GuildHandler.GuildConfigs[User.Guild.Id];

            if (!Config.LeaveEvent.IsEnabled)
            {
                return;
            }

            ITextChannel Channel       = null;
            string       LeaveMessages = null;

            var LeaveChannel = User.Guild.GetChannel(Config.LeaveEvent.TextChannel);

            if (Config.LeaveMessages == null)
            {
                LeaveMessages = $"{User.Mention} just left {User.Guild.Name} :wave:";
            }



            if (User.Guild.GetChannel(Config.LeaveEvent.TextChannel) != null)
            {
                Channel = LeaveChannel as ITextChannel;

                var replace = StringExtension.ReplaceWith(Config.LeaveMessages, User.Username + "#" + User.Discriminator, User.Guild.Name);
                LeaveMessages = replace;
                var embed = new EmbedBuilder()
                {
                    Title        = "=== User Left ===",
                    Description  = $"{LeaveMessages}",
                    Color        = new Color(255, 0, 0),
                    ThumbnailUrl = User.GetAvatarUrl(),
                    Timestamp    = DateTime.UtcNow
                };

                await Channel.SendMessageAsync("", embed : embed);
            }
            else
            {
                Channel = User.Guild.DefaultChannel as ITextChannel;

                var replace = StringExtension.ReplaceWith(Config.LeaveMessages, User.Username, User.Guild.Name);
                LeaveMessages = replace;
                var embed = new EmbedBuilder()
                {
                    Title        = "=== User Left ===",
                    Description  = $"{LeaveMessages}",
                    Color        = new Color(255, 0, 0),
                    ThumbnailUrl = User.GetAvatarUrl(),
                    Timestamp    = DateTime.UtcNow
                };
                await Channel.SendMessageAsync("", embed : embed);
            }
        }
コード例 #9
0
        private async Task GuildJoin(SocketGuild arg)
        {
            string       currTime = DateTime.UtcNow.ToString("ddMMyyHHmmss");
            ITextChannel chan     = returnChannel(arg.Channels.ToList(), arg.Id);

            if (!Directory.Exists("Saves"))
            {
                Directory.CreateDirectory("Saves");
            }
            if (!File.Exists("Saves/sanaraDatas.dat"))
            {
                File.WriteAllText("Saves/sanaraDatas.dat", currTime); // Creation date
            }
            if (!Directory.Exists("Saves/Servers/" + arg.Id))
            {
                Directory.CreateDirectory("Saves/Servers/" + arg.Id);
                File.WriteAllText("Saves/Servers/" + arg.Id + "/serverDatas.dat", currTime + Environment.NewLine + 0 + Environment.NewLine + arg.Name); // Join date | unused | server name
                await chan.SendMessageAsync(Sentences.introductionMsg(arg.Id));
            }
            if (!File.Exists("Saves/Servers/" + arg.Id + "/kancolle.dat"))
            {
                File.WriteAllText("Saves/Servers/" + arg.Id + "/kancolle.dat", "0" + Environment.NewLine + "0" + Environment.NewLine + "0" + Environment.NewLine + "0" + Environment.NewLine + "0");
            }
            // Attempt game, attempt ship, ship found, bestScore, ids of people who help to have the best score
            if (!Directory.Exists("Saves/Users"))
            {
                Directory.CreateDirectory("Saves/Users");
            }
            guildLanguages.Add(arg.Id, (File.Exists("Saves/Servers/" + arg.Id + "/language.dat")) ? (File.ReadAllText("Saves/Servers/" + arg.Id + "/language.dat")) : ("en"));
            prefixs.Add(arg.Id, (File.Exists("Saves/Servers/" + arg.Id + "/prefix.dat")) ? (File.ReadAllText("Saves/Servers/" + arg.Id + "/prefix.dat")) : ("s."));
            foreach (IUser u in arg.Users)
            {
                if (!File.Exists("Saves/Users/" + u.Id + ".dat"))
                {
                    relations.Add(new Character(u.Id, u.Username));
                }
                else
                {
                    try
                    {
                        if (!relations.Any(x => x._name == Convert.ToUInt64(File.ReadAllLines("Saves/Users/" + u.Id + ".dat")[1])))
                        {
                            relations.Add(new Character());
                            relations[relations.Count - 1].saveAndParseInfos(File.ReadAllLines("Saves/Users/" + u.Id + ".dat"));
                        }
                    }
                    catch (IndexOutOfRangeException)
                    {
                        if (arg.Id.ToString() == File.ReadAllLines("Saves/sanaraDatas.dat")[2])
                        {
                            await chan.SendMessageAsync(Sentences.introductionError(arg.Id, u.Id.ToString(), u.Username));
                        }
                    }
                }
            }
        }
コード例 #10
0
        internal static async Task UserJoinedAsync(SocketGuildUser User)
        {
            var Config = GuildHandler.GuildConfigs[User.Guild.Id];

            if (!Config.JoinEvent.IsEnabled)
            {
                return;
            }

            ITextChannel Channel        = null;
            string       WelcomeMessage = null;

            var JoinChannel = User.Guild.GetChannel(Config.JoinEvent.TextChannel);

            if (Config.WelcomeMessages == null)
            {
                WelcomeMessage = $"{User.Mention} just joined {User.Guild.Name}! WELCOME!";
            }


            if (User.Guild.GetChannel(Config.JoinEvent.TextChannel) != null)
            {
                var replace = StringExtension.ReplaceWith(Config.WelcomeMessages, User.Mention, User.Guild.Name);
                WelcomeMessage = replace;
                var embed = new EmbedBuilder()
                {
                    Title        = "=== User Joined ===",
                    Description  = $"{WelcomeMessage}",
                    Color        = new Color(0xAD33FF),
                    ThumbnailUrl = User.GetAvatarUrl(),
                    Timestamp    = DateTime.UtcNow
                };


                Channel = JoinChannel as ITextChannel;
                await Channel.SendMessageAsync("", embed : embed);
            }
            else
            {
                var replace = StringExtension.ReplaceWith(Config.WelcomeMessages, User.Mention, User.Guild.Name);

                WelcomeMessage = replace;
                var embed = new EmbedBuilder()
                {
                    Title        = "=== User Joined ===",
                    Description  = $"{WelcomeMessage}",
                    Color        = new Color(0xAD33FF),
                    ThumbnailUrl = User.GetAvatarUrl(),
                    Timestamp    = DateTime.UtcNow
                };

                Channel = User.Guild.DefaultChannel as ITextChannel;
                await Channel.SendMessageAsync("", embed : embed);
            }
        }
コード例 #11
0
ファイル: PvEEnvironment.cs プロジェクト: dom426/IodemBot
        private async Task Initialize()
        {
            EnemyMessage = await BattleChannel.SendMessageAsync(GetEnemyMessageString());

            _ = EnemyMessage.AddReactionsAsync(new IEmote[]
            {
                Emote.Parse("<:Fight:536919792813211648>"),
                Emote.Parse("<:Battle:536954571256365096>")
            });
            return;
        }
コード例 #12
0
ファイル: AudioService.cs プロジェクト: Bluheir/Frequency2.0
        public async Task SkipTrackAsync(ICommandContext Context, ITextChannel textChannel, bool sendError = true)
        {
            var player = LavaClient.GetPlayer(Context.Guild.Id);
            var user   = await Users.GetValue((long)Context.User.Id);

            var guild = GetOrAddConfig(Context.Guild.Id);



            if (player == null)
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} {GetError(17)}");
                }
                return;
            }

            if (!player.IsPlaying)
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} {GetError(17)}");
                }
                return;
            }
            var myChannel = player.VoiceChannel as SocketVoiceChannel;

            if ((player.IsPlaying && myChannel.Users.Count > 2 && !(Context.User as IGuildUser).ContainsRole("DJ")))
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} {GetError(12)}");
                }
                return;
            }



            if (guild.Queue.Count < 1)
            {
                await player.StopAsync();

                if (sendError && user.SendCompMessage)
                {
                    await textChannel.SendMessageAsync(":musical_note: Successfully skipped the current track!");
                }
            }
            else
            {
                await player.StopAsync();
            }
        }
コード例 #13
0
ファイル: Entrance.cs プロジェクト: gay-sex/Chino-chan
        public static void HandleCommand(string Command, ITextChannel Channel = null)
        {
            var Lower     = Command.ToLower();
            var Trim      = Lower.Trim();
            var Parameter = "";
            var Index     = Command.IndexOf(" ");

            if (Index >= 0)
            {
                Lower     = Lower.Substring(0, Index);
                Trim      = Lower.Trim();
                Parameter = Command.Substring(Index).TrimEnd().TrimStart();
            }
            if (Trim == "gc")
            {
                Clean();
                if (Channel != null)
                {
                    Channel.SendMessageAsync(Channel.GetLanguage().GCDone);
                }
            }
            else if (Trim == "quit")
            {
                if (Channel != null)
                {
                    Channel.SendMessageAsync(
                        Global.LanguageHandler.GetLanguage(
                            Global.GuildSettings.GetSettings(Channel.GuildId).LanguageId).Shutdown).Wait();
                }

                Global.StopAsync().Wait();
                Environment.Exit(exitCode: 0);
            }
            else if (Trim == "reload")
            {
                if (Channel != null)
                {
                    Channel.SendMessageAsync(
                        Global.LanguageHandler.GetLanguage(
                            Global.GuildSettings.GetSettings(Channel.GuildId).LanguageId).Reloading).Wait();
                }

                Reload(Channel);
            }
            else if (Trim == "update")
            {
                if (Global.Updater.Update())
                {
                    Environment.Exit(exitCode: 0);
                }
            }
        }
コード例 #14
0
 //[Command("play",RunMode =RunMode.Async)]
 //[Summary("Palys music")]
 public async Task Play()
 {
     try
     {
         Pause = false;
         this.MusicPlay(Context);
         await _textChannel.SendMessageAsync($"{Context.User.Mention} resumed playback!");
     }
     catch (Exception ex)
     {
         CommonTools.ErrorReporting(ex);
     }
 }
コード例 #15
0
ファイル: AudioService.cs プロジェクト: Bluheir/Frequency2.0
        public async Task InsertSongAsync(string song, int index, ICommandContext Context, ITextChannel textChannel, bool sendError = true, bool prioritiseSoundcloud = false)
        {
            var player = LavaClient.GetPlayer(Context.Guild.Id);
            var user   = await Users.GetValue((long)Context.User.Id);

            var guild = GetOrAddConfig(Context.Guild.Id);

            index -= 1;

            if (player == null || !player.IsPlaying)
            {
                await PlayAsync(song, Context, textChannel, sendError, prioritiseSoundcloud);

                return;
            }
            if (player == null)
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} {GetError(17)}");
                }
                return;
            }

            if (index >= guild.Queue.Count)
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} :x: That index is out of range");
                }
            }

            var myChannel = player.VoiceChannel as SocketVoiceChannel;

            if ((player.IsPlaying && myChannel.Users.Count > 2 && !(Context.User as IGuildUser).ContainsRole("DJ")))
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} {GetError(12)}");
                }
                return;
            }
            var track = await GetTrack(song, prioritiseSoundcloud);

            guild.Queue.Insert(index, track);

            if (user.SendCompMessage && sendError)
            {
                await textChannel.SendMessageAsync($":musical_note: Successfully inserted song `{track.Title}` at index {index} of the queue!");
            }
        }
コード例 #16
0
        public async Task <LavaPlayer?> JoinAsync(ICommandContext context, ITextChannel textChannel, bool sendMsg = true, bool sendAdv = true)
        {
            if (context.Guild == null)
            {
                return(null);
            }
            ;
            _audio.TryGetPlayer(context.Guild, out var guild);
            var usersVc = context.UsersVC() as SocketVoiceChannel;
            var user    = context.User as IGuildUser;

            if (usersVc == null)
            {
                if (sendMsg)
                {
                    await textChannel.SendMessageAsync($":musical_note: {context.User.Mention} You are not in a voice channel.");
                }
                return(null);
            }
            if (guild == null)
            {
                if (sendMsg && sendAdv)
                {
                    await textChannel.SendMessageAsync($":musical_note: {context.User.Mention} Successfuly joined your voice channel!");
                }
                return(await _audio.JoinAsync(context.UsersVC(), textChannel));
            }
            else if (usersVc.Id == guild.VoiceChannel.Id)
            {
                if (sendMsg && sendAdv)
                {
                    await textChannel.SendMessageAsync($":musical_note: {context.User.Mention} We are in the same voice channel already!");
                }
                return(guild);
            }
            else if (usersVc.Users.Count > 1 && !user.HasRole("DJ"))
            {
                if (sendMsg)
                {
                    await textChannel.SendMessageAsync($":musical_note: {context.User.Mention} You don't have the valid permissions to do this action.");
                }
                return(null);
            }
            if (sendMsg && sendAdv)
            {
                await textChannel.SendMessageAsync($":musical_note: {context.User.Mention} Successfuly joined your voice channel!");
            }
            await _audio.LeaveAsync(guild.VoiceChannel);

            return(await _audio.JoinAsync(context.UsersVC(), textChannel));
        }
コード例 #17
0
        async Task UserJoinedVc(SocketGuildUser user, SocketVoiceState state)
        {
            var          voice  = state.VoiceChannel;
            ITextChannel text   = null;
            bool         manage = false;

            if (Pairings.TryGetValue(voice, out var txtId))
            {
                text = user.Guild.GetTextChannel(txtId);
            }
            else if (hasEnabledPairing(user, state.IsSelfMuted))
            {
                manage = true;
                var ls = new List <Overwrite>();
                ls.Add(new Overwrite(user.Guild.EveryoneRole.Id, PermissionTarget.Role, new OverwritePermissions(viewChannel: PermValue.Deny)));
                foreach (var x in voice.Users)
                {
                    ls.Add(new Overwrite(x.Id, PermissionTarget.User, perms(x.Id == user.Id)));
                }
                text = await user.Guild.CreateTextChannelAsync("pair-" + voice.Name, x =>
                {
                    x.PermissionOverwrites = ls;
                    x.CategoryId           = voice.CategoryId;
                    x.Position             = 999;
                    x.Topic = $"Paired channel with <#{voice.Id}>.";
                });

                Pairings.Add(voice, text.Id);
                OnSave();
                await text.SendMessageAsync(embed : new EmbedBuilder()
                                            .WithTitle("Paired Channel")
                                            .WithDescription("This channel will be deleted once the user leaves the paired voice channel.")
                                            .WithAuthor(user)
                                            .Build());
            }
            if (text == null)
            {
                return;
            }
            await text.AddPermissionOverwriteAsync(user, perms(manage));

            if (!manage)
            {
                await text.SendMessageAsync(embed : new EmbedBuilder()
                                            .WithTitle("User Joined Paired VC")
                                            .WithDescription($"{user.GetName()} has joined the paired VC.\r\n" +
                                                             $"They have been granted permission to access this channel.")
                                            .WithAuthor(user)
                                            .Build());
            }
        }
コード例 #18
0
 public async Task <bool> Stop()
 {
     if (!IsActive)
     {
         return(false);
     }
     NadekoBot.Client.MessageReceived -= AnswerReceived;
     finishedUserIds.Clear();
     IsActive = false;
     sw.Stop();
     sw.Reset();
     try { await channel.SendMessageAsync("Typing contest stopped").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
     return(true);
 }
コード例 #19
0
ファイル: AudioService.cs プロジェクト: Bluheir/Frequency2.0
        public async Task ShuffleAsync(ICommandContext Context, ITextChannel textChannel, bool sendError = true)
        {
            var player = LavaClient.GetPlayer(Context.Guild.Id);
            var user   = await Users.GetValue((long)Context.User.Id);

            var guild = _guildConfigs.GetOrAdd(player.VoiceChannel.GuildId, new GuildMusicConfig());

            if (player == null)
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} {GetError(17)}");
                }
                return;
            }

            if (!player.IsPlaying)
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} {GetError(17)}");
                }
                return;
            }

            if (guild.Queue.Count < 2)
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} {GetError(18)}");
                }
            }
            var myChannel = player.VoiceChannel as SocketVoiceChannel;

            if ((player.IsPlaying && myChannel.Users.Count > 2 && !(Context.User as IGuildUser).ContainsRole("DJ")))
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} {GetError(12)}");
                }
                return;
            }

            guild.Queue.Shuffle();

            if (sendError && user.SendCompMessage)
            {
                await(textChannel.SendMessageAsync($":musical_note: Successfully shuffled the queue!"));
            }
        }
コード例 #20
0
        public async Task Reply(IUser agent, ITextChannel channel, string user, string content)
        {
            if (UserAccounts.GetAccountByName(user).UserName == channel.Name)
            {
                var   userID = UserAccounts.GetAccountByName(user).UserID;
                var   guild  = Utils.Guild;
                IUser target = guild.GetUser(userID);
                if (target != null)
                {
                    var eb = new EmbedBuilder()
                    {
                        Author = new EmbedAuthorBuilder()
                        {
                            IconUrl = agent.GetAvatarUrl(),
                            Name    = $"{agent.Username}#{agent.Discriminator} replied to your question."
                        },
                        Description = content,
                        Footer      = new EmbedFooterBuilder()
                        {
                            Text = DateTime.Now.ToString(),
                        }
                    };
                    var ebl = new EmbedBuilder()
                    {
                        Author = new EmbedAuthorBuilder()
                        {
                            IconUrl = target.GetAvatarUrl(),
                            Name    = $"Sent reply to {target.Username}#{target.Discriminator}."
                        },
                        Description = content,
                        Footer      = new EmbedFooterBuilder()
                        {
                            Text = DateTime.Now.ToString(),
                        }
                    };
                    await channel.SendMessageAsync("", false, eb.Build());

                    DMTicket.ReplyToDM(target, "", eb);
                    await Task.CompletedTask;
                    return;
                }
            }
            else
            {
                await channel.SendMessageAsync("Invalid ticket channel, This command only works in ticket channels.");
            }
            return;
        }
コード例 #21
0
ファイル: AudioService.cs プロジェクト: Bluheir/Frequency2.0
        public async Task RemoveSongAtAsync(int index, ICommandContext Context, ITextChannel textChannel, bool sendError = true)
        {
            var player = LavaClient.GetPlayer(Context.Guild.Id);
            var user   = await Users.GetValue((long)Context.User.Id);

            var guild = GetOrAddConfig(Context.Guild.Id);

            index -= 1;


            if (player == null || !player.IsPlaying)
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} :x: There are no songs playing");
                }
                return;
            }


            if (index >= guild.Queue.Count)
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} :x: That index is out of range");
                }
            }

            var myChannel = player.VoiceChannel as SocketVoiceChannel;

            if ((player.IsPlaying && myChannel.Users.Count > 2 && !(Context.User as IGuildUser).ContainsRole("DJ")))
            {
                if (sendError)
                {
                    await textChannel.SendMessageAsync($"{Context.User.Mention} {GetError(12)}");
                }
                return;
            }

            var track = guild.Queue[index];

            guild.Queue.RemoveAt(index);

            if (user.SendCompMessage && sendError)
            {
                await textChannel.SendMessageAsync($":musical_note: Successfully removed song `{track.Title}` at index {index} of the queue!");
            }
        }
コード例 #22
0
 private async Task SendMessageAsync(string message, ITextChannel channel)
 {
     if (channel != null)
     {
         await channel.SendMessageAsync(message);
     }
 }
コード例 #23
0
ファイル: Moderation.cs プロジェクト: jpmac26/JackFrost-Bot
        public static async void PruneNonmembers(SocketGuildUser moderator, ITextChannel channel, IReadOnlyCollection <IGuildUser> users)
        {
            int usersPruned = 0;

            foreach (IGuildUser user in users)
            {
                if (user.RoleIds.Count <= 1)
                {
                    Processing.LogConsoleText($"Nonmember found: {user.Username}", channel.Guild.Id);
                    await user.KickAsync("Inactivity");

                    usersPruned++;
                }
            }

            var embed = Embeds.PruneNonmembers(usersPruned);
            await channel.SendMessageAsync("", embed : embed).ConfigureAwait(false);

            //Log the prune in the bot-logs channel
            embed = Embeds.LogPruneNonmembers(moderator, usersPruned);
            var botlog = await channel.Guild.GetTextChannelAsync(UserSettings.Channels.BotLogsId(channel.Guild.Id));

            if (botlog != null)
            {
                await botlog.SendMessageAsync("", embed : embed).ConfigureAwait(false);
            }
        }
コード例 #24
0
ファイル: Moderation.cs プロジェクト: jpmac26/JackFrost-Bot
        public static async void PruneLurkers(SocketGuildUser moderator, ITextChannel channel, IReadOnlyCollection <IGuildUser> users)
        {
            int usersPruned = 0;

            foreach (IGuildUser user in users)
            {
                if (user.RoleIds.Any(x => x == UserSettings.Roles.LurkerRoleID(channel.Guild.Id)))
                {
                    Console.WriteLine($"Lurker found: {user.Username}");
                    await user.KickAsync("Inactivity");

                    usersPruned++;
                }
            }

            var embed = Embeds.PruneLurkers(usersPruned);
            await channel.SendMessageAsync("", embed : embed).ConfigureAwait(false);

            //Log the unmute in the bot-logs channel
            embed = Embeds.LogPruneLurkers(moderator, usersPruned);
            var botlog = await channel.Guild.GetTextChannelAsync(UserSettings.Channels.BotLogsId(channel.Guild.Id));

            if (botlog != null)
            {
                await botlog.SendMessageAsync("", embed : embed).ConfigureAwait(false);
            }
        }
コード例 #25
0
ファイル: Moderation.cs プロジェクト: jpmac26/JackFrost-Bot
        public static async void Unlock(SocketGuildUser moderator, ITextChannel channel)
        {
            //Unlock the channel
            var guild = channel.Guild;

            //Don't mess with channel permissions if nonmembers can't speak there anyway
            if (IsPublicChannel((SocketGuildChannel)channel))
            {
                try
                {
                    await channel.RemovePermissionOverwriteAsync(guild.EveryoneRole, RequestOptions.Default);
                }
                catch
                {
                    Processing.LogConsoleText($"Failed to unlock {guild.Name}#{channel.Name.ToString()}", guild.Id);
                }
            }

            //Announce the unlock
            var embed = Embeds.Unlock(channel);
            await channel.SendMessageAsync("", embed : embed).ConfigureAwait(false);

            //Log the lock in the bot-logs channel
            embed = Embeds.LogUnlock(moderator, channel);
            var botlog = await channel.Guild.GetTextChannelAsync(UserSettings.Channels.BotLogsId(channel.Guild.Id));

            if (botlog != null)
            {
                await botlog.SendMessageAsync("", embed : embed).ConfigureAwait(false);
            }
        }
コード例 #26
0
ファイル: Moderation.cs プロジェクト: jpmac26/JackFrost-Bot
        public static async void Unmute(string moderator, ITextChannel channel, SocketGuildUser user)
        {
            foreach (SocketTextChannel chan in user.Guild.TextChannels)
            {
                var guild = user.Guild;
                //Don't mess with channel permissions if nonmembers can't speak there anyway
                if (IsPublicChannel(chan))
                {
                    try
                    {
                        await chan.RemovePermissionOverwriteAsync(user, RequestOptions.Default);
                    }
                    catch
                    {
                        Processing.LogConsoleText($"Failed to unmute in {guild.Name}#{chan.Name.ToString()}", guild.Id);
                    }
                }
            }

            var embed = Embeds.Unmute(user);
            await channel.SendMessageAsync("", embed : embed).ConfigureAwait(false);

            //Log the unmute in the bot-logs channel
            embed = Embeds.LogUnmute(moderator, channel, user);
            var botlog = await channel.Guild.GetTextChannelAsync(UserSettings.Channels.BotLogsId(user.Guild.Id));

            if (botlog != null)
            {
                await botlog.SendMessageAsync("", embed : embed).ConfigureAwait(false);
            }
        }
コード例 #27
0
        public Task JoinedGuild(SocketGuild e)
        {
            //Set activity
            string[]  Players = File.ReadAllLines("PlayerID");
            IActivity game    = new Game("//help | " + Players[0] + " Players in " + _client.Guilds.Count + " Guild") as IActivity;

            _client.SetActivityAsync(game);

            //Send join message
            try
            {
                ITextChannel channel = e.DefaultChannel as ITextChannel;
                channel.SendMessageAsync(
                    "**Hello, I'm LewdBox.**\n\n" +
                    "I have been summoned to bring fun upon this server.\n" +
                    "If you haven't registered an account yet, use //register\n\n" +
                    "For more information use //help or //info\n" +
                    "Have fun.");
            }
            catch (Exception args)
            {
                Console.WriteLine(args.Message);
                return(Task.CompletedTask);
            }

            return(Task.CompletedTask);
        }
コード例 #28
0
        private Task SendReplyAsync(string message)
        {
            var _ = Task.Run(async() =>
            {
                if (_channel != null)
                {
                    _messages.Add(await _channel.SendMessageAsync(message));
                }
                else if (_user != null)
                {
                    _messages.Add(await _user.SendMessageAsync(message));
                }
            });

            return(Task.CompletedTask);
        }
コード例 #29
0
        static async Task <bool> FilterHeadings(SocketUserMessage message)
        {
            if (!message.Content.StartsWith("```"))
            {
                if (message.Author.Id == botId)
                {
                    return(true);
                }

                ITextChannel channel    = (message.Channel as ITextChannel);
                ITextChannel discussion = await channel.Guild.GetChannelAsync(449033901168656403) as ITextChannel;

                await discussion.SendMessageAsync($@"Hi {message.Author.Mention} - Messages in {channel.Mention} require a heading!

To help, I've created a template for you to copy & paste. Be sure to change the placeholder text!
If you were simply trying to discuss someone elses message, this is the place to do so.
Alternatively react with a :thumbsup: to show your support.

` ```Your Heading```
{message.Content}`");

                await message.DeleteAsync();

                await ReplyAndDelete(message, $"Hi {message.Author.Mention}! Your message needs a heading! Let me help you out in {discussion.Mention}.", 10);

                return(false);
            }

            return(true);
        }
コード例 #30
0
        private async Task <long> CreateTwitchMessage(TwitchStreamer streamer, Stream stream,
                                                      TwitchAlertSubscription subscription, ITextChannel channel)
        {
            var message = await channel.SendMessageAsync($"@everyone {streamer.Name} is live!", embed : CreateTwitchEmbed(streamer, stream));

            return((long)message.Id);
        }
コード例 #31
0
 private static async Task<bool> IsAnimeListAuthorized(ITextChannel e)
 {
     if ((DateTime.Now - Storage.anilistAuthorizationCreated).TotalMinutes > 50)
     {
         if (!await AuthorizeAnilistAsync())
         {
             await e.SendMessageAsync($"Something went wrong authorizing Anilist, please try again!");
             return false;
         }
     }
     return true;
 }
コード例 #32
0
 private async Task TrackStream(ITextChannel channel, string username, FollowedStream.FollowedStreamType type)
 {
     username = username.ToLowerInvariant().Trim();
     var stream = new FollowedStream
     {
         GuildId = channel.Guild.Id,
         ChannelId = channel.Id,
         Username = username,
         Type = type,
     };
     bool exists;
     using (var uow = DbHandler.UnitOfWork())
     {
         exists = uow.GuildConfigs.For(channel.Guild.Id).FollowedStreams.Where(fs => fs.ChannelId == channel.Id && fs.Username.ToLowerInvariant().Trim()  == username).Any();
     }
     if (exists)
     {
         await channel.SendMessageAsync($":anger: I am already following `{username}` ({type}) stream on this channel.").ConfigureAwait(false);
         return;
     }
     StreamStatus data;
     try
     {
         data = await GetStreamStatus(stream).ConfigureAwait(false);
     }
     catch
     {
         await channel.SendMessageAsync(":anger: Stream probably doesn't exist.").ConfigureAwait(false);
         return;
     }
     var msg = $"Stream is currently **{(data.IsLive ? "ONLINE" : "OFFLINE")}** with **{data.Views}** viewers";
     if (data.IsLive)
         if (type == FollowedStream.FollowedStreamType.Hitbox)
             msg += $"\n`Here is the Link:`【 http://www.hitbox.tv/{stream.Username}/ 】";
         else if (type == FollowedStream.FollowedStreamType.Twitch)
             msg += $"\n`Here is the Link:`【 http://www.twitch.tv/{stream.Username}/ 】";
         else if (type == FollowedStream.FollowedStreamType.Beam)
             msg += $"\n`Here is the Link:`【 https://beam.pro/{stream.Username}/ 】";
     using (var uow = DbHandler.UnitOfWork())
     {
         uow.GuildConfigs.For(channel.Guild.Id).FollowedStreams.Add(stream);
         await uow.CompleteAsync();
     }
     msg = $":ok: I will notify this channel when status changes.\n{msg}";
     await channel.SendMessageAsync(msg).ConfigureAwait(false);
 }
コード例 #33
0
ファイル: Searches.cs プロジェクト: Chewsterchew/NadekoBot
 public static async Task<bool> ValidateQuery(ITextChannel ch, string query)
 {
     if (!string.IsNullOrEmpty(query.Trim())) return true;
     await ch.SendMessageAsync("Please specify search parameters.").ConfigureAwait(false);
     return false;
 }
コード例 #34
0
ファイル: Music.cs プロジェクト: Chewsterchew/NadekoBot
        public static async Task QueueSong(IGuildUser queuer, ITextChannel textCh, IVoiceChannel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal)
        {
            if (voiceCh == null || voiceCh.Guild != textCh.Guild)
            {
                if (!silent)
                    await textCh.SendMessageAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.").ConfigureAwait(false);
                throw new ArgumentNullException(nameof(voiceCh));
            }
            if (string.IsNullOrWhiteSpace(query) || query.Length < 3)
                throw new ArgumentException("💢 Invalid query for queue song.", nameof(query));

            var musicPlayer = MusicPlayers.GetOrAdd(textCh.Guild.Id, server =>
            {
                float vol = 1;// SpecificConfigurations.Default.Of(server.Id).DefaultMusicVolume;
                using (var uow = DbHandler.UnitOfWork())
                {
                    vol = uow.GuildConfigs.For(textCh.Guild.Id).DefaultMusicVolume;
                }
                var mp = new MusicPlayer(voiceCh, vol);


                IUserMessage playingMessage = null;
                IUserMessage lastFinishedMessage = null;
                mp.OnCompleted += async (s, song) =>
                {
                    if (song.PrintStatusMessage)
                    {
                        try
                        {
                            if (lastFinishedMessage != null)
                                await lastFinishedMessage.DeleteAsync().ConfigureAwait(false);
                            if (playingMessage != null)
                                await playingMessage.DeleteAsync().ConfigureAwait(false);
                            try { lastFinishedMessage = await textCh.SendMessageAsync($"🎵`Finished`{song.PrettyName}").ConfigureAwait(false); } catch { }
                            if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.Provider == "YouTube")
                            {
                                await QueueSong(queuer.Guild.GetCurrentUser(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false);
                            }
                        }
                        catch { }
                    }
                };
                mp.OnStarted += async (s, song) =>
                {
                    if (song.PrintStatusMessage)
                    {
                        var sender = s as MusicPlayer;
                        if (sender == null)
                            return;

                            var msgTxt = $"🎵`Playing`{song.PrettyName} `Vol: {(int)(sender.Volume * 100)}%`";
                        try { playingMessage = await textCh.SendMessageAsync(msgTxt).ConfigureAwait(false); } catch { }
                    }
                };
                return mp;
            });
            Song resolvedSong;
            try
            {
                musicPlayer.ThrowIfQueueFull();
                resolvedSong = await Song.ResolveSong(query, musicType).ConfigureAwait(false);

                if (resolvedSong == null)
                    throw new SongNotFoundException();

                musicPlayer.AddSong(resolvedSong, queuer.Username);
            }
            catch (PlaylistFullException)
            {
                try { await textCh.SendMessageAsync($"🎵 `Queue is full at {musicPlayer.MaxQueueSize}/{musicPlayer.MaxQueueSize}.` "); } catch { }
                throw;
            }
            if (!silent)
            {
                try
                {
                    var queuedMessage = await textCh.SendMessageAsync($"🎵`Queued`{resolvedSong.PrettyName} **at** `#{musicPlayer.Playlist.Count + 1}`").ConfigureAwait(false);
                    var t = Task.Run(async () =>
                    {
                        try
                        {
                            await Task.Delay(10000).ConfigureAwait(false);
                        
                            await queuedMessage.DeleteAsync().ConfigureAwait(false);
                        }
                        catch { }
                    }).ConfigureAwait(false);
                }
                catch { } // if queued message sending fails, don't attempt to delete it
            }
        }