Пример #1
0
        private async Task EnableLogger()
        {
            _channel = (ISocketMessageChannel)_discord?.GetChannel(_channelId);

            foreach (var message in _preloadMessages)
            {
                await _channel?.SendMessageAsync(message);
            }
        }
Пример #2
0
        public async Task SendMessage(string message)
        {
            if (bool.Parse(_settingsKeeper.GetSetting("EnableDiscordBot").Value))
            {
                await Connect();

                var channel = _discordSocketClient?.GetChannel(ulong.Parse(_settingsKeeper.GetSetting("DiscordChannelId").Value)) as SocketTextChannel;
                channel?.SendMessageAsync(message);
            }
        }
Пример #3
0
        public static async Task ChangeGame(DiscordSocketClient _client, SocketMessage message, bool DeleteMessage = true) // Changes game (name) of a lobby. 80 Character max.
        {
            if (DeleteMessage)
            {
                await message.DeleteAsync();
            }
            ulong channel = (message.Channel as SocketTextChannel).CategoryId.Value;

            if (message.Content.Split(' ').Count() > 2)
            {
                var del = await message.Channel.SendMessageAsync($"A lobby name may not have spaces."); await Task.Delay(5000); await del.DeleteAsync(); return;
            }
            if (message.Content.Split(' ')[1].Length >= 80)
            {
                var del = await message.Channel.SendMessageAsync($"Game name is 80 characters max. \nWhat game even has such a long name?"); await Task.Delay(5000); await del.DeleteAsync(); return;
            }
            if (!message.Channel.Name.ToLower().EndsWith("lb"))
            {
                var del = await message.Channel.SendMessageAsync($"This command is only usable within a lobby."); await Task.Delay(5000); await del.DeleteAsync(); return;
            }
            foreach (var lobby in List)
            {
                if (lobby.CategoryId == channel)
                {
                    var end = lobby;
                    if (!(lobby.OwnerId == message.Author.Id))
                    {
                        var del = await message.Channel.SendMessageAsync("You must be the lobby owner to use this command."); await Task.Delay(5000); await del.DeleteAsync(); return;
                    }
                    var cc = (message.Author as SocketGuildUser).Guild.Channels.Where(x => x.CategoryId == lobby.CategoryId);
                    var ct = _client.GetChannel(message.Channel.Id);
                    var cv = _client.GetChannel(message.Channel.Id);
                    if (message.Content.Split(' ')[1].Contains("text") || message.Content.Split(' ')[1].Contains("voice"))
                    {
                        var del = await message.Channel.SendMessageAsync("Sorry, but games cannot contain the phrase Text or Voice."); await Task.Delay(5000); await del.DeleteAsync(); return;
                    }
                    foreach (var cnl in cc)
                    {
                        if (cnl.Name.ToLower().Contains("text"))
                        {
                            ct = cnl;
                        }
                        else if (cnl.Name.ToLower().Contains("voice"))
                        {
                            cv = cnl;
                        }
                    }
                    int index = List.FindIndex(prm => lobby.Equals(prm));
                    end.Game = message.Content.Split(' ')[1];
                    try
                    {
                        await(ct as SocketTextChannel).ModifyAsync(x => { x.Name = message.Content.Split(' ')[1] + " Voice Channel LB"; });
                        await(cv as SocketVoiceChannel).ModifyAsync(x => { x.Name = message.Content.Split(' ')[1] + " Text Channel LB"; });
                    }
                    catch (Exception)
                    {
                        var del = await message.Channel.SendMessageAsync("Discord places a rate limit on changing channel names. \n\nPlease wait awhile to use this command again."); await Task.Delay(5000); await del.DeleteAsync(); return;
                    }
                    List[index] = end;
                    break;
                }
            }
        }
Пример #4
0
        public static void SendMessage(ulong channelId, EmbedBuilder embed)
        {
            var channel = _client.GetChannel(channelId) as SocketTextChannel;

            channel.SendMessageAsync("", false, embed.WithAuthor(_client.CurrentUser).Build());
        }
Пример #5
0
 // converts stored IDs from database into ulongs (mongo can't store ulong ha ha) and use them to
 // assign our discord objects
 public void SetServerDiscordObjects(DbDiscordServer server)
 {
     server.DiscordServerObject = _discord.GetGuild(Convert.ToUInt64(server.ServerId));
     server.ConfigChannel       = _discord.GetChannel(Convert.ToUInt64(server.ConfigChannelId)) as ITextChannel;
     server.ReminderChannel     = _discord.GetChannel(Convert.ToUInt64(server.ReminderChannelId)) as ITextChannel;
 }
