예제 #1
0
        public async Task AnnounceRegistration(SocketTextChannel channel, RestUserMessage message)
        {
            var embed1 = new EmbedBuilder()
                         .WithColor(new Color(114, 137, 218))
                         .WithTitle("IT BEGINS TO RAIN!")
                         .WithImageUrl(_config["rainImageUrlAnnouncement"])
                         .Build();
            var embed2 = new EmbedBuilder()
                         .WithColor(new Color(114, 137, 218))
                         .WithTitle("QUICK, SEND ME YOUR WALLET ADDRESSES!")
                         .WithDescription($"YOU HAVE ``{_registerDelay.TotalSeconds}`` SECONDS TO SEND ME YOUR WALLET ADDRESS.\nDON'T FORGET TO ADD THE REACTION I WILL SEND YOU BACK.")
                         .WithImageUrl(_config["rainImageUrlRegistration"])
                         .Build();

            await message.ModifyAsync(m => m.Embed = embed1);

            foreach (var emote in ReactionEmotes)
            {
                await message.AddReactionAsync(emote);

                await Task.Delay(2500);
            }

            _logger.LogInformation("=== ACCEPT REGISTRATION ===");
            _guildUsers = await _guild.GetUsersAsync();

            State = RainServiceState.AcceptingRegistrations;

            await message.ModifyAsync(m => m.Embed = embed2);
        }
예제 #2
0
        private async Task MessageReceived(SocketMessage message)
        {
            Console.WriteLine($"{message.Channel} => {message.Content.ToString()} from {message.Author}");
            var command = message.Content.Split(' ');

            if (command[0].ToLower() == CommandPrefix)
            {
                if (command[1].ToLower() == "pp")
                {
                    // await message.Channel.SendMessageAsync("Incoming command");

                    if (message.MentionedUsers.Count == 0)
                    {
                        await CreateAndDistrubutePP(message, (SocketGuildUser)message.Author);
                    }

                    foreach (var MentionedUser in message.MentionedUsers)
                    {
                        await CreateAndDistrubutePP(message, (SocketGuildUser)MentionedUser);
                    }

                    return;
                }

                if (command[1] == "simp")
                {
                    string[] frames = new[] { "⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷" };

                    RestUserMessage restUserMessage = await message.Channel.SendMessageAsync("Detecting Simp");

                    foreach (var frame in frames)
                    {
                        await restUserMessage.ModifyAsync(msg => msg.Content = frame);

                        Thread.Sleep(1000);
                    }

                    await restUserMessage.ModifyAsync(msg => msg.Content = "Detected Simp");
                }

                if (command[1] == "embed")
                {
                    EmbedBuilder builder = new EmbedBuilder();
                    builder.WithTitle("PP Size Machine");
                    builder.WithDescription("SkrubLord's pp \n new Line");
                    builder.WithCurrentTimestamp();
                    builder.WithColor(new Random().Next(0, 255), new Random().Next(0, 255), new Random().Next(0, 255));
                    await message.Channel.SendMessageAsync("", false, builder.Build());

                    return;
                }

                if (command[1] == "help")
                {
                    await message.Channel.SendMessageAsync(" -> twat pp @UserName");

                    return;
                }
            }
        }
예제 #3
0
        public async Task Import([Remainder] string url)
        {
            User            user = GetUser();
            RestUserMessage msg  = await ReplyAsync("Importing character...");

            try
            {
                Character character = await SheetService.NewCharacter(url, Context);

                switch (character.Type)
                {
                case Models.SheetType.Character:
                    user.Character = character;
                    await msg.ModifyAsync(x => x.Content = "The character `" + character.Name + "` (id `" + character.RemoteId + "`) has been successfully imported and has been assigned as your active character!");

                    break;

                case Models.SheetType.Companion:
                    user.Companion = character;
                    await msg.ModifyAsync(x => x.Content = "The companion `" + character.Name + "` (id `" + character.RemoteId + "`) has been successfully imported and has been assigned as your active companion!");

                    break;
                }

                UpdateUser(user);
            }
            catch (Exception e)
            {
                await msg.ModifyAsync(x => x.Content = e.Message);
            }
        }
예제 #4
0
        private async Task PlaceVote(Cacheable <IUserMessage, ulong> userMessage, ISocketMessageChannel channel, SocketReaction reaction)
        {
            if (!voters.ContainsKey(reaction.UserId))
            {
                voters.Add(reaction.UserId, new List <int>());
            }
            List <int> ballot = voters[reaction.UserId];

            if (ballot.Count >= serverData.UserVoteLimit)
            {
                //We need to send the user a fraggin message??? Nope. Maxed out votes, ignore this particular reaction?? Assuming it is even a vote... (which it may very well not be)
                return;
            }

            int vote = MojiCommand.EmojiToVoteNumber(reaction.Emote);

            if (vote >= movieOptions.Length || ballot.Contains(vote))
            {
                //User tried to vote for something outside the valid range, or they already voted for this
                return;
            }

            //If the execution makes it here, we can safely add the vote to the ballot
            voters[reaction.UserId].Add(vote);

            numVotes = CalculateBallotScore();

            //Update any embeds here!
            await voteMessage.ModifyAsync(VoteMessage => {
                VoteMessage.Content = "Movie Vote!!!";
                VoteMessage.Embed   = MakeVoteEmbed();
                return;
            });
        }
