コード例 #1
0
ファイル: QueryBroker.cs プロジェクト: mrkurt/mubble-old
        static void QueueQuery(Query q, string cacheKey, Cacheable current)
        {
            lock (queuedQueries)
            {
                if (!queuedQueries.ContainsKey(cacheKey))
                {
                    queuedQueries.Add(cacheKey, DateTime.Now);

                    Worker.Queue(
                        new QueryRunner(SafeRunQueryAndCache),
                        q,
                        cacheKey,
                        current
                        );
                }
            }
        }
コード例 #2
0
ファイル: QueryBroker.cs プロジェクト: mrkurt/mubble-old
 static Cacheable SafeRunQueryAndCache(Query q, string cacheKey, Cacheable current)
 {
     try
     {
         return RunQueryAndCache(q, cacheKey, current);
     }
     catch (Exception ex)
     {
         log.Error("Running background query failed", ex);
         return null;
     }
 }
コード例 #3
0
        public async Task _client_MessageUpdated(Cacheable <IMessage, ulong> messageBefore,
                                                 SocketMessage messageAfter, ISocketMessageChannel arg3)
        {
            if (messageAfter.Author.IsBot)
            {
                return;
            }
            var after = messageAfter as IUserMessage;

            if (messageAfter.Content == null)
            {
                return;
            }

            if (messageAfter.Author is SocketGuildUser userCheck && userCheck.IsMuted)
            {
                return;
            }


            var before = messageBefore.HasValue ? messageBefore.Value : null;

            if (before == null)
            {
                return;
            }
            if (arg3 == null)
            {
                return;
            }
            if (before.Content == after?.Content)
            {
                return;
            }


            var list = _commandsInMemory.CommandList;

            foreach (var t in list)
            {
                if (t.MessageUserId != messageAfter.Id)
                {
                    continue;
                }

                if (!(messageAfter is SocketUserMessage message))
                {
                    continue;
                }

                if (t.BotSocketMsg == null)
                {
                    return;
                }
                _global.TotalCommandsChanged++;
                var account = _accounts.GetAccount(messageAfter.Author);
                var context = new SocketCommandContextCustom(_client, message, _commandsInMemory, "edit", "ru");
                var argPos  = 0;


                if (message.Channel is SocketDMChannel)
                {
                    var resultTask = Task.FromResult(await _commands.ExecuteAsync(
                                                         context,
                                                         argPos,
                                                         _services));



                    await resultTask.ContinueWith(async task =>
                                                  await CommandResults(task, context));

                    return;
                }



                if (message.HasStringPrefix("*", ref argPos) || message.HasStringPrefix("*" + " ",
                                                                                        ref argPos) ||
                    message.HasMentionPrefix(_client.CurrentUser,
                                             ref argPos) ||
                    message.HasStringPrefix(account.MyPrefix + " ",
                                            ref argPos) ||
                    message.HasStringPrefix(account.MyPrefix,
                                            ref argPos))
                {
                    var resultTask = Task.FromResult(await _commands.ExecuteAsync(
                                                         context,
                                                         argPos,
                                                         _services));


                    await resultTask.ContinueWith(async task =>
                                                  await CommandResults(task, context));
                }

                return;
            }



            await HandleCommandAsync(messageAfter);
        }
コード例 #4
0
 private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
 {
     await OnReactionChanged(arg1, arg3, 1);
 }
コード例 #5
0
 private async Task reactionRemoved(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction)
 {
     if (Globals.trackables.Contains(channel.Id))
     {
         if (Globals.trackingMessage.ContainsKey(reaction.MessageId))
         {
             Dictionary <IEmote, List <(ulong, string)> > emoteList = Globals.messageEmotes[reaction.MessageId];
             if (emoteList.ContainsKey(reaction.Emote))
             {
                 Console.WriteLine("Has emote");
                 foreach (var(a, b) in emoteList[reaction.Emote])
                 {
                     if (a == reaction.UserId)
                     {
                         emoteList[reaction.Emote].Remove((a, b));
                         break;
                     }
                 }
                 if (emoteList[reaction.Emote].Count == 0)
                 {
                     emoteList.Remove(reaction.Emote);
                 }
             }
             else
             {
                 Console.WriteLine("Error: Tried to remove emote from list that is not yet listed?");
                 Console.WriteLine(reaction.Emote.Name);
             }
             string text = "**Reactions on the message above** <:kannaPeer:584921908198375444>\n";
             if (emoteList.Count == 0)
             {
                 text += "No reactions";
             }
             foreach (KeyValuePair <IEmote, List <(ulong, string)> > entry in emoteList)
             {
                 if (entry.Key is Emote emote)
                 {
                     var chnl = channel as SocketGuildChannel;
                     if (CheckEmoteInGuild(emote, chnl.Guild))
                     {
                         text += "<:" + emote.Name + ":" + emote.Id + ">";
                     }
                     else
                     {
                         text += "__" + emote.Name + "__";
                     }
                 }
                 else if (entry.Key is Emoji emoji)
                 {
                     text += emoji;
                 }
                 text += "\n";
                 foreach (var(a, b) in entry.Value)
                 {
                     text += Globals.client.GetUser(a).Username.ToString();
                     text += " at ";
                     text += b;
                     text += "\n";
                 }
                 text += "\n";
             }
             await Globals.trackingMessage[reaction.MessageId].ModifyAsync(x => x.Content = text);
         }
     }
 }