Пример #6
0
        public async Task HandleStreamEvent(string username, Event streamEvents, Guild[] guilds)
        {
            _logger.LogDebug("Logging {username} to {guilds}", username, guilds);
            if (!_messageCache.ContainsKey(username))
            {
                _messageCache.Add(username, new List <RestUserMessage>());
            }

            try
            {
                if (streamEvents.Data.Length == 0)
                {
                    // Offline
                    // await channel.SendMessageAsync("Stream went offline");

                    // Delete message
                    var messages = _messageCache[username];
                    messages.ForEach(async message => await message.DeleteAsync());
                    messages.Clear();

                    var vodGuilds = guilds.Where(guild => guild.EnableVods).ToList();

                    if (vodGuilds.Count == 0)
                    {
                        return;
                    }
                    var vod = (await _twitch.GetVods(username)).Data.FirstOrDefault();
                    if (vod == null)
                    {
                        return;
                    }
                    var embed = await CreateVodEmbed(vod);

                    foreach (var guild in vodGuilds)
                    {
                        if (guild.VodChannelId <= 0)
                        {
                            continue;
                        }
                        var channel = (SocketTextChannel)_client.GetChannel(guild.VodChannelId);
                        await channel.SendMessageAsync(embed : embed);
                    }
                }
                else
                {
                    var streamEvent = streamEvents.Data[0];
                    var messages    = _messageCache[username];
                    var gameName    = await _twitch.GetGameName(streamEvent.GameId);

                    if (messages.Count == 0)
                    {
                        // Streamer just went live
                        foreach (var guild in guilds)
                        {
                            var channelId = guild.StreamChannelId;
                            var roleId    = guild.AnnounceRoleId;
                            if (channelId == 0)
                            {
                                continue;
                            }
                            var    channel = (SocketTextChannel)_client.GetChannel(channelId);
                            string mention = null;
                            if (roleId > 0)
                            {
                                mention = $"<@&{roleId}>";
                            }
                            var message = await channel.SendMessageAsync(text : mention, embed : await CreateStreamEmbed(streamEvent));

                            messages.Add(message);
                        }
                    }
                    else
                    {
                        // Stream title changed OR game changed
                        var embed = await CreateStreamEmbed(streamEvent);

                        messages.ForEach(async message =>
                        {
                            await message.ModifyAsync(prop =>
                            {
                                prop.Embed = embed;
                            });
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "HandleStreamEvent error");
            }
        }
Пример #7
0
        private void StartAutomaticNewsPosting()
        {
            if (_autoModeCTS != null)
            {
                return;
            }

            _autoModeCTS = new CancellationTokenSource();
            Task autoTask = Task.Run(async() =>
            {
                using IDisposable context           = _log.UseSource("Elite CGs");
                CancellationToken cancellationToken = _autoModeCTS.Token;
                // wait 5 seconds to let the client get connection state in check
                await Task.Delay(5 * 1000, cancellationToken).ConfigureAwait(false);
                _log.LogDebug("Starting automatic ED CG checker");
                DateTime _lastRetrievalTime = DateTime.MinValue;
                try
                {
                    while (!cancellationToken.IsCancellationRequested)
                    {
                        if (!this._enabled)
                        {
                            _log.LogWarning("Inara credentials missing. Elite Dangerous Community Goals feature will be disabled");
                            return;
                        }

                        TimeSpan nextUpdateIn = (_lastRetrievalTime + _options.CurrentValue.AutoNewsInterval) - DateTime.UtcNow;
                        // if still waiting, await time, and repeat iteration
                        if (nextUpdateIn > TimeSpan.Zero)
                        {
                            _log.LogTrace("Next update in: {TimeRemaining}", nextUpdateIn);
                            // this will not reflect on updates to options monitor, but that's ok
                            await Task.Delay(nextUpdateIn, cancellationToken).ConfigureAwait(false);
                            continue;
                        }

                        CommunityGoalsOptions options = _options.CurrentValue;

                        // get guild channel
                        if (!(_client.GetChannel(options.AutoNewsChannelID) is SocketTextChannel guildChannel))
                        {
                            throw new InvalidOperationException($"Channel {options.AutoNewsChannelID} is not a valid guild text channel.");
                        }

                        // retrieve CG data, take only new or finished ones, and then update cache
                        IEnumerable <CommunityGoal> allCGs         = await QueryCommunityGoalsAsync(cancellationToken).ConfigureAwait(false);
                        IList <CommunityGoal> newOrJustFinishedCGs = new List <CommunityGoal>(allCGs.Count());
                        foreach (CommunityGoal cg in allCGs)
                        {
                            CommunityGoal historyCg = await _cgHistoryStore.GetAsync(cg.ID, cancellationToken).ConfigureAwait(false);
                            if (historyCg == null || historyCg.IsCompleted != cg.IsCompleted)
                            {
                                newOrJustFinishedCGs.Add(cg);
                                await _cgHistoryStore.SetAsync(cg, cancellationToken).ConfigureAwait(false);
                            }
                        }
                        _log.LogTrace("New or just finished CGs count: {Count}", newOrJustFinishedCGs.Count);

                        // post all CGs
                        _log.LogTrace("Sending CGs");
                        foreach (CommunityGoal cg in newOrJustFinishedCGs)
                        {
                            await guildChannel.SendMessageAsync(null, false, CommunityGoalToEmbed(cg).Build(), cancellationToken).ConfigureAwait(false);
                        }
                        _lastRetrievalTime = DateTime.UtcNow;
                    }
                }
                catch (OperationCanceledException) { }
                catch (Exception ex) when(ex.LogAsError(_log, "Error occured in automatic ED CG checker loop"))
                {
                }
                finally
                {
                    _log.LogDebug("Stopping automatic ED CG checker");
                    // clear CTS on exiting if it wasn't cleared yet
                    if (_autoModeCTS?.Token == cancellationToken)
                    {
                        _autoModeCTS = null;
                    }
                }
            }, _autoModeCTS.Token);
        }
Пример #8
0
        public TimerService(DiscordSocketClient client)
        {
            _timer = new Timer(async _ =>
            {
                try
                {
                    //First filter out any servers which do not appear in the bot's guild list (ie. They removed the bot from the server)
                    AcceptedServers = client.Guilds.Where(x => AcceptedServers.Contains(x.Id)).Select(x => x.Id)
                                      .ToList();
                    var newlist = AcceptedServers.ToList();
                    var gcon    = Tokens.Load().SupportServer;
                    //Randomly Shuffle in order to provide a level of randomness in which servers get shared where. We also ensure that newlist isn't being modified during the loop by casting it to a second list.
                    foreach (var guildid in newlist.ToList().OrderBy(x => rndshuffle.Next()))
                    {
                        try
                        {
                            //Try to get the server's saved config
                            var guildobj = GuildConfig.GetServer(client.GetGuild(guildid));
                            //Filter out servers which are either banned or do not use the partner program
                            if (!guildobj.PartnerSetup.IsPartner || guildobj.PartnerSetup.banned)
                            {
                                continue;
                            }
                            //Ensure that the partner channel still exists
                            if (client.GetChannel(guildobj.PartnerSetup.PartherChannel) is IMessageChannel channel)
                            {
                                try
                                {
                                    //make sure we filter out the current server in the random list so that servers dont receive their own partner message
                                    var newitems = newlist.Where(x => x != guildid).ToList();
                                    //next select a random server from the previous list to share
                                    var newitem = newitems[new Random().Next(0, newitems.Count)];

                                    var selectedguild = GuildConfig.GetServer(client.GetGuild(newitem))
                                                        .PartnerSetup;
                                    //ensure the selected guild is not banned
                                    if (selectedguild.banned)
                                    {
                                        continue;
                                    }
                                    //also ensure that the selected guild is using the partner channel, it is a legitimate channel and their message isn't empty
                                    if (!selectedguild.IsPartner ||
                                        !(client.GetChannel(selectedguild.PartherChannel) is IGuildChannel
                                          otherchannel) || selectedguild.Message == null)
                                    {
                                        continue;
                                    }
                                    //In order to filter out people trying to cheat the systen, we filter out servers where less than 90% of users can actually see the channel
                                    if ((decimal)((SocketTextChannel)otherchannel).Users.Count /
                                        ((SocketGuild)otherchannel.Guild).Users.Count * 100 < 90)
                                    {
                                        //Ideally we notify the infringing guild that they are being ignored in the partner program until they change their settings.
                                        await((ITextChannel)otherchannel).SendMessageAsync(
                                            $"{(decimal) ((SocketTextChannel) otherchannel).Users.Count * 100 / ((SocketGuild) otherchannel.Guild).Users.Count}% Visibility - The partner channel is currently inactive as less that 90% of this server's users can view the channel. You can fix this by ensuring that all roles have permissions to view messages and message history in the channel settings");
                                        continue;
                                    }

                                    //Generate an embed with the partner message from newitem
                                    var embed = new EmbedBuilder
                                    {
                                        Title        = otherchannel.Guild.Name,
                                        Description  = selectedguild.Message,
                                        ThumbnailUrl = otherchannel.Guild.IconUrl,
                                        ImageUrl     = selectedguild.ImageUrl,
                                        Color        = Color.Green,
                                        Footer       = new EmbedFooterBuilder
                                        {
                                            Text = selectedguild.showusercount
                                                    ? $"User Count: {((SocketGuild) otherchannel.Guild).MemberCount} || Get PassiveBOT: {gcon}"
                                                    : $"Get PassiveBOT: {gcon}"
                                        }
                                    };
                                    //send the partner message to the original server
                                    await channel.SendMessageAsync("", false, embed.Build());
                                    //remove the given item from the list so we don't have any repeats
                                    newlist.Remove(newitem);
                                    await Task.Delay(500);
                                }
                                catch     //(Exception e)
                                {
                                    //Console.WriteLine(e);
                                }
                            }
                            else
                            {
                                //auto-disable servers with a missing partner channel
                                guildobj.PartnerSetup.IsPartner = false;
                                GuildConfig.SaveServer(guildobj);
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                LastFireTime = DateTime.UtcNow;
            },
                               null, TimeSpan.Zero, TimeSpan.FromMinutes(FirePreiod));
        }
Пример #9
0
        async Task TrackStreams()
        {
            int count = 0;

            tracking = true;

            await Task.Yield();

            while (continue_tracking)
            {
                await Task.Delay(DELAY *tracked.Count * 1000);

                HttpClient web_client = new HttpClient();

                if (stream_list.Count == 0)
                {
                    EndTrack();
                }
                count = (count + 1) % stream_list.Count;

                string name = stream_list[count];
                HttpResponseMessage response = await GetResponse(web_client, GetStreamURLByUser(name));

                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine(response.StatusCode.ToString());
                    web_client.Dispose();
                    continue;
                }

                JSONObject data = Parser.Parse(await response.Content.ReadAsStringAsync());
                data = data["data"];

                if (data.is_table_array)
                {
                    // Stream Up
                    if (!live[name])
                    {
                        live[name] = true;

                        foreach (SocketGuild guild in client.Guilds)
                        {
                            if (tracked[guild.Id].ContainsKey(name))
                            {
                                ISocketMessageChannel channel = client.GetChannel(tracked[guild.Id][name]) as ISocketMessageChannel;
                                await channel.SendMessageAsync((channel as IGuildChannel).Guild.EveryoneRole.Mention + " " + name + " is live!");

                                await channel.SendMessageAsync("https://www.twitch.tv/" + name);
                            }
                        }
                    }
                }
                else
                {
                    // Stream Down
                    live[name] = false;
                }

                web_client.Dispose();
            }



            await Task.Yield();

            tracking = false;
        }
Пример #10
0
        private async Task <bool> StartService()
        {
            LoadSettings();

            // Escape early since we have nothing to process
            if (ReactSettings.UserReactRoleList == null)
            {
                _isRunning = true;
                return(true);
            }

            // Get our Emotes
            var serverGuild = _client.GetGuild(_settings.GuildId);

            if (serverGuild == null)
            {
                Console.WriteLine("ReactRoleService failed to start, could not return guild information.");
                await _loggingService.LogAction("ReactRoleService failed to start.");

                return(false);
            }

            for (var messageIndex = 0; messageIndex < ReactSettings.UserReactRoleList.Count; messageIndex++)
            {
                var reactMessage = ReactSettings.UserReactRoleList[messageIndex];
                // Channel used for message
                var messageChannel = _client.GetChannel(reactMessage.ChannelId) as IMessageChannel;
                if (messageChannel == null)
                {
                    Console.WriteLine($"ReactRoleService: Channel {reactMessage.ChannelId} does not exist.");
                    continue;
                }

                // Get The Message for this group of reactions
                if (!_reactMessages.ContainsKey(reactMessage.MessageId))
                {
                    _reactMessages.Add(reactMessage.MessageId, await messageChannel.GetMessageAsync(reactMessage.MessageId) as IUserMessage);
                }
                for (var i = 0; i < reactMessage.RoleCount(); i++)
                {
                    // We check if emote exists
                    var emote = serverGuild.Emotes.First(guildEmote => guildEmote.Id == reactMessage.Reactions[i].EmojiId);

                    // Add a Reference to our Roles to simplify lookup
                    if (!_guildRoles.ContainsKey(reactMessage.Reactions[i].EmojiId))
                    {
                        _guildRoles.Add(reactMessage.Reactions[i].EmojiId, serverGuild.GetRole(reactMessage.Reactions[i].RoleId));
                    }
                    // Same for the Emojis, saves look-arounds
                    if (!_guildEmotes.ContainsKey(reactMessage.Reactions[i].EmojiId))
                    {
                        _guildEmotes.Add(reactMessage.Reactions[i].EmojiId, emote);
                    }
                    // If our message doesn't have the emote, we add it.
                    if (!_reactMessages[reactMessage.MessageId].Reactions.ContainsKey(_guildEmotes[reactMessage.Reactions[i].EmojiId]))
                    {
                        Console.WriteLine($"Added Reaction to Message {reactMessage.MessageId} which was missing.");
                        // We could add these in bulk, but that'd require a bit more setup
                        await _reactMessages[reactMessage.MessageId].AddReactionAsync(emote);
                    }
                }
            }

            _isRunning = true;
            return(true);
        }
Пример #11
0
 public async Task AnnounceJoinedUser(SocketGuildUser user)                                                                                                                                               //Welcomes the new user
 {
     var channel = Client.GetChannel(124366291611025417) as SocketTextChannel;                                                                                                                            // Gets the channel to send the message in
     await channel.SendMessageAsync($"Welcome {user.Mention} to {channel.Guild.Name}. Please wait while we load the real humans. For general guidance in the meantime, check out <#549039583459934209>"); //Welcomes the new user
 }
Пример #12
0
        public async Task onMessage(SocketMessage message)
        {
            if (message.Author.IsBot == true)
            {
                return;
            }
            var guild       = client.GetGuild(558484910256422912);
            var male_roll   = guild.Roles.FirstOrDefault(roles => roles.Name == "男性");
            var female_roll = guild.Roles.FirstOrDefault(roles => roles.Name == "女性");
            var lgbtq_roll  = guild.Roles.FirstOrDefault(roles => roles.Name == "LGBTQ");

            var user = message.Author as SocketGuildUser;

            if (user.Roles.Contains(male_roll) || user.Roles.Contains(female_roll) || user.Roles.Contains(lgbtq_roll))
            {
                return;
            }

            if (message.Channel.Id == male)
            {
                await user.AddRoleAsync(male_roll);

                var annotation_ = client.GetChannel(annotation) as SocketTextChannel;
                await annotation_.SendMessageAsync(message.Author.Mention + "さんに" + male_roll.Name + "を付与しました。");

                var text = client.GetChannel(male) as SocketTextChannel;
                await text.SendMessageAsync(
                    "※あくまでテンプレです。参考までにどうぞ。\n" +
                    "\n" +
                    "\n" +
                    "【名前】\n" +
                    "【性別】\n" +
                    "【年齢】\n" +
                    "【住み】\n" +
                    "【時間】\n" +
                    "【趣味】\n" +
                    "【一言】\n"
                    );
            }

            if (message.Channel.Id == female)
            {
                await user.AddRoleAsync(female_roll);

                var annotation_ = client.GetChannel(annotation) as SocketTextChannel;
                await annotation_.SendMessageAsync(message.Author.Mention + "さんに" + female_roll.Name + "を付与しました。");

                var text = client.GetChannel(female) as SocketTextChannel;
                await text.SendMessageAsync(
                    "※あくまでテンプレです。参考までにどうぞ。\n" +
                    "\n" +
                    "\n" +
                    "【名前】\n" +
                    "【性別】\n" +
                    "【年齢】\n" +
                    "【住み】\n" +
                    "【時間】\n" +
                    "【趣味】\n" +
                    "【一言】\n"
                    );
            }
            if (message.Channel.Id == lgbtq)
            {
                await user.AddRoleAsync(lgbtq_roll);

                var annotation_ = client.GetChannel(annotation) as SocketTextChannel;
                await annotation_.SendMessageAsync(message.Author.Mention + "さんに" + lgbtq_roll.Name + "を付与しました。");

                var text = client.GetChannel(lgbtq) as SocketTextChannel;
                await text.SendMessageAsync(
                    "※あくまでテンプレです。参考までにどうぞ。\n" +
                    "\n" +
                    "\n" +
                    "【名前】\n" +
                    "【性別】\n" +
                    "【年齢】\n" +
                    "【住み】\n" +
                    "【時間】\n" +
                    "【趣味】\n" +
                    "【一言】\n"
                    );
            }
        }
Пример #13
0
 public Task <bool> ConnectVoiceChannel(ulong voiceChannelId)
 {
     return(ConnectVoiceChannel(DiscordSocketClient.GetChannel(voiceChannelId) as SocketVoiceChannel));
 }
Пример #14
0
        public async Task StartQCM([Remainder] string qcmName)
        {
            Console.WriteLine();
            Qcm qcm = await GetQcm(qcmName);

            AudioService audioService = (AudioService)Program._services.GetService(typeof(AudioService));

            if (am == null)
            {
                am = new AudioModule(audioService, Context);
            }
            IMessage msg = null;

            if (!qcm.HasStarted)
            {
                stopwatch.Restart();
                qcm.HasStarted = true;
                Console.WriteLine("Affichage Q1");
                // Si ça buggue ç'est à cause du display Mode
                msg = await qcm.DisplayInDiscord(_client.GetChannel(414746672284041222) as ISocketMessageChannel, qcm.questions[0], Qcm.DisplayMode.QCM, am);

                qcm.questionsID.Add(msg.Id);
            }
            else //Problème réussir à bloquer l'affichage Q2 cad ignorer le dernier smiley
            {
                ISocketMessageChannel channel = _client.GetChannel(414746672284041222) as ISocketMessageChannel;
                if (i < qcm.questions.Count)
                {
                    Console.WriteLine("On arrive à une question de type :" + qcm.questions[i].type);
                    msg = await qcm.DisplayInDiscord(_client.GetChannel(414746672284041222) as ISocketMessageChannel, qcm.questions[i], Qcm.DisplayMode.QCM);

                    qcm.questionsID.Add(msg.Id);
                    Console.WriteLine(stopwatch.ElapsedMilliseconds);
                }
                // Tableau des réponses
                else
                {
                    // Le tableau des réponses ne s'affiche que pour un affichage de type QCM
                    if (qcm.displayMode == Qcm.DisplayMode.QCM)
                    {
                        await channel.SendMessageAsync("Vous êtes arrivé au bout de ce QCM");

                        await channel.SendMessageAsync("Réponses enregistrées : " + qcm.allAnswers.Count);

                        EmbedBuilder embed    = new EmbedBuilder();
                        int          i        = 0;
                        int          score    = 0;
                        int          maxScore = qcm.allAnswers.Count;
                        Console.OutputEncoding = System.Text.Encoding.UTF8;
                        var usersIDThatAnswered = new List <ulong>();
                        var playerList          = new List <QcmPlayer>();
                        foreach (var ans in qcm.allAnswers)
                        {
                            if (!usersIDThatAnswered.Contains(ans.User.Value.Id))
                            {
                                usersIDThatAnswered.Add(ans.User.Value.Id);
                                playerList.Add(new QcmPlayer(ans.User.Value));
                            }
                        }
                        foreach (var ans in qcm.allAnswers)
                        {
                            try
                            {
                                if (ans.Emote.Name != null)
                                {
                                    embed.AddField("Votre Réponse n°" + (i + 1) + " : " + ans.Emote.Name, " par " + ans.User.Value.Username);
                                    foreach (var player in playerList)
                                    {
                                        if (ans.Emote.Name == qcm.questions[i].answerLetter && ans.User.Value == player.user)
                                        {
                                            player.score++;
                                        }
                                        if (ans.User.Value == player.user)
                                        {
                                            player.maxScore++;
                                        }
                                    }
                                    embed.AddField("Bonne réponse ", qcm.questions[i].answer + ":" + qcm.questions[i].answerLetter);
                                    if (ans.Emote.Name == qcm.questions[i].answerLetter)
                                    {
                                        score++;
                                    }
                                    else
                                    {
                                        Console.WriteLine(ans.Emote.Name + " : " + qcm.questions[i].answerLetter);
                                    }
                                }

                                i++;
                                embed.AddField("", "");
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }
                        await channel.SendMessageAsync("", false, embed);

                        await channel.SendMessageAsync(" Score Final " + score + " / " + maxScore + "\n Durée : " + (stopwatch.ElapsedMilliseconds / 1000) + "s");

                        foreach (var player in playerList)
                        {
                            await channel.SendMessageAsync(">> " + player.user.Username + " Score : " + player.score + " / " + player.maxScore);
                        }
                    }
                }
            }
            // return msg;
        }
Пример #15
0
        public void SendScoreEvent(ulong channelId, SubmitScore score)
        {
            var channel = _client.GetChannel(channelId) as SocketTextChannel;

            channel?.SendMessageAsync($"{score.Score.Username} has scored {score.Score._Score}{(score.Score.FullCombo ? " (Full Combo!)" : "")} on {score.Score.Parameters.Beatmap.Name}!");
        }
Пример #16
0
        public static async Task Browse(DiscordSocketClient _client, ulong category, ulong serverid) // Browsing - do every time a new channel is made.
        {
            ulong     mchannel     = _client.GetGuild(serverid).Channels.Where(x => x.Name.ToLower() == "gllobbies").First().Id;
            ListItems currentlobby = List.Where(x => x.CategoryId == category).First();

            #region make embed
            var se = new EmbedBuilder();
            se.WithColor(Color.Blue).WithTitle("Lobby Information:").AddField("Owner:", _client.GetUser(currentlobby.OwnerId).Mention).AddField("Game:", currentlobby.Game);
            if (currentlobby.Bio != null)
            {
                se.AddField("Bio:", currentlobby.Bio);
            }
            se.AddField("Access:", currentlobby.Access).WithFooter("To join this lobby, click the green reaction below. It may take a few seconds, so be paitent.");
            #endregion
            var message = await(_client.GetChannel(mchannel) as SocketTextChannel).SendMessageAsync("", false, se.Build());
            var aa      = new EmbedBuilder();

            var emote = _client.GetGuild(406657890921742336).Emotes.First() as IEmote;
            await message.AddReactionAsync(emote);

            List <ulong> joined = new List <ulong>
            {
                _client.CurrentUser.Id,
                currentlobby.OwnerId
            };
            var guild = _client.GetGuild(currentlobby.GuildId);
            // Create permissions
            OverwritePermissions denyall = new OverwritePermissions(PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Deny); OverwritePermissions inall = new OverwritePermissions(PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit, PermValue.Inherit); OverwritePermissions fairuser = new OverwritePermissions(PermValue.Inherit, PermValue.Inherit, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Deny, PermValue.Deny, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Deny, PermValue.Allow, PermValue.Allow, PermValue.Allow, PermValue.Deny, PermValue.Deny, PermValue.Deny, PermValue.Allow, PermValue.Deny, PermValue.Deny);

            await Task.Delay(5000);

            while (true) // Goes until break;
            {
                // Updates browser
                try
                {
                    var exists = List.Where(x => x.CategoryId == category);
                    if (exists.Count() == 0) // Does not exist anymore.
                    {
                        await message.DeleteAsync();

                        break;
                    }
                    else // Still exists.
                    {
                        // Set currentlobby to be the actual current lobby.
                        currentlobby = exists.First();

                        // Create correct embed
                        var eb = new EmbedBuilder();
                        eb.WithColor(Color.Blue).WithTitle("Lobby Information:").AddField("Owner:", _client.GetUser(currentlobby.OwnerId).Mention).AddField("Game:", currentlobby.Game);
                        if (currentlobby.Bio != null)
                        {
                            eb.AddField("Bio:", currentlobby.Bio);
                        }
                        eb.AddField("Access:", currentlobby.Access).WithFooter("To join this lobby, click the green reaction below. It may take a few seconds, so be paitent.");

                        if (currentlobby.Bio != null)
                        {
                            if (eb.Build().Fields[1].Value == message.Embeds.First().Fields[1].Value && eb.Build().Fields[2].Value == message.Embeds.First().Fields[2].Value &&
                                eb.Build().Fields[3].Value == message.Embeds.First().Fields[3].Value)
                            {
                                // do nothing
                            }
                            else
                            {
                                await message.ModifyAsync(x => { x.Embed = eb.Build(); });
                            }
                        }
                        else
                        {
                            if (eb.Build().Fields[1].Value == message.Embeds.First().Fields[1].Value && eb.Build().Fields[2].Value == message.Embeds.First().Fields[2].Value)
                            {
                                // do nothing
                            }
                            else
                            {
                                await message.ModifyAsync(x => { x.Embed = eb.Build(); });
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }



                // Checks for new users
                try
                {
                    var users = await message.GetReactionUsersAsync(emote);

                    List <IUser> newu = new List <IUser>();
                    foreach (var user in users)
                    {
                        if (joined.Contains(user.Id))
                        {
                        }
                        else
                        {
                            newu.Add(user);
                        }
                        if (user.Id != _client.CurrentUser.Id)
                        {
                            await Task.Delay(1000);                         // Try to not ratelimit.

                            await message.RemoveReactionAsync(emote, user); // Removes reaction
                        }
                    }
                    foreach (var user in newu) // Does something for every new user that has joined.
                    {
                        joined.Add(user.Id);   // Adds to list so it counts as new user.
                        // Join Lobby
                        var chnls = guild.Channels.Where(x => x.CategoryId == category);
                        foreach (var chnl in chnls) // Apply new permissions and such.
                        {
                            if (currentlobby.Access.ToLower() == "private")
                            {
                                var keyc = chnls.Where(chn => !(chn.Name.ToLower().Contains("text") || chn.Name.ToLower().Contains("voice"))).First();
                                await keyc.AddPermissionOverwriteAsync(user, fairuser);

                                await(keyc as SocketTextChannel).SendMessageAsync(user.Mention + " please input the lobby key.\n\nDo this by doing `joinkey: {key}`\n\n(If you do not know the key, you can do `leavelobby:` to exit.)");
                                break;
                            }
                            else
                            {
                                await(_client.GetChannel(currentlobby.CategoryId) as SocketCategoryChannel).AddPermissionOverwriteAsync(user, fairuser);
                                await(chnls.Where(x => x.Name.ToLower().Contains("text")).First() as SocketTextChannel).SendMessageAsync($"{user.Mention} has joined the lobby! You can do `leavelobby:` at any time to leave it.");
                                break;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
                await Task.Delay(5000); // Just so it slows down a bit - not as frantic checking. Saves my PC.
            }
        }
Пример #17
0
        private async void SendReminder(Reminder r, TimeSpan expired)
        {
            // build the embed
            var embed = new EmbedBuilder();

            embed.WithAuthor(m_client.CurrentUser);

            string title;

            if (expired.Equals(TimeSpan.Zero))
            {
                title = "Reminder Expired";
            }
            else
            {
                title = expired.Humanize(3, false).Humanize(LetterCasing.Title) + " Remains";
            }
            embed.WithTitle(title);

            //embed.WithCurrentTimestamp();

            // get the author username
            var user = m_client.GetUser(r.AuthorId);

            if (user != null)
            {
                embed.WithFooter("Reminder created by " + user.Username);
            }

            string description;

            // when reminder expire, don't include the timespan difference between now and remindertime
            //if (expired.Equals( TimeSpan.Zero))
            //{
            //    description = $"Reminder for {r.ReminderTime.ToString("g")}\n\n{r.ReminderText}";
            //}
            //else
            //{
            //    description = $"Reminder for {r.ReminderTime.ToString("g")} ({(r.ReminderTime - DateTime.Now).Humanize()} remains.)\n\n{r.ReminderText}";
            //}

            description = $"Reminder for {r.ReminderTime.ToString("g")}\n\n{r.ReminderText}";

            if (r.ReminderTimeSpanTicks.Count > 1)
            {
                // list the remaining reminder timespans
                description += "\n\nNext reminder notifications:\n";
                foreach (TimeSpan ts in r.ReminderTimeSpans)
                {
                    description += $"{ts.Humanize(3, false)}\n";
                }
            }

            description = description.TrimEnd();

            string mentionStr = "";

            // get the person that we are supposed to ping
            if (r.ReminderType == ReminderType.Author && user != null)
            {
                mentionStr = user.Mention;
            }
            else if (r.ReminderType == ReminderType.Channel)
            {
                mentionStr = "@here";
            }
            else if (r.ReminderType == ReminderType.Guild)
            {
                mentionStr = "@everyone";
            }

            embed.WithColor(new Color(255, 204, 77));
            embed.WithDescription(description);
            embed.WithFooter("Reminder ID " + r.ID);

            // get the guild
            var guild = m_client.GetGuild(r.GuildId);

            if (guild == null)
            {
                return;
            }

            // get the channel
            var channel = m_client.GetChannel(r.TextChannelId);

            if (channel == null)
            {
                return;
            }

            // cast it to a message channel
            IMessageChannel socketChannel = channel as IMessageChannel;

            if (socketChannel == null)
            {
                return;
            }

            // send the message
            try
            {
                var msg = await socketChannel.SendMessageAsync(mentionStr, false, embed.Build());

                if (r.LastReminderMessageId.HasValue)
                {
                    // get the id of the last reminder message
                    // and delete the message

                    var g       = m_client.GetGuild(r.GuildId);
                    var c       = g.GetChannel(r.TextChannelId) as ITextChannel;
                    var message = await c.GetMessageAsync(r.LastReminderMessageId.Value) as IMessage;

                    if (message == null)
                    {
                        await Bot.Log(new LogMessage(LogSeverity.Warning, "ReminderService",
                                                     "Tried to delete an expired reminder notification, but got casting error."));
                    }
                    else
                    {
                        await message.DeleteAsync();
                    }
                }

                // set the LastReminderMessageId
                r.LastReminderMessageId = msg.Id;

                // actually update this back in the LiteDB
                UpdateReminder(r);
            }
            catch (Exception e)
            {
                // catch permissions issues that may result from sending a message or deleting the old one
                // if we catch, then at lesat update the reminder in the db
                UpdateReminder(r);
            }
        }
Пример #18
0
        async private void SendButton_Click(object sender, EventArgs e)
        {
            Embed embed = null;

            if (EmbedEnabled.Checked)
            {
                EmbedBuilder builder = new EmbedBuilder();
                builder.Title       = EmbedNameTextBox.Text;
                builder.Description = DescriptionTextBox.Text;
                builder.Color       = (Discord.Color?)colorDialog1.Color;
                builder.ImageUrl    = ImageUrl.Text;

                if (AuthorEnabled.Checked)
                {
                    builder.WithAuthor(new EmbedAuthorBuilder().WithIconUrl(AuthorIconUrlTextBox.Text).WithName(AuthorText.Text).WithUrl(AuthorUrlTextBox.Text));
                }

                if (FooterEnabled.Checked)
                {
                    builder.WithFooter(new EmbedFooterBuilder().WithIconUrl(FooterIconUrl.Text).WithText(FooterText.Text));
                }

                embed = builder.Build();
            }

            if (InputWebHookRadioBtn.Checked)
            {
                DiscordWebhookClient webhookClient = new DiscordWebhookClient(InputWebHookTextBox.Text);
                await webhookClient.SendMessageAsync(text: TextTextBox.Text, username : NameTextBox.Text, avatarUrl : AvatarTextBox.Text, embeds : new Embed[] { embed });

                webhookClient.Dispose();
            }
            else if (ChooseWebHookRadioBtn.Checked)
            {
                //DiscordWebhookClient webhookClient = new DiscordWebhookClient(hooks[WebHookComboBox.SelectedIndex]._WebHook);
                //await webhookClient.SendMessageAsync(text: TextTextBox.Text, username: NameTextBox.Text, avatarUrl: AvatarTextBox.Text, embeds: new Embed[] { embed });

                //webhookClient.Dispose();

                MessageBox.Show("Нажмите кнопку \"Выбрать\"");
            }
            else if (InputTokenRadioButton.Checked)
            {
                if (_client == null)                 // Если сменить токен после отправки, отправлять будет всё-равно на прошлый токен
                {
                    _client = new DiscordSocketClient();
                    await _client.LoginAsync(0, TokenTextBox.Text);                     // TokenType.User = 0

                    await _client.StartAsync();

                    while (_client.ConnectionState != Discord.ConnectionState.Connected)
                    {
                        await Task.Delay(500);
                    }
                }

                if (GuildChannelRadioButton.Checked)                 // Guild Channel
                {
                    var channel = _client
                                  .GetChannel(ulong.Parse(ChannelIdTextBox.Text));

                    await((IMessageChannel)channel).SendMessageAsync(TextTextBox.Text, embed: embed);
                }
                else if (UserRadioButton.Checked)                   // User channel
                {
                    SocketUser user = _client
                                      .GetUser(ulong.Parse(UserIdTextBox.Text));

                    await user.SendMessageAsync(TextTextBox.Text, embed : embed);
                }
            }
        }
Пример #19
0
 public SocketChannel getChannel(ulong id)
 {
     return(client.GetChannel(id));
 }
Пример #20
0
        private async Task DeletedAsync(Cacheable <IMessage, ulong> CacheableMessage, ISocketMessageChannel origChannel)
        {
            var CachedMessage = await CacheableMessage.GetOrDownloadAsync();

            var MessageChannel = (ITextChannel)origChannel;

            if (CachedMessage.Source != MessageSource.User)
            {
                return;
            }
            if (MessageChannel.Guild == null)
            {
                return;
            }
            if (CachedMessage == null)
            {
                return;
            }

            Guild G = null;
            List <BlockedLogs> BLs = new List <BlockedLogs>();

            using (var uow = DBHandler.UnitOfWork())
            {
                if (!uow.Guild.IsDeleteLoggingEnabled(MessageChannel.Guild.Id))
                {
                    return;
                }
                G = uow.Guild.GetOrCreateGuild(MessageChannel.Guild.Id);
                if (G.GuildID == 0)
                {
                    return;
                }
                BLs = uow.BlockedLogs.GetServerBlockedLogs(MessageChannel.Guild.Id);
            }

            if (BLs != null && BLs.Count > 0)
            {
                if (BLs.Any(x => CachedMessage.Content.StartsWith(x.BlockedString)))
                {
                    return;
                }
            }

            if (G == null)
            {
                return;
            }

            var ChannelToSend = (IMessageChannel)_discord.GetChannel(G.DeleteLogChannel);

            string content = CachedMessage.Content;

            if (content == "")
            {
                content = "*original message was blank*";
            }

            EmbedBuilder embed = new EmbedBuilder().WithAuthor(eab => eab.WithIconUrl(CachedMessage.Author.GetAvatarUrl()).WithName(CachedMessage.Author.Username)).WithOkColour()
                                 .AddField(efb => efb.WithName("Channel").WithValue("#" + origChannel.Name).WithIsInline(true))
                                 .AddField(efb => efb.WithName("MessageID").WithValue(CachedMessage.Id).WithIsInline(true))
                                 .AddField(efb => efb.WithName("UserID").WithValue(CachedMessage.Author.Id).WithIsInline(true))
                                 .AddField(efb => efb.WithName("Message").WithValue(content));

            string footerText = "Created: " + CachedMessage.CreatedAt.ToString();

            if (CachedMessage.EditedTimestamp != null)
            {
                footerText += $" | Edited: " + CachedMessage.EditedTimestamp.ToString();
            }

            EmbedFooterBuilder footer = new EmbedFooterBuilder().WithText(footerText);

            await ChannelToSend.BlankEmbedAsync(embed.WithFooter(footer).Build());

            if (CachedMessage.Attachments.Count > 0)
            {
                await ChannelToSend.SendMessageAsync(string.Format("Message ID: {0} contained {1} attachment{2}.", CachedMessage.Id, CachedMessage.Attachments.Count, CachedMessage.Attachments.Count > 1 || CachedMessage.Attachments.Count == 0 ? "s" : string.Empty));
            }
        }
Пример #21
0
        private async Task onReactionAdded(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction)
        {
            var requests = Requests.FindAll(r => r.messageId == reaction.MessageId);

            if (requests.Count > 0)
            {
                string items          = "";
                bool   completedOrder = false;

                foreach (var request in requests)
                {
                    if (reaction.Emote.Name == "⏲")
                    {
                        request.assignedCrafter = reaction.User.Value.Mention;
                        request.status          = OrderStatus.Assigned;
                    }
                    else if (reaction.Emote.Name == "✅")
                    {
                        if (request.assignedCrafter == "Unassigned")
                        {
                            request.assignedCrafter = reaction.User.Value.Mention;
                        }
                        request.status = OrderStatus.InProgress;
                    }
                    else if (reaction.Emote.Name == "📦")
                    {
                        if (request.assignedCrafter == "Unassigned")
                        {
                            request.assignedCrafter = reaction.User.Value.Mention;
                        }
                        request.status = OrderStatus.Ready;
                    }
                    else if (reaction.Emote.Name == "🛄")
                    {
                        if (request.assignedCrafter == "Unassigned")
                        {
                            request.assignedCrafter = reaction.User.Value.Mention;
                        }
                        request.status = OrderStatus.Completed;

                        completedOrder = true;
                    }
                    else if (reaction.Emote.Name == "❌")
                    {
                        //TODO Delete Post
                        Requests.Remove(request);
                    }
                    items += $"{request.quantity}x {request.itemName}{Environment.NewLine}";
                }

                if (completedOrder)
                {
                    var message = await channel.GetMessageAsync(reaction.MessageId);

                    await message.DeleteAsync();

                    Requests.RemoveAll(r => r.messageId == reaction.MessageId);

                    var archives = Client.GetChannel(524011068285255696) as SocketTextChannel;
                    await archives.SendMessageAsync($"[{DateTime.Now.ToShortDateString()}] OrderID: {requests[0].id} | Requester: {requests[0].Requester} | Crafter: {requests[0].assignedCrafter} {Environment.NewLine} {items}");
                }

                Utilities.UpdateListing(channel);
            }
        }
Пример #22
0
        /// <inheritdoc />
        public override Task <IReadOnlyCollection <ChannelRepresentation> > MapChannels(IEnumerable <Api.Models.ChatChannel> channels, CancellationToken cancellationToken)
        {
            if (channels == null)
            {
                throw new ArgumentNullException(nameof(channels));
            }

            if (!Connected)
            {
                Logger.LogWarning("Cannot map channels, provider disconnected!");
                return(Task.FromResult <IReadOnlyCollection <ChannelRepresentation> >(Array.Empty <ChannelRepresentation>()));
            }

            ChannelRepresentation GetModelChannelFromDBChannel(Api.Models.ChatChannel channelFromDB)
            {
                if (!channelFromDB.DiscordChannelId.HasValue)
                {
                    throw new InvalidOperationException("ChatChannel missing DiscordChannelId!");
                }

                var    channelId = channelFromDB.DiscordChannelId.Value;
                ulong  discordChannelId;
                string connectionName;
                string friendlyName;

                if (channelId == 0)
                {
                    connectionName   = client.CurrentUser.Username;
                    friendlyName     = "(Unmapped accessible channels)";
                    discordChannelId = 0;
                }
                else
                {
                    var discordChannel = client.GetChannel(channelId);
                    if (!(discordChannel is ITextChannel textChannel))
                    {
                        Logger.LogWarning("Cound not map channel {0}! Incorrect type: {1}", channelId, discordChannel?.GetType());
                        return(null);
                    }

                    discordChannelId = textChannel.Id;
                    connectionName   = textChannel.Guild.Name;
                    friendlyName     = textChannel.Name;
                }

                var channelModel = new ChannelRepresentation
                {
                    RealId           = discordChannelId,
                    IsAdminChannel   = channelFromDB.IsAdminChannel == true,
                    ConnectionName   = connectionName,
                    FriendlyName     = friendlyName,
                    IsPrivateChannel = false,
                    Tag = channelFromDB.Tag
                };

                Logger.LogTrace("Mapped channel {0}: {1}", channelModel.RealId, channelModel.FriendlyName);
                return(channelModel);
            }

            var enumerator = channels
                             .Select(x => GetModelChannelFromDBChannel(x))
                             .Where(x => x != null).ToList();

            lock (mappedChannels)
            {
                mappedChannels.Clear();
                mappedChannels.AddRange(enumerator.Select(x => x.RealId));
            }

            return(Task.FromResult <IReadOnlyCollection <ChannelRepresentation> >(enumerator));
        }
Пример #23
0
 public static SocketChannel GetChannel(ulong channelId)
 {
     return(DiscordClient.GetChannel(channelId));
 }
Пример #24
0
        public async Task StartRemindersAsync()
        {
            var dbGuild = _database.Guild;

            var channel = _client.GetChannel(dbGuild.WarChannelId) as SocketTextChannel;
            var guild   = channel.Guild;

            IRole warRole = null;

            while (true)
            {
                try
                {
                    var currentWar = await _clash.GetCurrentWarAsync(dbGuild.ClanTag);

                    if (currentWar is null || currentWar.State == WarState.Default || currentWar.State == WarState.Ended)
                    {
                        await Task.Delay(TimeSpan.FromMinutes(10), _maintenanceCts.Token);

                        continue;
                    }

                    async Task RunRemindersAsync(bool hasMatched)
                    {
                        TimeSpan threshold;

                        if (hasMatched)
                        {
                            currentWar = await _clash.GetCurrentWarAsync(dbGuild.ClanTag);

                            threshold = DateTimeOffset.UtcNow - currentWar.StartTime;
                        }

                        else
                        {
                            threshold = DateTimeOffset.UtcNow - currentWar.PreparationTime;
                        }

                        if (threshold < TimeSpan.FromMinutes(60))
                        {
                            if (!hasMatched)
                            {
                                warRole = await WarMatchAsync(channel, dbGuild, guild, currentWar);

                                var startTime = currentWar.StartTime - DateTimeOffset.UtcNow;

                                await Task.Delay(startTime, _maintenanceCts.Token);
                            }

                            await channel.SendMessageAsync($"{warRole?.Mention} war has started!");

                            _warTcs.SetResult(true);

                            var beforeEnd = currentWar.EndTime - DateTimeOffset.UtcNow.AddHours(1);

                            await Task.Delay(beforeEnd, _maintenanceCts.Token);

                            currentWar = await _clash.GetCurrentWarAsync(dbGuild.ClanTag);

                            await NeedToAttackAsync(channel, dbGuild.GuildMembers, currentWar);

                            await Task.Delay(TimeSpan.FromHours(1).Add(TimeSpan.FromMinutes(10)));

                            currentWar = await _clash.GetCurrentWarAsync(dbGuild.ClanTag);

                            await WarEndedAsync(channel, dbGuild.GuildMembers, currentWar);

                            await warRole.DeleteAsync();
                        }
                    }

                    switch (currentWar.State)
                    {
                    case WarState.Preparation:
                        await RunRemindersAsync(false);

                        break;

                    case WarState.InWar:
                        await RunRemindersAsync(true);

                        break;
                    }

                    await Task.Delay(TimeSpan.FromMinutes(10), _maintenanceCts.Token);
                }
                catch (TaskCanceledException)
                {
                    await channel.SendMessageAsync("Maintenance break");

                    try
                    {
                        await Task.Delay(-1, _noMaintenanceCts.Token);
                    }
                    catch (TaskCanceledException) { }

                    await channel.SendMessageAsync("Maintenance ended");
                }
                catch (Exception ex)
                {
                    await _logger.LogAsync(Source.Reminder, Severity.Error, string.Empty, ex);
                }
                finally
                {
                    _warTcs = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);
                }
            }
        }
Пример #25
0
 public static async Task UpdateMenu(UserAccount user, ulong channelid, int num, string content)
 {
     await UpdateMenu(user, (ISocketMessageChannel)_client.GetChannel(channelid), num, content);
 }
Пример #26
0
        public async Task RunBotAsync()
        {
            var config = new Config("./config.json");

            var clashClient = new ClashClient(new ClashClientConfig
            {
                Token = config.ClashToken
            });

            var bandClient = new BandClient(new BandClientConfig
            {
                Token = config.BandToken
            });

            var asm = Assembly.GetEntryAssembly();

            _services = new ServiceCollection()
                        .AddSingleton(_client = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel            = LogSeverity.Verbose,
                AlwaysDownloadUsers = true,
                MessageCacheSize    = 100
            }))
                        .AddSingleton(_commands = new CommandService(new CommandServiceConfiguration
            {
                StringComparison = StringComparison.InvariantCultureIgnoreCase
            })
                                                  .AddTypeParsers(asm))
                        .AddSingleton(clashClient)
                        .AddSingleton(bandClient)
                        .AddSingleton <TaskQueue>()
                        .AddServices(asm.FindTypesWithAttribute <ServiceAttribute>())
                        .BuildServiceProvider();

            var tcs = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);

            Task OnReadyAsync()
            {
                tcs.SetResult(true);
                _client.Ready -= OnReadyAsync;
                return(Task.CompletedTask);
            }

            _client.Ready += OnReadyAsync;

            _client.UserJoined += user =>
            {
                Task.Run(async() =>
                {
                    var guild  = _services.GetService <DatabaseService>().Guild;
                    var dGuild = _client.GetGuild(guild.Id);

                    var channel = dGuild.GetTextChannel(guild.WelcomeChannelId);
                    var role    = dGuild.GetRole(guild.NotVerifiedRoleId);

                    await user.AddRoleAsync(role);

                    var builder = new EmbedBuilder
                    {
                        Color        = new Color(0x11f711),
                        ThumbnailUrl = dGuild.CurrentUser.GetAvatarUrl(),
                        Title        = "Welcome to the Discord!",
                        Description  = $"{user.GetDisplayName()} welcome to Reddit Rise!\nHere are some premade, perfect FWA bases. Please click the link that corresponds to your TH.\n" +
                                       $"{Format.Url("TH12", "https://link.clashofclans.com/en?action=OpenLayout&id=TH12%3AWB%3AAAAAHQAAAAFw3gmOJJOUocokY9SNAt9V")}\n" +
                                       $"{Format.Url("TH11", "https://link.clashofclans.com/en?action=OpenLayout&id=TH11%3AWB%3AAAAAOwAAAAE4a6sCQApcIa9kDl5W1N3C")}\n" +
                                       $"{Format.Url("TH10", "https://link.clashofclans.com/en?action=OpenLayout&id=TH10%3AWB%3AAAAAFgAAAAF-L9A_pnLR3BtoRk7SZjD_")}\n" +
                                       $"{Format.Url("TH9", "https://link.clashofclans.com/en?action=OpenLayout&id=TH9%3AWB%3AAAAAHQAAAAFw3chc3wBw2ipMxGm6Mq8P")}\n" +
                                       "and if you're feeling nice post your in game player tag (e.g. #YRQ2Y0UC) so we know who you are!"
                    };

                    await channel.SendMessageAsync(user.Mention, embed: builder.Build());
                });
                return(Task.CompletedTask);
            };

            var logger = _services.GetService <LogService>();

            _client.Log += message =>
            {
                var(source, severity, lMessage, exception) = LogFactory.FromDiscord(message);
                return(logger.LogAsync(source, severity, lMessage, exception));
            };

            //TODO do this properly
            _client.UserLeft += (user) =>
            {
                var channel = _client.GetChannel(533650294509404181) as SocketTextChannel;
                return(channel.SendMessageAsync($"{user.GetDisplayName()} left"));
            };

            clashClient.Log   += message => logger.LogAsync(Source.Clash, Severity.Verbose, message);
            clashClient.Error += error => logger.LogAsync(Source.Clash, Severity.Error, error.Message);

            bandClient.Log   += message => logger.LogAsync(Source.Band, Severity.Verbose, message);
            bandClient.Error += error => logger.LogAsync(Source.Band, Severity.Error, error.Message);

            await _client.LoginAsync(TokenType.Bot, config.BotToken);

            await _client.StartAsync();

            _commands.AddModules(Assembly.GetEntryAssembly());

            await tcs.Task;

            _services.GetService <MessageService>();

            //Task.Run(() => _services.GetService<BigBrotherService>().RunServiceAsync());

#if !DEBUG
            Task.Run(() => _services.GetService <WarReminderService>().StartRemindersAsync());
            Task.Run(() => _services.GetService <WarReminderService>().StartPollingServiceAsync());
            Task.Run(() => _services.GetService <StartTimeService>().StartServiceAsync());
#endif

            await Task.Delay(-1);
        }
Пример #27
0
 public async Task AnnounceJoinedUser(SocketGuildUser user) //Welcomes the new user
 {
     //Console.WriteLine("User joined");
     var channel = _client.GetChannel(421689189805981698) as SocketTextChannel;                                     // Gets the channel to send the message in
     await channel.SendMessageAsync($"Welcome {user.Mention} to {channel.Guild.Name}! Enjoy your stay \\\\(≧ω≦)/"); //Welcomes the new user
 }
Пример #28
0
 /* GENERAL COMMANDS */
 public static async Task MessageChannel(DiscordSocketClient client, string messageContent, ulong channelId)
 {
     var channel = client.GetChannel(channelId) as IMessageChannel;
     await channel.SendMessageAsync(messageContent);
 }
Пример #29
0
        public async Task HandleReaction(DiscordSocketClient discordSocketClient, SocketReaction reaction, ISocketMessageChannel channel, Dictionary <string, string> _reactionWatcher, Program program)
        {
            if (reaction.MessageId.ToString() == "586248421715738629")
            {
                var eventDetailChannel = (ISocketMessageChannel)discordSocketClient.GetChannel(572721078359556097);
                var embededMessage     = (IUserMessage)await eventDetailChannel.GetMessageAsync(586248421715738629);

                var embedInfo = embededMessage.Embeds.First();
                var guild     = discordSocketClient.Guilds.FirstOrDefault(x => x.Id == (ulong)505485680344956928);
                var user      = guild.GetUser(reaction.User.Value.Id);

                var embedBuilder = new EmbedBuilder
                {
                    Title       = embedInfo.Title,
                    Description = embedInfo.Description + "\n" + user.Username,
                    Footer      = new EmbedFooterBuilder {
                        Text = embedInfo.Footer.ToString()
                    },
                    Color = embedInfo.Color
                };

                await embededMessage.ModifyAsync(msg => msg.Embed = embedBuilder.Build());
            }

            var data = JsonExtension.GetJsonData("../../../Resources/irleventdata.txt");

            if (reaction.UserId != 504633036902498314 && data.Keys.Contains(reaction.MessageId.ToString()))
            {
                if (reaction.Emote.ToString() == "<:green_check:671412276594475018>")
                {
                    var deelnemersMsgData =
                        JsonExtension.ToDictionary <string[]>(data[reaction.MessageId.ToString()]);
                    var eventDetailChannel = reaction.Channel;
                    var msgId          = deelnemersMsgData.First().Key;
                    var embededMessage =
                        (IUserMessage)await eventDetailChannel.GetMessageAsync(ulong.Parse(msgId));

                    var embedInfo = embededMessage.Embeds.First();
                    var user      = discordSocketClient.GetUser(reaction.User.Value.Id);

                    var embedBuilder = new EmbedBuilder
                    {
                        Title       = embedInfo.Title,
                        Description = embedInfo.Description + "\n" + "<@!" + user.Id + ">",
                        Footer      = new EmbedFooterBuilder {
                            Text = embedInfo.Footer.ToString()
                        },
                        Color = embedInfo.Color
                    };
                    //Add permissions to see the general event channel
                    var d = deelnemersMsgData[reaction.MessageId + "0"];
                    var generalChannel = discordSocketClient.GetGuild(505485680344956928)
                                         .GetChannel(ulong.Parse(d.First()));
                    await generalChannel.AddPermissionOverwriteAsync(user,
                                                                     new OverwritePermissions().Modify(sendMessages: PermValue.Allow,
                                                                                                       viewChannel: PermValue.Allow, readMessageHistory: PermValue.Allow));

                    await embededMessage.ModifyAsync(msg => msg.Embed = embedBuilder.Build());
                }
                else if (reaction.Emote.ToString() == "<:blue_check:671413239992549387>")
                {
                    var user = discordSocketClient.GetUser(reaction.User.Value.Id);
                    var deelnemersMsgData =
                        JsonExtension.ToDictionary <string[]>(data[reaction.MessageId.ToString()]);
                    var d = deelnemersMsgData[reaction.MessageId + "0"];
                    var generalChannel = discordSocketClient.GetGuild(505485680344956928)
                                         .GetChannel(ulong.Parse(d.First()));
                    await generalChannel.AddPermissionOverwriteAsync(user,
                                                                     new OverwritePermissions().Modify(sendMessages: PermValue.Allow,
                                                                                                       viewChannel: PermValue.Allow, readMessageHistory: PermValue.Allow));
                }
                else if (reaction.Emote.ToString() == "<:red_check:671413258468720650>")
                {
                    var user           = discordSocketClient.GetUser(reaction.User.Value.Id);
                    var generalChannel = discordSocketClient.GetGuild(505485680344956928)
                                         .GetChannel(reaction.Channel.Id);
                    await generalChannel.AddPermissionOverwriteAsync(user,
                                                                     new OverwritePermissions().Modify(sendMessages: PermValue.Deny, viewChannel: PermValue.Deny,
                                                                                                       readMessageHistory: PermValue.Deny));
                }
            }

            if (reaction.MessageId.ToString() == "586248421715738629")
            {
                var messageID = reaction.MessageId;
                var userID    = reaction.UserId;
            }

            if (channel.Id == 549343990957211658)
            {
                var guild     = discordSocketClient.Guilds.FirstOrDefault(x => x.Id == (ulong)505485680344956928);
                var user      = guild.GetUser(reaction.User.Value.Id);
                var userRoles = user.Roles;
                foreach (var role in userRoles)
                {
                    if (role.Name == "Nieuwkomer")
                    {
                        var addRole    = guild.Roles.FirstOrDefault(x => x.Name == "Koos Rankloos");
                        var deleteRole = guild.Roles.FirstOrDefault(x => x.Name == "Nieuwkomer");
                        await user.AddRoleAsync(addRole);

                        await user.RemoveRoleAsync(deleteRole);
                    }
                }
            }

            if (channel.Id == 549350982081970176)
            {
                bool authenticationCheck()
                {
                    var guild     = discordSocketClient.Guilds.FirstOrDefault(x => x.Id == (ulong)505485680344956928);
                    var userRoles = guild.GetUser(reaction.User.Value.Id).Roles;

                    foreach (var role in userRoles)
                    {
                        if (role.Name == "Staff")
                        {
                            return(true);
                        }
                    }

                    return(false);
                }

                if (authenticationCheck())
                {
                    //{✅}
                    //{⛔}
                    // vinkje = status veranderen en actie uitvoeren om er in te zetten
                    // denied is status veranderen en user mention gebruiken
                    var messageFromReaction = await reaction.Channel.GetMessageAsync(reaction.MessageId);

                    var casted    = (IUserMessage)messageFromReaction;
                    var usedEmbed = casted.Embeds.First();
                    if (reaction.Emote.Name == "⛔")
                    {
                        var deniedEmbed = new EmbedBuilder();
                        //need staff check
                        try
                        {
                            deniedEmbed = new EmbedBuilder
                            {
                                Title        = usedEmbed.Title,
                                Description  = usedEmbed.Description.Replace("Waiting for approval", "Denied"),
                                ThumbnailUrl = usedEmbed.Thumbnail.Value.Url,
                                Color        = Color.Red
                            };
                        }
                        catch
                        {
                            deniedEmbed = new EmbedBuilder
                            {
                                Title       = usedEmbed.Title,
                                Description = usedEmbed.Description.Replace("Waiting for approval", "Denied"),
                                Color       = Color.Red
                            };
                        }

                        await casted.ModifyAsync(msg => msg.Embed = deniedEmbed.Build());

                        await casted.RemoveAllReactionsAsync();
                    }

                    if (reaction.Emote.Name == "✅")
                    {
                        var digitsOnly    = new Regex(@"[^\d]");
                        var oneSpace      = new Regex("[ ]{2,}");
                        var IDS           = oneSpace.Replace(digitsOnly.Replace(usedEmbed.Description, " "), "-").Split("-");
                        var discordId     = IDS[2];
                        var scoresaberId  = IDS[1];
                        var approvedEmbed = new EmbedBuilder();
                        try
                        {
                            approvedEmbed = new EmbedBuilder
                            {
                                Title        = usedEmbed.Title,
                                Description  = usedEmbed.Description.Replace("Waiting for approval", "Approved"),
                                ThumbnailUrl = usedEmbed.Thumbnail.Value.Url,
                                Color        = Color.Green
                            };
                        }
                        catch
                        {
                            approvedEmbed = new EmbedBuilder
                            {
                                Title       = usedEmbed.Title,
                                Description = usedEmbed.Description.Replace("Waiting for approval", "Approved"),
                                Color       = Color.Green
                            };
                        }


                        var check = await new RoleAssignment(discordSocketClient).LinkAccount(discordId,
                                                                                              scoresaberId);
                        if (check)
                        {
                            await casted.ModifyAsync(msg => msg.Embed = approvedEmbed.Build());

                            await casted.RemoveAllReactionsAsync();
                        }

                        var player = await new ScoresaberAPI(scoresaberId).GetPlayerFull();


                        DutchRankFeed.GiveRoleWithRank(player.playerInfo.CountryRank, scoresaberId, discordSocketClient);
                        var dutchGuild  = new GuildService(discordSocketClient, 505485680344956928);
                        var linkingUser = dutchGuild.Guild.GetUser(new RoleAssignment(discordSocketClient).GetDiscordIdWithScoresaberId(scoresaberId));
                        await dutchGuild.AddRole("Verified", linkingUser);


                        await dutchGuild.DeleteRole("Link my discord please", linkingUser);

                        await dutchGuild.DeleteRole("Koos Rankloos", linkingUser);

                        await program.UserJoinedMessage(linkingUser);
                    }
                }
            }

            //Add Roles from reactions added to specific channels
            if (channel.Id == 510227606822584330 || channel.Id == 627292184143724544)
            {
                var guild = discordSocketClient.GetGuild(505485680344956928);
                if (channel.Id == 510227606822584330)
                {
                    guild = discordSocketClient.GetGuild(505485680344956928);
                }
                else if (channel.Id == 627292184143724544)
                {
                    guild = discordSocketClient.GetGuild(627156958880858113);
                }
                var user = guild.GetUser(reaction.UserId);

                var t = reaction.Emote.ToString().Replace("<a:", "<:");

                foreach (var reactionDic in _reactionWatcher)
                {
                    if (reactionDic.Key == t)
                    {
                        var role = guild.Roles.FirstOrDefault(x => x.Name == reactionDic.Value);
                        await(user as IGuildUser).AddRoleAsync(role);
                    }
                }
            }

            if (reaction.UserId != 504633036902498314)
            {
                //Turn page from help command

                //right (681843066104971287)
                //left (681842980134584355)
                if (reaction.Emote.ToString() == "<:right:681843066104971287>")
                {
                    var t       = reaction.Message.ToString();
                    var message = await channel.GetMessageAsync(reaction.MessageId);

                    var casted    = (IUserMessage)message;
                    var usedEmbed = casted.Embeds.First();
                    var pagenr    = usedEmbed.Title.Split("[")[1].Split("]")[0];

                    var currentNr = int.Parse(pagenr.Split("/")[0]);
                    var maxNr     = int.Parse(pagenr.Split("/")[1]);

                    if (currentNr >= maxNr)
                    {
                        return;
                    }

                    casted.ModifyAsync(msg =>
                                       msg.Embed = Help.GetHelpList(discordSocketClient, int.Parse(pagenr.Split("/").First())));
                }

                if (reaction.Emote.ToString() == "<:left:681842980134584355>")
                {
                    var t       = reaction.Message.ToString();
                    var message = await channel.GetMessageAsync(reaction.MessageId);

                    var casted    = (IUserMessage)message;
                    var usedEmbed = casted.Embeds.First();
                    var pagenr    = usedEmbed.Title.Split("[")[1].Split("]")[0];

                    var currentNr = int.Parse(pagenr.Split("/")[0]);

                    if (currentNr <= 0)
                    {
                        return;
                    }

                    casted.ModifyAsync(msg =>
                                       msg.Embed = Help.GetHelpList(discordSocketClient,
                                                                    int.Parse(pagenr.Split("/").First()) - 2));
                }
            }
        }
Пример #30
0
        async void CheckForNewLogs()
        {
            List <WowGuildAssociations> guildList    = null;
            List <LogMonitoring>        logWatchList = null;

            try
            {
                using (var db = new NinjaBotEntities())
                {
                    guildList    = db.WowGuildAssociations.ToList();
                    logWatchList = db.LogMonitoring.ToList();
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine($"Error getting guild/logwatch list -> [{ex.Message}]");
            }
            if (guildList != null)
            {
                foreach (var guild in guildList)
                {
                    try
                    {
                        var watchGuild = logWatchList.Where(w => w.ServerId == guild.ServerId).FirstOrDefault();
                        if (watchGuild != null)
                        {
                            if (watchGuild.MonitorLogs)
                            {
                                List <Reports> logs = null;
                                if (!string.IsNullOrEmpty(guild.LocalRealmSlug))
                                {
                                    logs = await GetReportsFromGuild(guildName : guild.WowGuild, locale : guild.Locale, realm : guild.WowRealm.Replace("'", ""), realmSlug : guild.LocalRealmSlug, region : guild.WowRegion, isList : true);
                                }
                                else if (!string.IsNullOrEmpty(guild.Locale))
                                {
                                    logs = await GetReportsFromGuild(guildName : guild.WowGuild, realm : guild.WowRealm.Replace("'", ""), region : guild.WowRegion, isList : true, locale : guild.Locale);
                                }
                                else
                                {
                                    logs = await GetReportsFromGuild(guildName : guild.WowGuild, realm : guild.WowRealm.Replace("'", ""), region : guild.WowRegion, isList : true);
                                }
                                if (logs != null)
                                {
                                    var      latestLog = logs[0];
                                    DateTime startTime = UnixTimeStampToDateTime(latestLog.start);
                                    if (latestLog.id != watchGuild.ReportId)
                                    {
                                        using (var db = new NinjaBotEntities())
                                        {
                                            var latestForGuild = db.LogMonitoring.Where(l => l.ServerId == guild.ServerId).FirstOrDefault();
                                            latestForGuild.LatestLog = startTime;
                                            latestForGuild.ReportId  = latestLog.id;
                                            await db.SaveChangesAsync();
                                        }
                                        ISocketMessageChannel channel = _client.GetChannel((ulong)watchGuild.ChannelId) as ISocketMessageChannel;
                                        if (channel != null)
                                        {
                                            var embed = new EmbedBuilder();
                                            embed.Title = $"New log found for [{guild.WowGuild}]!";
                                            StringBuilder sb = new StringBuilder();
                                            sb.AppendLine($"[__**{latestLog.title}** **/** **{latestLog.zoneName}**__]({latestLog.reportURL})");
                                            sb.AppendLine($"\t:timer: Start time: **{UnixTimeStampToDateTime(latestLog.start)}**");
                                            //sb.AppendLine($"\tLink: ***");
                                            sb.AppendLine($"\t:mag: [WoWAnalyzer](https://wowanalyzer.com/report/{latestLog.id}) | :sob: [WipeFest](https://www.wipefest.net/report/{latestLog.id}) ");
                                            sb.AppendLine();
                                            embed.Description = sb.ToString();
                                            embed.WithColor(new Color(0, 0, 255));
                                            await channel.SendMessageAsync("", false, embed);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine($"Error checking for logs [{guild.WowGuild}]:[{guild.WowRealm}]:[{guild.WowRealm}]! -> [{ex.Message}]");
                    }
                }
            }
        }