예제 #5
0
        /// <summary>
        /// Sends a message to the same channel that evoked this command.
        /// If the command was edited, it will edit the reply to that command instead.
        /// </summary>
        /// <param name="Contents">The contents of the message.</param>
        /// <param name="Embed">The embed of the message, if any.</param>
        /// <param name="IsTTS">Is this message TextToSpeech?</param>
        /// <returns>The RestUserMessage sent or edited. </returns>
        public async Task <RestUserMessage> ReplyAsync(string Contents, Embed Embed = null, bool IsTTS = false)
        {
            if (Command.CommandCache.TryGetValue(Context.Message.Id, out ulong Id))
            {
                RestUserMessage msg = await Context.Channel.GetMessageAsync(Id) as RestUserMessage;

                if (msg != null)
                {
                    await msg.ModifyAsync(x => x.Content = Contents);

                    await msg.ModifyAsync(x => x.Embed = Embed);

                    return(msg);
                }
                else
                {
                    msg = await Context.Channel.SendMessageAsync(Contents, IsTTS, Embed);

                    Command.CommandCache.TryAdd(Context.Message.Id, msg.Id);
                    return(msg);
                }
            }
            else
            {
                var msg = await Context.Channel.SendMessageAsync(Contents, IsTTS, Embed);

                Command.CommandCache.TryAdd(Context.Message.Id, msg.Id);
                return(msg);
            }
        }