コード例 #6
0
        private async Task ReactionAdded(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
        {
            if (!message.HasValue)
            {
                await Log(LogSeverity.Debug, $"Message with id {message.Id} was not in cache.");

                return;
            }
            if (!reaction.User.IsSpecified)
            {
                await Log(LogSeverity.Debug, $"Message with id {message.Id} had invalid user.");

                return;
            }

            var msg     = message.Value;
            var iclient = (SocketClient as IDiscordClient) ?? (ShardedClient as IDiscordClient);

            if (reaction.UserId == iclient.CurrentUser.Id)
            {
                return;
            }
            if (msg.Author.Id == iclient.CurrentUser.Id &&
                reaction.UserId == (await iclient.GetApplicationInfoAsync()).Owner.Id &&
                reaction.Emote.Name == _litter.Name)
            {
                await msg.DeleteAsync();

                return;
            }

            if (Helpmsgs.TryGetValue(msg.Id, out var fhm))
            {
                if (reaction.UserId != fhm.UserId)
                {
                    var _ = msg.RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                    return;
                }

                switch (reaction.Emote.Name)
                {
                case FancyHelpMessage.SFirst:
                    await fhm.First();

                    break;

                case FancyHelpMessage.SBack:
                    await fhm.Back();

                    break;

                case FancyHelpMessage.SNext:
                    await fhm.Next();

                    break;

                case FancyHelpMessage.SLast:
                    await fhm.Last();

                    break;

                case FancyHelpMessage.SDelete:
                    await fhm.Delete();

                    break;

                default:
                    break;
                }
            }
        }
コード例 #7
0
 private async Task ReactionRemoved(Cacheable <IUserMessage, ulong> cacheMessage, ISocketMessageChannel channel, SocketReaction reaction)
 {
     //not uset yet
 }
コード例 #8
0
ファイル: DadModule.cs プロジェクト: crazyants/Volvox.Helios
 /// <summary>
 /// Callback that receives message updates on a server.
 /// </summary>
 /// <param name="messageCache"></param>
 /// <param name="socketMessage"></param>
 /// <param name="channel"></param>
 /// <returns></returns>
 private Task OnMessageUpdated(Cacheable <IMessage, ulong> messageCache,
                               SocketMessage socketMessage,
                               ISocketMessageChannel channel)
 {
     return(TryPostMessage(socketMessage));
 }
コード例 #9
0
 private async Task MessageDeleted(Cacheable <IMessage, ulong> cacheMessage, ISocketMessageChannel channel)
 {
     //not uset yet
 }
コード例 #10
0
 private async Task MessageUpdated(Cacheable <IMessage, ulong> cacheMessageBefore, SocketMessage messageAfter, ISocketMessageChannel channel)
 {
     //not uset yet
 }
コード例 #11
0
 public Task HandleMessageDeleted(Cacheable <IMessage, ulong> message, ISocketMessageChannel channel) =>
 _proxy.HandleMessageDeletedAsync(message, channel);
コード例 #12
0
 public Task HandleReactionAdded(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel,
                                 SocketReaction reaction) => _proxy.HandleReactionAddedAsync(message, channel, reaction);
コード例 #13
0
        public async Task CheckVerification(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            var tuser = _client.GetGuild(Global.SwissGuildId).GetUser(arg3.UserId);

            if (!Global.VerifyAlts && AltAccountHandler.IsAlt(tuser))
            {
                return;
            }
            if (arg2.Id == Global.VerificationChanID)
            {
                var user  = _client.GetGuild(Global.SwissGuildId).GetUser(arg3.UserId);
                var emote = new Emoji("✅");
                if (arg3.Emote.Name == emote.Name)
                {
                    if (user == null)
                    {
                        user = _client.GetGuild(Global.SwissGuildId).GetUser(arg1.Value.Author.Id);
                    }
                    if (user == null)
                    {
                        await arg2.SendMessageAsync("users not in server");

                        var msg = await arg2.GetMessageAsync(arg3.MessageId);

                        await msg.DeleteAsync();

                        FList.Remove(arg3.MessageId);
                        return;
                    }
                    string nick = "";
                    if (user.Nickname != null)
                    {
                        nick = user.Nickname;
                    }
                    SocketRole unVertRole = _client.GetGuild(Global.SwissGuildId).Roles.FirstOrDefault(x => x.Id == Global.UnverifiedRoleID);
                    if (user.Roles.Contains(unVertRole))
                    {
                        var userRole = _client.GetGuild(Global.SwissGuildId).Roles.FirstOrDefault(x => x.Id == Global.MemberRoleID);
                        await user.AddRoleAsync(userRole);

                        Console.WriteLine($"Verified user {user.Username}#{user.Discriminator}");
                        EmbedBuilder eb2 = new EmbedBuilder()
                        {
                            Title  = $"Verified {user.Mention}",
                            Color  = Color.Green,
                            Footer = new EmbedFooterBuilder()
                            {
                                IconUrl = user.GetAvatarUrl(),
                                Text    = $"{user.Username}#{user.Discriminator}"
                            },
                            Fields = new List <EmbedFieldBuilder>()
                            {
                                { new EmbedFieldBuilder()
                                  {
                                      IsInline = true,
                                      Name     = "AutoVerified?",
                                      Value    = "false"
                                  } }
                            }
                        };
                        var chan = _client.GetGuild(Global.SwissGuildId).GetTextChannel(Global.VerificationLogChanID);
                        await chan.SendMessageAsync("", false, eb2.Build());

                        await user.RemoveRoleAsync(unVertRole);

                        string       welcomeMessage = WelcomeMessageBuilder(Global.WelcomeMessage, user);
                        EmbedBuilder eb             = new EmbedBuilder()
                        {
                            Title  = $"***Welcome to Swiss001's Discord server!***",
                            Footer = new EmbedFooterBuilder()
                            {
                                IconUrl = user.GetAvatarUrl(),
                                Text    = $"{user.Username}#{user.Discriminator}"
                            },
                            Description  = welcomeMessage,
                            ThumbnailUrl = Global.WelcomeMessageURL,
                            Color        = Color.Green
                        };
                        await _client.GetGuild(Global.SwissGuildId).GetTextChannel(Global.WelcomeMessageChanID).SendMessageAsync("", false, eb.Build());

                        await user.SendMessageAsync("", false, new EmbedBuilder()
                        {
                            Title       = "***Welcome to Swiss001's Discord Server!***",
                            Description = "Welcome, we hope you read the rules, if not please watch this video https://www.youtube.com/watch?v=RFOkRDpF8dY thanks!",
                            Color       = Color.Green
                        }.Build());

                        Global.ConsoleLog($"WelcomeMessage for {user.Username}#{user.Discriminator}", ConsoleColor.Blue);
                    }
                }
            }
            else if (arg2.Id == 692909459831390268)
            {
                //rewrite man verification

                if (arg3.User.Value.IsBot)
                {
                    return;
                }
                if (FList.Keys.Contains(arg3.MessageId))
                {
                    var k    = FList[arg3.MessageId];
                    var user = _client.GetGuild(Global.SwissGuildId).GetUser(k);
                    var msg  = _client.GetGuild(Global.SwissGuildId).GetTextChannel(692909459831390268).GetMessageAsync(arg3.MessageId).Result;
                    var ch   = new Emoji("✅");
                    var ex   = new Emoji("❌");
                    if (arg3.Emote.Name == ch.Name)
                    {
                        var unVertRole = _client.GetGuild(Global.SwissGuildId).Roles.FirstOrDefault(x => x.Id == Global.UnverifiedRoleID);
                        if (user.Roles.Contains(unVertRole))
                        {
                            var userRole = _client.GetGuild(Global.SwissGuildId).Roles.FirstOrDefault(x => x.Id == Global.MemberRoleID);
                            await user.AddRoleAsync(userRole);

                            Console.WriteLine($"Verified user {user.Username}#{user.Discriminator}");
                            EmbedBuilder eb2 = new EmbedBuilder()
                            {
                                Title  = $"Verified {user.Mention}",
                                Color  = Color.Green,
                                Footer = new EmbedFooterBuilder()
                                {
                                    IconUrl = user.GetAvatarUrl(),
                                    Text    = $"{user.Username}#{user.Discriminator}"
                                },
                            };
                            var chan = _client.GetGuild(Global.SwissGuildId).GetTextChannel(Global.VerificationLogChanID);
                            await chan.SendMessageAsync("", false, eb2.Build());

                            await user.RemoveRoleAsync(unVertRole);

                            string       welcomeMessage = WelcomeMessageBuilder(Global.WelcomeMessage, user);
                            EmbedBuilder eb             = new EmbedBuilder()
                            {
                                Title  = $"***Welcome to Swiss001's Discord server!***",
                                Footer = new EmbedFooterBuilder()
                                {
                                    IconUrl = user.GetAvatarUrl(),
                                    Text    = $"{user.Username}#{user.Discriminator}"
                                },
                                Description  = welcomeMessage,
                                ThumbnailUrl = Global.WelcomeMessageURL,
                                Color        = Color.Green
                            };
                            await _client.GetGuild(Global.SwissGuildId).GetTextChannel(Global.WelcomeMessageChanID).SendMessageAsync("", false, eb.Build());

                            Global.ConsoleLog($"WelcomeMessage for {user.Username}#{user.Discriminator}", ConsoleColor.Blue);
                            await msg.DeleteAsync();

                            FList.Remove(arg3.MessageId);
                            Global.SaveAltCards();
                            await _client.GetGuild(Global.SwissGuildId).GetTextChannel(662142405377654804).SendMessageAsync($"Allowed {user.ToString()}. Moderator: {arg3.User.ToString()}");
                        }
                    }
                    if (arg3.Emote.Name == ex.Name)
                    {
                        try
                        {
                            await user.SendMessageAsync("", false, new EmbedBuilder()
                            {
                                Title       = "**You have been Stopped!**",
                                Color       = Color.Red,
                                Description = "You've been banned from **Swiss001 Official Discord Server.**",
                                Fields      = new List <EmbedFieldBuilder>()
                                {
                                    { new EmbedFieldBuilder()
                                      {
                                          Name  = "To appeal",
                                          Value = "https://neoney.xyz/swiss001/unban"
                                      } }
                                },
                            }.Build());
                        }
                        catch { }
                        await user.BanAsync(7, "Denied by Staff");

                        await msg.DeleteAsync();

                        FList.Remove(arg3.MessageId);
                        Global.SaveAltCards();
                        await _client.GetGuild(Global.SwissGuildId).GetTextChannel(692909459831390268).SendMessageAsync($"Banned {user.ToString()}. Moderator: {arg3.User.ToString()}");
                    }
                }
            }
        }
コード例 #14
0
 protected abstract Task HandleReactionAsync(
     Cacheable <IUserMessage, ulong> message,
     Cacheable <IMessageChannel, ulong> channel,
     SocketReaction reaction
     );
コード例 #15
0
 private async Task ReactionsCleared(Cacheable <IUserMessage, ulong> cacheMessage, ISocketMessageChannel channel)
 {
     //not uset yet
 }
コード例 #16
0
        private Task _client_MessageUpdated(Cacheable <IMessage, ulong> optmsg, SocketMessage imsg2, ISocketMessageChannel ch)
        {
            var _ = Task.Run(async() =>
            {
                try
                {
                    var after = imsg2 as IUserMessage;
                    if (after == null || after.IsAuthor(_client))
                    {
                        return;
                    }

                    var before = (optmsg.HasValue ? optmsg.Value : null) as IUserMessage;
                    if (before == null)
                    {
                        return;
                    }

                    var channel = ch as ITextChannel;
                    if (channel == null)
                    {
                        return;
                    }

                    if (before.Content == after.Content)
                    {
                        return;
                    }

                    if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out LogSetting logSetting) ||
                        (logSetting.MessageUpdatedId == null) ||
                        logSetting.IgnoredChannels.Any(ilc => ilc.ChannelId == channel.Id))
                    {
                        return;
                    }

                    ITextChannel logChannel;
                    if ((logChannel = await TryGetLogChannel(channel.Guild, logSetting, LogType.MessageUpdated)) == null || logChannel.Id == after.Channel.Id)
                    {
                        return;
                    }

                    var embed = new EmbedBuilder()
                                .WithOkColor()
                                .WithTitle("📝 " + GetText(logChannel.Guild, "msg_update", ((ITextChannel)after.Channel).Name))
                                .WithDescription(after.Author.ToString())
                                .AddField(efb => efb.WithName(GetText(logChannel.Guild, "old_msg")).WithValue(string.IsNullOrWhiteSpace(before.Content) ? "-" : before.Resolve(userHandling: TagHandling.FullName)).WithIsInline(false))
                                .AddField(efb => efb.WithName(GetText(logChannel.Guild, "new_msg")).WithValue(string.IsNullOrWhiteSpace(after.Content) ? "-" : after.Resolve(userHandling: TagHandling.FullName)).WithIsInline(false))
                                .AddField(efb => efb.WithName("Id").WithValue(after.Id.ToString()).WithIsInline(false))
                                .WithFooter(efb => efb.WithText(CurrentTime(channel.Guild)));

                    await logChannel.EmbedAsync(embed).ConfigureAwait(false);
                }
                catch
                {
                    // ignored
                }
            });

            return(Task.CompletedTask);
        }