예제 #6
0
        public void UpdateLevelsOfMembers(RestUserMessage updateMessage)
        {
            Task.Run(async() =>
            {
                var guild = Global.Bot.GetGuild(Global.ServerID);
                await updateMessage.ModifyAsync(m => m.Content = "0 % Done");
                using (var db = new Database())
                {
                    List <User> users = db.Users.Include(u => u.ExperienceRoleReference).ThenInclude(u => u.RoleReference).ToList();
                    var totalUsers    = users.Count();
                    var userDone      = 0;
                    List <ExperienceRole> rolesUsedInExperience = db.ExperienceRoles.Include(ro => ro.RoleReference).ToList();
                    List <ExperienceLevel> levelConfiguration   = db.ExperienceLevels.ToList();
                    List <SocketRole> experienceRolesInGuild    = new List <SocketRole>();
                    foreach (ExperienceRole role in rolesUsedInExperience)
                    {
                        experienceRolesInGuild.Add(guild.GetRole(role.RoleReference.RoleID));
                    }

                    foreach (var user in users)
                    {
                        await UpdateLevelsForUser(user, db, guild, rolesUsedInExperience, levelConfiguration, experienceRolesInGuild, true);

                        userDone++;
                        if (userDone % (Math.Floor((double)totalUsers / 10)) == 0)
                        {
                            await updateMessage.ModifyAsync(m => m.Content = $"{Math.Ceiling(((double)userDone / totalUsers) * 100)}% ({userDone}/{totalUsers}) done");
                        }
                        db.SaveChanges();
                    }
                    await updateMessage.ModifyAsync(m => m.Content = "Finished");
                }
            }).ContinueWith(t => Console.WriteLine(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
        }
예제 #7
0
 public async Task IncrementTurn()
 {
     if (!isGameGoing)
     {
         return;
     }
     currentTurnUser = currentTurnUser == Player1 ? Player2 : Player1;
     await m.ModifyAsync(m => { m.Content = $"It is {currentTurnUser.Mention}'s turn.\n\n{writeBoard}"; });
 }
예제 #8
0
        /// <summary>
        /// Check images in message and send them in gate if necessary
        /// </summary>
        /// <param name="arg">SocketMessage received from HandleCommandAsync</param>
        /// <param name="msg">User message</param>
        private async Task SendMessageGate(SocketMessage arg, SocketUserMessage msg)
        {
            string url = GetImageUrl(msg);

            if (url != null)
            {
                ulong           guildId = (arg.Channel as ITextChannel).GuildId;
                RestUserMessage waitMsg = await arg.Channel.SendMessageAsync(Sentences.WaitMsg(guildId));

                if (!await db.IsBan(arg.Author.Id.ToString()))
                {
                    bool isNsfw = (arg.Channel as ITextChannel).IsNsfw;
                    if (await IsSfw(url, isNsfw))
                    {
                        TimeSpan?waitValue = CanSendImage(guildId);
                        if (waitValue == null || waitValue.Value.TotalSeconds < 0)
                        {
                            if (timeLastSent.ContainsKey(guildId))
                            {
                                timeLastSent[guildId] = DateTime.Now;
                            }
                            else
                            {
                                timeLastSent.Add(guildId, DateTime.Now);
                            }
                            List <string> ids = db.GetAllGuilds(guildId, isNsfw, out _, out _);
                            if (ids.Count == 0)
                            {
                                await waitMsg.ModifyAsync(x => x.Content = Sentences.NoChan(guildId));
                            }
                            else
                            {
                                await SendImageToServer(ids, arg, url, guildId, waitMsg);
                            }
                        }
                        else
                        {
                            await waitMsg.ModifyAsync(x => x.Content = Sentences.WaitImage(guildId, TimeSpanToString(guildId, waitValue.Value)));
                        }
                    }
                    else
                    {
                        await waitMsg.ModifyAsync(x => x.Content = Sentences.NsfwImage(guildId) + ((isNsfw) ? (" " + Sentences.WrongNsfw(guildId)) : ("")));
                    }
                }
                else
                {
                    await waitMsg.ModifyAsync(x => x.Content = Sentences.IsBannedImage(guildId));
                }
                await IncreaseCommandReceived();
            }
        }
예제 #9
0
        public async Task IntentionalShutdown()
        {
            if (Context.Message.Author.Id == ulong.Parse(Program.Instance.GetSetting("OWNER_ID")))
            {
                if (!Program.Instance.serverUp)
                {
                    Program.Instance.downIntentionally = true;
                    if (Program.Instance.Client.GetChannel(ulong.Parse(Program.Instance.GetSetting("CHANNEL_ID"))) != null)
                    {
                        SocketTextChannel channel = (SocketTextChannel)Program.Instance.Client.GetChannel(ulong.Parse(Program.Instance.GetSetting("CHANNEL_ID")));
                        if (await channel.GetMessageAsync(ulong.Parse(Program.Instance.GetSetting("MESSAGE_ID"))) != null)
                        {
                            RestUserMessage message = (RestUserMessage)await channel.GetMessageAsync(ulong.Parse(Program.Instance.GetSetting("MESSAGE_ID")));

                            await message.ModifyAsync(msg => msg.Embed = EmbedMaker.PlayerListOffline(Color.Red, Program.Instance.Client, true, Program.Instance.GetSetting("SERVER_NAME")));

                            await Context.Message.Channel.SendMessageAsync("Changed down-message to intentional.");
                        }
                    }
                }
                else
                {
                    await Context.Channel.SendMessageAsync($"The server is still up, if this isn't right, try again in **{Program.Instance.GetSetting("INTERVAL_SEC")} seconds**.");
                }
            }
            else
            {
                await Context.Channel.SendMessageAsync($"Only <@{Program.Instance.GetSetting("OWNER_ID")}> can do this.");
            }
        }
예제 #10
0
            public static async Task OctoGameLogs(SocketReaction reaction, RestUserMessage socketMsg)
            {
                var globalAccount = Global.Client.GetUser(reaction.UserId);
                var account       = GameUserAccounts.GetAccount(globalAccount);

                if (account.CurrentLogString.Length >= 1400)
                {
                    account.CurrentLogString = "New page.";
                    GameUserAccounts.SaveAccounts();
                }

                var log = account.CurrentLogString ?? "No logs yet";

                var logPage = new EmbedBuilder();

                logPage.WithAuthor(globalAccount);
                logPage.WithFooter($"Log Fight Page");
                logPage.WithColor(Color.DarkGreen);
                logPage.AddField("Logs", $"{log}");


                await socketMsg.ModifyAsync(message =>
                {
                    message.Embed = logPage.Build();

                    // This somehow can't be empty or it won't update the
                    // embed propperly sometimes... I don't know why
                    // message.Content =  Constants.InvisibleString;
                });
            }
예제 #11
0
        private async Task LoadCommands()
        {
            using (Channel.EnterTypingState())
            {
                commands = new List <Command>();

                var parsedCommands = JObject.Parse(await File.ReadAllTextAsync("Commands.json")).ToObject <Dictionary <string, string> >();

                RestUserMessage lastMessage = null;
                string          messageText = null;

                foreach (var command in parsedCommands)
                {
                    commands.Add(new Command(command.Key, command.Value));

                    if (lastMessage == null)
                    {
                        messageText = $"Registered command: {command.Key}";
                        lastMessage = await Channel.SendMessageAsync(messageText);
                    }
                    else
                    {
                        messageText += $", {command.Key}";
                        await lastMessage.ModifyAsync(msg => msg.Content = messageText);
                    }
                }
            }
        }
        public void UpdateServerRequestInfo()
        {
            EmbedBuilder builder = new EmbedBuilder()
                                   .WithColor(Data.COLOR_BOT)
                                   .WithTitle("Server Request Info")
                                   .WithFooter("(Do not remove this message! It is edited by the bot whenever the above information changes to keep it updated. Removing this message will cause the bot to crash!)");
            List <string> requests = Data.GetContainers <string>(Data.FILE_PATH + Data.REQUEST_FILE);

            if (requests != null)
            {
                builder
                .WithDescription("Current number of requests pending approval: `" + requests.Count() + "`");
            }
            else
            {
                builder
                .WithDescription("Current number of requests pending approval: `Error: Unable to find and retrieve request list.`");
            }

            RestUserMessage message = (RestUserMessage)((SocketTextChannel)Context.Guild.GetChannel(Data.CHANNEL_ID_ADMIN)).GetMessageAsync(Data.MESSAGE_ID_ADMIN_SERVER_REQUEST_INFO).GetAwaiter().GetResult();

            message.ModifyAsync(msg =>
            {
                msg.Content = "";
                msg.Embed   = builder.Build();
            }).GetAwaiter().GetResult();
        }
예제 #13
0
        public static async Task Calc(SocketMessage arg)
        {
            try
            {
                RestUserMessage msg = await arg.Channel.SendMessageAsync($"Syncing..");

                double     allWeight  = 0;
                bool       canRecurse = !(arg.Content.Contains(' ') && int.TryParse(arg.Content.Split(' ')[1], out int _));
                int        thisReq    = arg.Content.Contains(' ') && int.TryParse(arg.Content.Split(' ')[1], out int _) ? int.Parse(arg.Content.Split(' ')[1]) : 100;
                pie_result foodA      = await GrabFood(arg.Author.Id, thisReq, canRecurse);

                Dictionary <string, double> allNames = new Dictionary <string, double>();
                foreach (var foodItem in foodA.value)
                {
                    allWeight += foodItem.Weight;
                    if (foodItem != null)
                    {
                        if (allNames.ContainsKey(foodItem.Name.ToUpper()))
                        {
                            allNames[foodItem.Name.ToUpper()] += foodItem.Weight;
                        }
                        else
                        {
                            allNames.Add(foodItem.Name.ToUpper(), foodItem.Weight);
                        }
                    }
                    else
                    {
                        foodA.value.Remove(foodItem);
                    }
                }
                var  highest5 = allNames.OrderByDescending(pair => pair.Value).Take(5).ToDictionary(pair => pair.Key, pair => pair.Value);
                bool isSuc    = await save.SaveOne(Program.idIndexUser[arg.Author.Id]);

                await msg.ModifyAsync(z =>
                {
                    string a = "";
                    foreach (var key in highest5.Keys)
                    {
                        a += $"\n{key.ToLower()} [{(float)(highest5[key] / allWeight) * 100}%] `x{highest5[key]}`";
                    }
                    z.Embed = new EmbedBuilder()
                    {
                        ThumbnailUrl = arg.Author.GetAvatarUrl(ImageFormat.Auto),
                        Color        = new Color(0x7dffba),
                        Footer       = new EmbedFooterBuilder()
                        {
                            Text = $"since {foodA.value.Last().ConsumedAt.ToShortDateString()}",
                        },
                        Description = a,
                    }.Build();
                    //z.Content = a + $"\n`{foodA.numOfMessagesChecked}` messages analyzed\nsync service `{isSuc}`";
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
예제 #14
0
파일: Ping.cs 프로젝트: olvrb/DiscordList
        public async Task PingAsync()
        {
            RestUserMessage message = await Context.Channel.SendMessageAsync("Ping?");

            await message.ModifyAsync(msg =>
                                      msg.Content =
                                      $"Pong! Current ping is {message.CreatedAt - Context.Message.CreatedAt}");
        }
예제 #15
0
        protected async Task <bool> AddAsync(IMessageChannel channel, ulong msgId, string footer, string title, string content, int position = 0)  // footer required to verify embed "type" (e.g. React-for-Role, server-status etc.)
        {
            if (!(await InitMessage(channel, msgId, new string[] { footer })))
            {
                return(false);
            }
            EmbedBuilder builder;

            if (position == 0) // adds it to the end of the existing embed
            {
                builder = _oldEmbed.ToEmbedBuilder();
                builder.AddField(title, content);
                _newEmbed = builder.Build();
            }
            else
            {
                if (position > 20 || position > _oldEmbed.Fields.Length + 1)
                {
                    await ReplyAsync(database["string", "errTooManyFields"]);

                    return(false);
                }

                builder = new EmbedBuilder();
                builder.WithAuthor(new EmbedAuthorBuilder().WithName(_oldEmbed.Author.Value.Name).WithIconUrl(_oldEmbed.Author.Value.IconUrl));
                builder.WithFooter(footer);

                int i = 1;
                foreach (EmbedField field in _oldEmbed.Fields)
                {
                    if (i++ == position)
                    {
                        builder.AddField(title, content);
                    }
                    if (field.Name != title)
                    {
                        builder.AddField(field.Name, field.Value);                       // allows you to move items within the embed (instead of deleting it then re-adding it)
                    }
                }
                _newEmbed = builder.Build();
            }
            await _msg.ModifyAsync(m => m.Embed = _newEmbed);

            return(true);
        }
        private async Task PerformActionOnAllAsync(SocketCommandContext context, VoiceChannelMatch channelMatch, VoiceChannelAction action, CancellationToken cancellationToken)
        {
            if (!channelMatch.IsSuccess)
            {
                return;
            }

            // verify it's a guild message
            SocketTextChannel responseChannel = await this.VerifyGuildChannelAsync(context, cancellationToken).ConfigureAwait(false);

            if (responseChannel == null)
            {
                return;
            }

            // verify user's permissions
            _log.LogTrace("Verifying user {ID} has {Permission} permission in channel {ChannelName} ({ChannelFromID})", channelMatch.User.Id, action.RequiredPermission, channelMatch.Channel.Name, channelMatch.Channel.Id);
            if (!await this.VerifyUserPermissionsAsync(context, channelMatch.Channel, channelMatch.User.Id, action.RequiredPermission, cancellationToken).ConfigureAwait(false))
            {
                return;
            }

            // verify bot's permissions
            _log.LogTrace("Verifying the bot has {Permission} permission in channel {ChannelName} ({ChannelFromID})", action.RequiredPermission, channelMatch.Channel.Name, channelMatch.Channel.Id);
            if (!await this.VerifyUserPermissionsAsync(context, channelMatch.Channel, context.Client.CurrentUser.Id, action.RequiredPermission, cancellationToken).ConfigureAwait(false))
            {
                return;
            }

            // perform the action on the users
            SocketGuildUser[] users          = channelMatch.Channel.Users.ToArray();
            string            channelMention = GetVoiceChannelMention(channelMatch.Channel);

            _log.LogDebug($"{action.ModeWord} {{Count}} users from channel {{ChannelName}} ({{ChannelID}})", users.Length, channelMatch.Channel.Name, channelMatch.Channel.Id);
            RestUserMessage response = await context.ReplyAsync($"{action.ModeWord} {users.Length} user{(users.Length > 1 ? "s" : null)} in {channelMention}.", cancellationToken).ConfigureAwait(false);

            int errorCount = 0;

            foreach (SocketGuildUser user in users)
            {
                try
                {
                    await user.ModifyAsync(action.Action, cancellationToken).ConfigureAwait(false);
                }
                catch { errorCount++; }
            }
            // display confirmation
            StringBuilder builder      = new StringBuilder();
            int           successCount = users.Length - errorCount;

            builder.AppendFormat("{0} user{1} {2} in {3}.", successCount.ToString(), successCount > 1 || successCount == 0 ? "s" : null, action.ActionCompletedWord, channelMention);
            if (errorCount > 0)
            {
                builder.AppendFormat("\nFailed to {3} {0} user{2}. {1}", errorCount.ToString(), this._einherjiOptions.CurrentValue.FailureSymbol, errorCount > 1 ? "s" : null, action.ActionFailedWord);
            }
            await response.ModifyAsync(props => props.Content = builder.ToString(), cancellationToken).ConfigureAwait(false);
        }
예제 #17
0
        public async Task UpdateLastInteractedWithMessage(string update)
        {
            if (_lastMessagedInteractedWith != null)
            {
                var embed = DiscordHelper.CreateEmbeddedMessage(update);

                await _lastMessagedInteractedWith.ModifyAsync(msg => msg.Embed = embed);
            }
        }
예제 #18
0
        public static async void EditEmbed(bool successful, List <ValorantEvent> jsonParsed, int counter, RestUserMessage message)
        {
            var currentTime     = DateTime.Now.ToLongTimeString();
            var currentTimeZone = TZNames.GetAbbreviationsForTimeZone(TimeZoneInfo.Local.Id, "en-GB").Standard;
            var region          = jsonParsed[0].Regions[counter];
            var embedBuilder    = new EmbedBuilder();

            if (successful)
            {
                embedBuilder = new EmbedBuilder
                {
                    Title       = $"{jsonParsed[0].Regions[counter].Name.ToUpper()} Maintenance Status:",
                    Color       = Color.Green,
                    Description = "There is no scheduled Maintenance!"
                };
                embedBuilder.WithFooter($"Trexia A1.0 | Updated on {currentTime} {currentTimeZone}");

                await message.ModifyAsync(m =>
                {
                    m.Embed = embedBuilder.Build();
                });
            }
            else
            {
                embedBuilder = new EmbedBuilder
                {
                    Title = $"{region.Name.ToUpper()} Maintenance Status:",
                    Color = Color.Red
                };

                if (region.Maintenances[0].MaintenanceStatus.Equals("scheduled"))
                {
                    embedBuilder.AddField("Status:", "Scheduled Maintenance", false);
                }

                embedBuilder.AddField("Description:", jsonParsed[0].Regions[counter].Maintenances[0].Updates[0].Description, false);
                embedBuilder.WithFooter($"Trexia A1.0 | Updated on {currentTime} {currentTimeZone}");

                await message.ModifyAsync(m =>
                {
                    m.Embed = embedBuilder.Build();
                });
            }
        }
예제 #19
0
        public override async Task Run()
        {
            IMessage message = await channel.GetMessageAsync(UInt64.Parse(args[0]));

            RestUserMessage pingMessage = await channel.SendMessageAsync("pinging");

            TimeSpan ping = pingMessage.CreatedAt.Subtract(message.CreatedAt);

            await pingMessage.ModifyAsync(msg => msg.Content = ping.TotalMilliseconds.ToString() + "ms");
        }
예제 #20
0
 private async Task RefreshLobby()
 {
     await _lobbyMessage.ModifyAsync(x => x.Embed = new EmbedBuilder()
                                     .WithColor(Color.Red)
                                     .WithTitle($"Lobby ({Players.Count})")
                                     .WithDescription(
                                         "Join with `-join`. " +
                                         (Players.Count >= 4 ? "Start with `-start`." : "Cannot Start.") + "\n\n" +
                                         string.Join("\n", Players.Select(y => $"**{GetName(y)}**")))
                                     .Build());
 }
        public static async Task First_Use_Content_Filter_Confirm(SocketGuildUser user, RestUserMessage message)
        {
            // Get the account information of the command's target
            var account = UserInfoClasses.GetAccount(user);

            // Find the menu session associated with the current user.
            var menuSession = Global.MenuIdList.SingleOrDefault(x => x.User.Id == user.Id);

            // Search for a content filter list that corresponds to the user's ID.
            var filterSession = Global.ContentFilterList.SingleOrDefault(x => x.User.Id == menuSession.User.Id);

            // Create a new embed that will be displayed in the message.
            var embed  = new EmbedBuilder();
            var author = new EmbedAuthorBuilder
            {
                Name    = "Settings Saved",
                IconUrl = user.GetAvatarUrl()
            };

            embed.WithAuthor(author);

            embed.WithThumbnailUrl("https://i.imgur.com/L0K5pNh.png");

            embed.WithDescription($"" +
                                  $"You can adjust your content filter settings at any time from the **`{BotConfig.bot.cmdPrefix}settings`** menu by choosing [General Settings] > [Content Filter].");

            embed.AddField("Getting Started", "" +
                           $"Type **`{BotConfig.bot.cmdPrefix}help`** to view various commands and tutorials showing how to use Social Linker.");

            // Attempt editing the message if it hasn't been deleted by the user yet. If it has, catch the exception, send an error message, and return.
            try
            {
                // Remove all reactions from the current message.
                await message.RemoveAllReactionsAsync();

                // Edit the current active message by replacing it with the recently created embed.
                await message.ModifyAsync(x => {
                    x.Embed = embed.Build();
                });
            }
            catch (Exception ex)
            {
                await ErrorHandling.MissingMessageError((SocketTextChannel)message.Channel);

                Console.WriteLine(ex);
                return;
            }

            // Remove the menu entry from the global list.
            Global.MenuIdList.Remove(menuSession);

            // Remove the content filter entry from the global list.
            Global.ContentFilterList.Remove(filterSession);
        }
예제 #22
0
        private static async Task ProcessImage(SocketMessage arg, string downloadUrl)
        {
            RestUserMessage umsg = await arg.Channel.SendMessageAsync("Download Image...");

            WebClient wc = new WebClient();

            byte[] data = wc.DownloadData(downloadUrl);

            await umsg.ModifyAsync(msg => msg.Content = "Processing Image...");

            SearchResponse resp = await moeapi.TraceAnimeByImageAsync(data);


            umsg.ModifyAsync(msg =>
            {
                msg.Content = "";
                msg.Embed   = moeapi.ConvertResults(resp);
            });
            arg.Channel.SendFileAsync(new MemoryStream(moeapi.VideoThumbData(resp)), "thumb.mp4");
        }
예제 #23
0
        public async Task Action(Cacheable <IUserMessage, ulong> userMessage, ISocketMessageChannel channel, SocketReaction reaction)
        {
            if (this.channel.Id == channel.Id && reaction.MessageId == suggestionsMessage.Id && reaction.UserId != Program.Instance.client.CurrentUser.Id)
            {
                int old = pageNumber;
                //
                if (MojiCommand.IsLeftEnd(reaction.Emote))
                {
                    //Show the first page
                    old = 0;
                }

                if (MojiCommand.IsLeft(reaction.Emote))
                {
                    //Show the previous page
                    old -= 1;
                }

                if (MojiCommand.IsRight(reaction.Emote))
                {
                    //Show the next page
                    old += 1;
                }

                if (MojiCommand.IsRightEnd(reaction.Emote))
                {
                    //Show the last page
                    old = totalPages - 1;
                }

                if (old != pageNumber && old >= 0 && old <= totalPages)
                {
                    pageNumber = old;
                    await suggestionsMessage.ModifyAsync(VoteMessage => {
                        VoteMessage.Content = "Moves Info!!";
                        VoteMessage.Embed   = MakeEmbed();
                        return;
                    });
                }
            }
        }
예제 #24
0
        public async void Load(DiscordSocketClient client)
        {
            if (!Bot.Config.IsDevelopment)
            {
                SocketTextChannel rulesChannel = (SocketTextChannel)client.GetChannel(RULES_CHANNEL);
                try
                {
                    foreach (IMessage message in await rulesChannel.GetMessagesAsync(2).FlattenAsync())
                    {
                        if (message.Author.Id.Equals(client.CurrentUser.Id))
                        {
                            codeMessage = (RestUserMessage)message;
                            break;
                        }
                    }
                }
                catch (Exception exc)
                {
                    Trace.WriteLine(exc);
                }
                if (codeMessage == null)
                {
                    codeMessage = await rulesChannel.SendMessageAsync(getCodeMessage(getCurrentTime()));
                }
                else
                {
                    await codeMessage.ModifyAsync((messageProps) =>
                    {
                        messageProps.Content = getCodeMessage(getCurrentTime());
                    }, new RequestOptions()
                    {
                        RetryMode = RetryMode.RetryTimeouts | RetryMode.Retry502
                    });
                }

                client.UserJoined            += OnUserJoined;
                client.MessageReceived       += OnMessage;
                client.UserVoiceStateUpdated += OnVoiceUpdated;
            }
        }
예제 #25
0
        public async Task AnimateCommand(int timeout, string input)
        {
            if (input.Length > 10)
            {
                // Avoid getting rate-limited by Discord.
                await ReplyAsync("Message too long.");

                return;
            }

            char[]          charArr = input.ToCharArray();
            RestUserMessage message = await Context.Channel.SendMessageAsync("Animating...");

            foreach (char c in charArr)
            {
                // Edit message to the current char.
                await message.ModifyAsync(m => m.Content = c.ToString());

                await Task.Delay(timeout);
            }

            await message.ModifyAsync(m => m.Content = "Done :tada:.");
        }
예제 #26
0
        public async Task PingAsync()
        {
            EmbedBuilder embed = new EmbedBuilder()
                                 .WithColor(SecurityInfo.botColor)
                                 .WithDescription(":ping_pong:**Pong!**")
                                 .WithCurrentTimestamp();
            RestUserMessage msg = await Context.Channel.SendMessageAsync(embed : embed.Build());

            embed.WithDescription(":ping_pong:**Pong!**\n" +
                                  $"**Server:** {(int)(msg.Timestamp - Context.Message.Timestamp).TotalMilliseconds}ms\n" +
                                  $"**API:** {Context.Client.Latency}ms");

            await msg.ModifyAsync(x => x.Embed = embed.Build());
        }
예제 #27
0
        private async Task <IUser> RunVote(SocketGuild guild, RestTextChannel channel, int seconds, string message, IUser[] users, IUser[] randomSelection = null)
        {
            if (votes.ContainsKey(guild.Id))
            {
                votes[guild.Id] = new List <IUser>();
            }
            else
            {
                votes.Add(guild.Id, new List <IUser>());
            }

            if (!votingChannels.Contains(channel.Id))
            {
                votingChannels.Add(channel.Id);
            }

            await GuildUtils.SetAccessPermissions(channel, users, GuildUtils.CAN_SEND);

            await channel.SendMessageAsync(message);

            RestUserMessage timeMessage = await channel.SendMessageAsync(seconds + " seconds left.");

            for (int a = 0; a < seconds; a++)
            {
                await timeMessage.ModifyAsync(msg => msg.Content = (seconds - a) + " seconds left.");

                await Task.Delay(1000);
            }

            await GuildUtils.SetAccessPermissions(channel, users, GuildUtils.CANT_SEND);

            votingChannels.Remove(channel.Id);

            if (MafiaBot.DEBUG_MODE)
            {
                Console.WriteLine(votes[guild.Id].Count + ":" + (randomSelection == null) + ":" + (randomSelection == null ? -1 : randomSelection.Length));
            }

            if (votes[guild.Id].Count > 0)
            {
                return(votes[guild.Id].MostCommon());
            }
            else if (randomSelection != null)
            {
                return(randomSelection[(new Random()).Next(0, randomSelection.Length)]);
            }

            return(null);
        }
예제 #28
0
            public static async Task WaitMess(SocketReaction reaction, RestUserMessage socketMsg)
            {
                var globalAccount = Global.Client.GetUser(reaction.UserId);
                var account       = GameUserAccounts.GetAccount(globalAccount);

                var mainPage = new EmbedBuilder();

                mainPage.WithAuthor(globalAccount);
                mainPage.WithFooter($"Preparation time...");
                mainPage.WithColor(Color.DarkGreen);
                mainPage.AddField("Game is being ready", $"**Please wait until you will see emoji** {new Emoji("❌")}");


                await socketMsg.ModifyAsync(message =>
                {
                    message.Embed = mainPage.Build();
                    // This somehow can't be empty or it won't update the
                    // embed propperly sometimes... I don't know why
                    // message.Content =  Constants.InvisibleString;
                });

                await socketMsg.RemoveAllReactionsAsync();

                await socketMsg.AddReactionAsync(new Emoji("⬅"));

                await socketMsg.AddReactionAsync(new Emoji("➡"));

                await socketMsg.AddReactionAsync(new Emoji("📖"));

                await socketMsg.AddReactionAsync(new Emoji("1⃣"));

                await socketMsg.AddReactionAsync(new Emoji("2⃣"));

                await socketMsg.AddReactionAsync(new Emoji("3⃣"));

                /*await socketMsg.AddReactionAsync(new Emoji("4⃣"));
                 * await socketMsg.AddReactionAsync(new Emoji("5⃣"));
                 * await socketMsg.AddReactionAsync(new Emoji("6⃣"));
                 * await socketMsg.AddReactionAsync(new Emoji("7⃣"));
                 * await socketMsg.AddReactionAsync(new Emoji("8⃣"));
                 */
                await socketMsg.AddReactionAsync(new Emoji("❌"));

                account.OctopusFightPlayingStatus = 2;
                GameUserAccounts.SaveAccounts();

                await MainPage(reaction, socketMsg);
            }
예제 #29
0
        public static async Task ModifyEmbedMessageAsync(this RestUserMessage message, string newTitle, string newDescription, Colors?newColor = null,
                                                         string newThumbnailUrl = null, bool appendDescription = false, IEnumerable <EmbedFieldBuilder> newFields = null, bool appendFields = false)
        {
            var oldBuilder = message.Embeds.FirstOrDefault();

            if (oldBuilder == null)
            {
                return;
            }

            string description = newDescription == null ? oldBuilder.Description : (appendDescription ? (oldBuilder.Description + Environment.NewLine + newDescription) : newDescription);
            List <EmbedFieldBuilder> fields = new List <EmbedFieldBuilder>();

            if (appendFields)
            {
                foreach (var field in oldBuilder.Fields)
                {
                    fields.Add(new EmbedFieldBuilder()
                    {
                        IsInline = field.Inline,
                        Name     = field.Name,
                        Value    = field.Value
                    });
                }
            }
            if (newFields != null)
            {
                fields.AddRange(newFields);
            }

            var builder = new EmbedBuilder()
            {
                Title        = newTitle == null ? oldBuilder.Title : newTitle,
                Description  = description,
                Color        = newColor == null ? oldBuilder.Color : new Color((uint)newColor),
                ThumbnailUrl = newThumbnailUrl == null ? oldBuilder.Thumbnail?.Url : newThumbnailUrl,
                Footer       = new EmbedFooterBuilder()
                {
                    Text = oldBuilder.Footer.Value.Text
                }
            };

            builder.Fields.AddRange(fields);
            await message.ModifyAsync(f => f.Embed = builder.Build());
        }
예제 #30
0
        public async Task AnnounceRain(SocketTextChannel channel, RestUserMessage message, CancellationToken cancellationToken, long balance, int wallets, string txId)
        {
            long currentBalance = await _walletService.GetBalance(BotWallet);

            decimal missing = (BalanceThreshold - currentBalance) / 100.0M;
            string  desc    = missing > 0
                ? $"Donate {missing} TRTL to make it rain again! ```\n{BotWallet.Address}```"
                : "Wait, it is still raining?!";

            var embed = new EmbedBuilder()
                        .WithColor(new Color(114, 137, 218))
                        .WithTitle($"{balance / 100.0M} TRTL WAS GIVEN TO {wallets} TURTLES")
                        .WithUrl($"http://turtle-coin.com/?hash={txId}#blockchain_transaction")
                        .WithDescription(desc)
                        .WithThumbnailUrl(_config["rainImageUrlTRTL"])
                        .Build();

            await message.ModifyAsync(m => m.Embed = embed);
        }