コード例 #17
0
        private void Program_OnEmojiReactionAdded(Cacheable <IUserMessage, ulong> arg1, Cacheable <IMessageChannel, ulong> arg2, SocketReaction arg3)
        {
            if (arg3.Emote.Name == CancelEmote.Name)
            {
                var timer = Config.Data.timers.FirstOrDefault(x => x.MessageId == arg1.Id);
                if (timer != null && arg3.User.Value.Id == timer.AuthorId)
                {
                    var eventMessage = timer.GetMessage();

                    eventMessage.ModifyAsync(m => m.Content = $"```fix\n{timer.EventName} was cancelled :c```");
                    Config.Data.timers.Remove(timer);
                }
            }
        }
コード例 #18
0
 private Task HandleReactionRemovedAsync(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
 {
     throw new NotImplementedException();
 }
コード例 #19
0
 public async Task HandleUpdate(Cacheable <IMessage, ulong> cacheMsg, SocketMessage message, ISocketMessageChannel channel)
 {
     await HandleCommand(message);
 }
コード例 #20
0
        private async Task HandleReactionAsync(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction)
        {
            var message = cache.Value;

            if (!(message != null && message.Author.Id == _client.CurrentUser.Id))
            {
                return;
            }

            if (reaction.User.Value.IsBot)
            {
                return;
            }

            var msgEmbed = message.Embeds.GetEnumerator();

            msgEmbed.MoveNext();

            Console.WriteLine(msgEmbed.Current.Title);

            if (!(msgEmbed.Current.Title.StartsWith("Recipe Results for")))
            {
                return;
            }

            var linkString = msgEmbed.Current.Description.Split("\n");

            RecipeModel recipe = null;

            switch (reaction.Emote.Name)
            {
            case "1⃣":
                if (linkString.Length >= 2)
                {
                    recipe = await _recipeService.GetRecipeFromPageAsync(url : Regex.Match(linkString[1], @"\(([^)]*)\)").Groups[1].Value);
                }
                break;

            case "2⃣":
                if (linkString.Length >= 3)
                {
                    recipe = await _recipeService.GetRecipeFromPageAsync(url : Regex.Match(linkString[2], @"\(([^)]*)\)").Groups[1].Value);
                }
                break;

            case "3⃣":
                if (linkString.Length >= 4)
                {
                    recipe = await _recipeService.GetRecipeFromPageAsync(url : Regex.Match(linkString[3], @"\(([^)]*)\)").Groups[1].Value);
                }
                break;

            case "4⃣":
                if (linkString.Length >= 5)
                {
                    recipe = await _recipeService.GetRecipeFromPageAsync(url : Regex.Match(linkString[4], @"\(([^)]*)\)").Groups[1].Value);
                }
                break;

            case "5⃣":
                if (linkString.Length >= 6)
                {
                    recipe = await _recipeService.GetRecipeFromPageAsync(url : Regex.Match(linkString[5], @"\(([^)]*)\)").Groups[1].Value);
                }
                break;

            default:
                return;
            }

            if (recipe == null)
            {
                return;
            }

            var embed = new EmbedBuilder
            {
                Title    = recipe.Name,
                Url      = recipe.Link,
                ImageUrl = recipe.Img,
                Footer   = new EmbedFooterBuilder
                {
                    Text = $"Calories: {recipe.Calories.ToString()}  Time: {recipe.Time}"
                },
                Description = ParseIngredients(recipe.Ingredients),
                Fields      = ParseDirections(recipe.Directions)
            };

            await channel.SendMessageAsync(null, false, embed.Build());
        }
コード例 #21
0
        public async Task HandleDelete(Cacheable <IMessage, ulong> message, ISocketMessageChannel channel)
        {
            IMessage msg = await message.GetOrDownloadAsync();

            await botLogChannel.SendMessageAsync($"The deleted message was from {msg.Author} and was: ```{msg.Content}```");
        }
コード例 #22
0
 private Task MessageDeleted(Cacheable <IMessage, ulong> message, ISocketMessageChannel channel)
 {
     return(Task.FromResult(Helpmsgs.TryRemove(message.Id, out var _)));
 }
コード例 #23
0
 public Task OnMessageDeleted(Cacheable <IMessage, ulong> message, ISocketMessageChannel channel)
 {
     return(Task.CompletedTask);
 }
コード例 #24
0
        public async static Task RPSProcessor(Cacheable <IUserMessage, ulong> cachedEntity, ISocketMessageChannel channel, SocketReaction reaction)
        {
            var message      = (SocketUserMessage)cachedEntity.Value;
            var reactingUser = (SocketUser)reaction.User;

            if (reactingUser.IsBot || message == null)
            {
                return;
            }

            if (message.Content.StartsWith("Game over: "))
            {
                if (message.Reactions.ContainsKey(new Emoji("❗")))
                {
                    await message.ModifyAsync(x => x.Content = "Choose Rock, Paper, or Scissors!");

                    await message.RemoveAllReactionsAsync();

                    IEmote[] rpsReactions = new IEmote[]
                    {
                        new Emoji("🪨"),
                        new Emoji("🧻"),
                        new Emoji("✂️"),
                        new Emoji("❗"),
                    };

                    await message.AddReactionsAsync(rpsReactions);
                }
            }

            if (message.Content == "Choose Rock, Paper, or Scissors!")
            {
                var    reactions     = message.Reactions;
                IEmote usersReaction = null;

                foreach (var r in reactions)
                {
                    if (r.Value.ReactionCount > 1)
                    {
                        usersReaction = r.Key;
                    }
                }

                ThrowResult playerThrow = (ThrowResult)(-1);
                if (usersReaction.Name == "🪨")
                {
                    playerThrow = ThrowResult.Rock;
                }
                else if (usersReaction.Name == "🧻")
                {
                    playerThrow = ThrowResult.Paper;
                }
                else if (usersReaction.Name == "✂️")
                {
                    playerThrow = ThrowResult.Scissors;
                }
                else
                {
                    return;
                }

                ThrowResult computerThrow = EnumHelper.RandomEnumValue <ThrowResult>();
                var         winner        = DetermineWinner(computerThrow, playerThrow);

                string outputMessage = "Game over: ";
                if (winner == Winner.Bot)
                {
                    outputMessage += $"{ message.Author.Mention } *won* by throwing { GetEmoji(computerThrow) } against { usersReaction.Name}!";
                }
                else if (winner == Winner.Player)
                {
                    outputMessage += $"{ reactingUser.Mention } *won* by throwing { usersReaction.Name} against { GetEmoji(computerThrow) }!";
                }
                else
                {
                    outputMessage += $"It's a tie! { GetEmoji(computerThrow)} vs { GetEmoji(playerThrow) }!";
                }

                await message.ModifyAsync(msg => msg.Content = outputMessage);
            }
        }
コード例 #25
0
 public Task OnMessageUpdated(Cacheable <IMessage, ulong> messageBeforeUpdate, SocketMessage messageAfterUpdate, ISocketMessageChannel channel)
 {
     return(Task.CompletedTask);
 }
コード例 #26
0
        private async Task HandleEventAsync(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction, RestUserMessage message, bool reactionAdded)
        {
            var           em     = message.Embeds.First();
            var           fields = em.Fields;
            List <string> att    = new List <string>();
            List <string> nAtt   = new List <string>();

            // Iterate over fields and grab data needed
            int    maxParticipants = 0;
            string dateTime        = "";

            for (int i = 0; i < fields.Count(); i++)
            {
                if (fields[i].Name == "When?")
                {
                    dateTime = fields[i].Value;
                }
                if (fields[i].Name == "Max Participants")
                {
                    maxParticipants = Int32.Parse(fields[i].Value);
                }
            }

            // Refresh both 'Attending' and 'Not attending' lists
            var attending = message.GetReactionUsersAsync(new Emoji("\u2705"), 100);

            attending.ForEach(users => {
                for (int i = 0; i < users.Count(); i++)
                {
                    if (!users.ElementAt(i).IsBot)
                    {
                        att.Add(users.ElementAt(i).Mention);
                    }
                }
            });
            var notAttending = message.GetReactionUsersAsync(new Emoji("\u274C"), 100);

            notAttending.ForEach(users => {
                for (int i = 0; i < users.Count(); i++)
                {
                    if (!users.ElementAt(i).IsBot)
                    {
                        nAtt.Add(users.ElementAt(i).Mention);
                    }
                }
            });

            // If reaction was added
            if (reactionAdded)
            {
                // Check if max participants have been reached
                if (att.Count > maxParticipants && maxParticipants != 0)
                {
                    await message.RemoveReactionAsync(new Emoji("\u2705"), reaction.User.Value);

                    return;
                }

                // Check for and handle double reactions
                if (reaction.Emote.Equals(new Emoji("\u2705")))
                {
                    foreach (string n in nAtt)
                    {
                        if (n == reaction.User.Value.Mention)
                        {
                            await message.RemoveReactionAsync(new Emoji("\u274C"), reaction.User.Value);

                            return;
                        }
                    }
                }
                if (reaction.Emote.Equals(new Emoji("\u274C")))
                {
                    foreach (string n in att)
                    {
                        if (n == reaction.User.Value.Mention)
                        {
                            await message.RemoveReactionAsync(new Emoji("\u2705"), reaction.User.Value);

                            return;
                        }
                    }
                }
            }

            var embed = await EmbedHandler.UpdateEventEmbed(em.Title, em.Description, maxParticipants, dateTime, em.Footer.Value.ToString(), att, nAtt);

            await message.ModifyAsync(q => {
                q.Embed = embed;
            });
        }
コード例 #27
0
        /// <summary>
        /// Sends mod log messages if configured, and deletes any corresponding bot response.
        /// </summary>
        private async Task HandleMessageDeleted(Cacheable <IMessage, ulong> cachedMessage, ISocketMessageChannel channel)
        {
            var msg = this.botResponsesCache.Remove(cachedMessage.Id);

            try
            {
                await msg?.DeleteAsync();
            }
            catch (Exception)
            {
                // ignore, don't care if we can't delete our own message
            }

            if (cachedMessage.HasValue && channel is IGuildChannel guildChannel)
            {
                var message     = cachedMessage.Value;
                var textChannel = guildChannel as ITextChannel;
                var guild       = guildChannel.Guild as SocketGuild;
                var settings    = SettingsConfig.GetSettings(guildChannel.GuildId);

                if (settings.HasFlag(ModOptions.Mod_LogDelete) && guildChannel.Id != settings.Mod_LogId && !message.Author.IsBot &&
                    this.Client.GetChannel(settings.Mod_LogId) is ITextChannel modLogChannel && modLogChannel.GetCurrentUserPermissions().SendMessages)
                {
                    string delText = "";

                    if (settings.TriggersCensor(message.Content, out _))
                    {
                        delText = "```Word Censor Triggered```";
                    }

                    var deletedContent = message.Content.Replace("@everyone", "@every\x200Bone").Replace("@here", "@he\x200Bre");
                    if (message.MentionedUserIds.Count > 0)
                    {
                        var guildUsers = guild.Users;

                        foreach (var userId in message.MentionedUserIds)
                        {
                            var guildUser = guildUsers.FirstOrDefault(u => u.Id == userId);
                            if (guildUser != null)
                            {
                                deletedContent = deletedContent.Replace($"{userId}", guildUser.Nickname ?? guildUser.Username);
                            }
                        }
                    }

                    if (message.MentionedRoleIds.Count > 0)
                    {
                        var guildRoles = guild.Roles;

                        foreach (var roleId in message.MentionedRoleIds)
                        {
                            var guildRole = guildRoles.FirstOrDefault(u => u.Id == roleId);
                            deletedContent = deletedContent.Replace($"{roleId}", guildRole.Name);
                        }
                    }

                    delText += $"**{message.Author.Username}#{message.Author.Discriminator}** deleted in {textChannel.Mention}: {deletedContent}";

                    // Include attachment URLs, if applicable
                    if (message.Attachments?.Count > 0)
                    {
                        delText += " " + string.Join(" ", message.Attachments.Select(a => a.Url));
                    }

                    this.BatchSendMessageAsync(modLogChannel, delText.SubstringUpTo(Discord.DiscordConfig.MaxMessageSize));
                }
            }
        }
コード例 #28
0
ファイル: QueryBroker.cs プロジェクト: mrkurt/mubble-old
        static Cacheable RunQueryAndCache(Query q, string cacheKey, Cacheable current)
        {
            ContentList results = Content.Query(q);
            Cacheable updated = new Cacheable(results, DateTime.Now);

            if (current == null || current.Results != null || current.Results.Count < 2 || results.Count > 0)
            {
                CacheBroker.Set(cacheKey, updated, Config.Caching.Current.GetSlidingExpiration());
                if (CachedQueryChanged != null && (current == null || !results.Equals(current.Results)))
                {
                    CachedQueryChanged(cacheKey);

                }
            }

            lock (queuedQueries)
            {
                queuedQueries.Remove(cacheKey);
            }

            return updated;
        }
コード例 #29
0
        protected override async Task ProcessReaction(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction)
        {
            try
            {
                if (reaction.User.Value.IsBot)
                {
                    return;
                }
                if (channel.Id != Teams[Team.A].teamChannel.Id && channel.Id != Teams[Team.B].teamChannel.Id)
                {
                    return;
                }
                if (reaction.Emote.Name == "Fight_A")
                {
                    _ = AddPlayer(reaction, Team.A);
                    return;
                }
                if (reaction.Emote.Name == "Fight_B")
                {
                    _ = AddPlayer(reaction, Team.B);
                    return;
                }
                else if (reaction.Emote.Name == "Battle")
                {
                    _ = StartBattle();
                    return;
                }
                if (!Battle.isActive)
                {
                    return;
                }

                Teams.Values.ToList().ForEach(async V =>
                {
                    var StatusMessage  = V.StatusMessage;
                    var PlayerMessages = V.PlayerMessages;
                    var EnemyMessage   = V.EnemyMessage;
                    var SummonsMessage = V.SummonsMessage;
                    if (channel.Id != V.teamChannel.Id)
                    {
                        return;
                    }
                    IUserMessage c = null;
                    if (StatusMessage.Id == reaction.MessageId)
                    {
                        c = StatusMessage;
                    }
                    if (EnemyMessage.Id == reaction.MessageId)
                    {
                        c = EnemyMessage;
                    }
                    if (SummonsMessage.Id == reaction.MessageId)
                    {
                        c = SummonsMessage;
                    }
                    if (PlayerMessages.Keys.Any(k => k.Id == reaction.MessageId))
                    {
                        c = PlayerMessages.Keys.Where(k => k.Id == reaction.MessageId).First();
                    }

                    if (c == null)
                    {
                        c = (IUserMessage)await channel.GetMessageAsync(reaction.MessageId);
                        _ = c.RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                        Console.WriteLine("No matching Message for User found.");
                        return;
                    }

                    if (!Battle.isActive)
                    {
                        _ = c.RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                        Console.WriteLine("Battle not active.");
                        return;
                    }

                    if (Battle.turnActive)
                    {
                        _ = c.RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                        Console.WriteLine("Not so fast");
                        return;
                    }

                    if (reaction.Emote.Name == "🔄")
                    {
                        await c.RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                        autoTurn.Stop();
                        Task.WaitAll(PlayerMessages.Select(m => m.Key.RemoveAllReactionsAsync()).Append(EnemyMessage.RemoveAllReactionsAsync()).ToArray());

                        _ = WriteBattleInit();
                        autoTurn.Start();
                        return;
                    }

                    if (reaction.Emote.Name == "⏸")
                    {
                        autoTurn.Stop();
                        return;
                    }

                    if (reaction.Emote.Name == "▶")
                    {
                        autoTurn.Start();
                        return;
                    }

                    if (reaction.Emote.Name == "⏩")
                    {
                        _ = ProcessTurn(true);
                        return;
                    }

                    var curPlayer = PlayerMessages.Values.Where(p => p.Id == reaction.User.Value.Id).FirstOrDefault();
                    if (curPlayer == null)
                    {
                        _ = c.RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                        Console.WriteLine("Player not in this room.");
                        return;
                    }
                    var correctID = PlayerMessages.Keys.Where(key => PlayerMessages[key].Id == curPlayer.Id).First().Id;

                    if (!numberEmotes.Contains(reaction.Emote.Name))
                    {
                        if (reaction.MessageId != EnemyMessage.Id && reaction.MessageId != correctID)
                        {
                        }
                    }

                    if (!curPlayer.Select(reaction.Emote))
                    {
                        _ = c.RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                        Console.WriteLine("Couldn't select that move.");
                        return;
                    }
                    reactions.Add(reaction);
                });

                _ = ProcessTurn(forced: false);
            }
            catch (Exception e)
            {
                Console.WriteLine("Colosso Turn Processing Error: " + e.Message);
                File.WriteAllText($"Logs/Crashes/Error_{DateTime.Now.Date}.log", e.Message);
            }
            await Task.CompletedTask;
        }
コード例 #30
0
        private async Task OnReactionadd(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel ch, SocketReaction reac)
        {
            Account acc = Global.AccountList.Find(a => a.DiscordID == reac.UserId);

            if (!(acc == null))
            {
                if (Global.MsgGrade.ContainsKey(reac.MessageId))
                {
                    var   key  = reac.MessageId;
                    Grade grde = Global.MsgGrade[key];

                    if (grde.obs == null)
                    {
                        if (!reac.Emote.Name.Equals("❌"))
                        {
                            grde.atv = Global.AtvsEmojis[reac.Emote.Name];
                            Global.MsgGrade.Remove(key);
                            EmbedBuilder embed = new EmbedBuilder();
                            embed.WithColor(40, 200, 150);
                            embed.WithTitle("Algo a declarar?");
                            embed.WithDescription("Adicione Observações em sua Grade!\n Me envie uma mensagem com as observações que deseja adicionar a grade, se não quiser nenhuma envie **0**\n Lembre-se de mencionar armas, Poder e outros atributos que considera importante para o sucesso da missão!");
                            RestUserMessage x = await ch.SendMessageAsync("", false, embed.Build());

                            Global.MsgGrade.Add(x.Id, grde);
                            acc.EstadodeAcao = Flag.escrevendo;
                            acc.lastmsg      = x.Id;
                            grde.Msg         = x.Id;
                        }
                        else
                        {
                            grde.stat = Status.Cancelada;
                            EmbedBuilder embed = new EmbedBuilder();
                            embed.WithColor(250, 0, 0);
                            embed.WithTitle("Grade Cancelada");

                            RestUserMessage x = await ch.SendMessageAsync("", false, embed.Build());
                        }
                    }
                    else if (grde.MaxMembers != 0)

                    {
                        Grade g = Global.MsgGrade[reac.MessageId];
                        if (reac.Emote.Name.Equals("❌"))
                        {
                            if (g.Principais.Find(a => a.DiscordID == acc.DiscordID) != null)
                            {
                                if (acc.DiscordID == g.Organizador.DiscordID)
                                {
                                    g.Organizador.EstadodeAcao = Flag.deletando_grade;
                                    acc.EstadodeAcao           = Flag.deletando_grade;
                                    g.stat = Status.Cancelada;
                                    EmbedBuilder embed = new EmbedBuilder();
                                    embed.WithColor(250, 0, 0);
                                    embed.WithTitle("Está desistindo??");
                                    embed.WithDescription($"\n Por que essa grade foi cancelada?: {g.atv} - {g.time}");

                                    var u = await ch.GetUserAsync(reac.UserId);

                                    await UserExtensions.SendMessageAsync(u, "", false, embed.Build());
                                }
                                else
                                {
                                    g.Principais.RemoveAll(A => A.DiscordID == acc.DiscordID);
                                    RestUserMessage x = await reac.Channel.SendMessageAsync("\n Pressione AQUI para poder Reagir \n", false, Global.EmbedGrade(g).Build());

                                    Global.MsgGrade.Remove(g.Organizador.lastmsg);
                                    Global.MsgGrade.Add(x.Id, g);
                                    g.Organizador.lastmsg = x.Id;
                                    g.Msg = x.Id;
                                }
                            }
                            if (g.Reserva.Find(a => a.DiscordID == acc.DiscordID) != null)
                            {
                                g.Reserva.RemoveAll(A => A.DiscordID == acc.DiscordID);
                                RestUserMessage x = await reac.Channel.SendMessageAsync("\n Pressione AQUI para poder Reagir \n", false, Global.EmbedGrade(g).Build());

                                Global.MsgGrade.Remove(g.Organizador.lastmsg);
                                Global.MsgGrade.Add(x.Id, g);
                                g.Organizador.lastmsg = x.Id;
                                g.Msg = x.Id;
                            }
                        }
                        else if (reac.Emote.Name.Equals("👋"))
                        {
                            if (g.Reserva.Find(a => a.DiscordID == acc.DiscordID) == null && g.Principais.Find(a => a.DiscordID == acc.DiscordID) == null)
                            {
                                g.Reserva.Add(acc);
                                RestUserMessage x = await reac.Channel.SendMessageAsync("\n Pressione AQUI para poder Reagir \n", false, Global.EmbedGrade(g).Build());

                                Global.MsgGrade.Remove(g.Organizador.lastmsg);
                                Global.MsgGrade.Add(x.Id, g);
                                g.Organizador.lastmsg = x.Id;
                                g.Msg = x.Id;
                            }
                        }
                        else if (g.Principais.Count <= g.MaxMembers)
                        {
                            if (g.Principais.Find(a => a.DiscordID == acc.DiscordID) == null && g.Reserva.Find(a => a.DiscordID == acc.DiscordID) == null)
                            {
                                g.Principais.Add(acc);
                                RestUserMessage x = await reac.Channel.SendMessageAsync("\n Pressione AQUI para poder Reagir \n", false, Global.EmbedGrade(g).Build());

                                Global.MsgGrade.Remove(g.Organizador.lastmsg);
                                Global.MsgGrade.Add(x.Id, g);
                                g.Organizador.lastmsg = x.Id;
                                g.Msg = x.Id;
                            }
                        }
                    }
                }
            }
        }
コード例 #31
0
 private Task OnReactionRemoved(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
 {
     OnPollReactionChanged(message, reaction, false);
     return(Task.CompletedTask);
 }
コード例 #32
0
 protected abstract Task HandleMessageDeleteAsync(
     Cacheable <IMessage, ulong> message,
     Cacheable <IMessageChannel, ulong> channel
     );
コード例 #33
0
 private async Task DiscordClient_ReactionAddedAsync(Cacheable <IUserMessage, ulong> cachedMessage, ISocketMessageChannel channel, SocketReaction reaction)
 {
     await AddOrRemoveRoleAsync(AddOrRemove.Add, cachedMessage, channel, reaction).ConfigureAwait(false);
 }