Ejemplo n.º 1
0
        public async Task NewMessageSetup(IMessageChannel channel, ulong messageId, string description = "")
        {
            if (_reactRoleService.IsPreparingMessage)
            {
                await ReplyAsync("A message is already being prepared, please finish.");
            }
            else
            {
                var linkedMessage = await channel.GetMessageAsync(messageId);

                if (linkedMessage == null)
                {
                    await ReplyAsync($"Message ID \"{messageId}\" passed in does not exist");

                    return;
                }

                _reactRoleService.NewMessage = new UserReactMessage
                {
                    ChannelId   = channel.Id,
                    Description = description,
                    MessageId   = messageId
                };
                await ReplyAsync(
                    $"Setup began, Reaction roles will be attached to {linkedMessage.GetJumpUrl()}");
                await ReplyAsync(
                    "Use `ReactRole Emote` \"Role\" \"Emoji\" \"Name (optional)\" to add emotes.");
            }
        }
Ejemplo n.º 2
0
        private async Task QuoteMessage(IMessageChannel channel, ulong id)
        {
            var message = await channel.GetMessageAsync(id);

            var builder = new EmbedBuilder()
                          .WithColor(new Color(200, 128, 128))
                          .WithTimestamp(message.Timestamp)
                          .WithFooter(footer =>
            {
                footer
                .WithText($"In channel {message.Channel.Name}");
            })
                          .WithAuthor(author =>
            {
                author
                .WithName(message.Author.Username)
                .WithIconUrl(message.Author.GetAvatarUrl());
            })
                          .AddField("Original message", message.Content);
            var embed = builder.Build();

            await ReplyAsync("", false, embed);

            await Task.Delay(1000);

            await Context.Message.DeleteAsync();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Clean up a channel
        /// </summary>
        /// <param name="channel">The channel to clean up</param>
        private async static void Clean(IMessageChannel channel)
        {
            // Remove all announcements that have expired from both the channel and the config (where necessary)
            var          announcements = Config.Instance.ChannelConfigs.Where(x => x.ChannelId == channel.Id).Single().ChannelData.Announcements;
            List <ulong> toRemove      = new List <ulong>();

            foreach (var a in announcements)
            {
                var message = await channel.GetMessageAsync(a.Key);

                if (message == null)
                {
                    toRemove.Add(a.Key);
                }
                else
                {
                    if (a.Value < DateTime.Now)
                    {
                        List <IMessage> toDelete = new List <IMessage>();
                        toDelete.Add(message);
                        await channel.DeleteMessagesAsync(toDelete);

                        toRemove.Add(a.Key);
                    }
                }
            }
            foreach (var remove in toRemove)
            {
                announcements.Remove(remove);
            }
            Config.Instance.Write();
        }
Ejemplo n.º 4
0
        private Task ReadyAsync()
        {
            //Console.WriteLine($"{_client.CurrentUser} is connected!");
            bool            msgFound = false;
            SocketGuild     guild    = _client.GetGuild(Convert.ToUInt64(_config.discordGuildID));
            IMessageChannel channel  = guild.GetChannel(Convert.ToUInt64(_config.discordChannelID)) as IMessageChannel;

            if (_config.discordMessageID != null)
            {
                Task <IMessage> msg = channel.GetMessageAsync(Convert.ToUInt64(_config.discordMessageID));
                msg.Wait();
                IUserMessage mesg = msg.Result as IUserMessage;
                if (mesg != null)
                {
                    msgFound = true;
                    mesg.ModifyAsync(x => x.Content = _message);
                }
            }
            if (_config.discordMessageID == null || !msgFound)
            {
                Task <IUserMessage> msg = channel.SendMessageAsync(_message);
                msg.Wait();
                IUserMessage mesg = msg.Result;
                _config.setDiscordMessageNumber(Convert.ToString(mesg.Id));
                _config.saveData();
            }

            Environment.Exit(0);
            return(Task.CompletedTask);
        }
        public async Task Edit(IMessageChannel channel, ulong messageId, [Remainder] string text)
        {
            if (string.IsNullOrWhiteSpace(text) || channel == null)
            {
                return;
            }

            var imsg = await channel.GetMessageAsync(messageId).ConfigureAwait(false);

            if (!(imsg is IUserMessage msg) || imsg.Author.Id != Context.Client.CurrentUser.Id)
            {
                return;
            }

            var rep = new ReplacementBuilder()
                      .WithDefault(Context)
                      .Build();

            if (CREmbed.TryParse(text, out var crembed))
            {
                rep.Replace(crembed);
                await msg.ModifyAsync(x => {
                    x.Embed   = crembed.ToEmbedBuilder().Build();
                    x.Content = crembed.PlainText?.SanitizeMentions() ?? "";
                }).ConfigureAwait(false);
            }
            else
            {
                await msg.ModifyAsync(x => x.Content = text.SanitizeMentions())
                .ConfigureAwait(false);
            }
        }
Ejemplo n.º 6
0
        public static async Task DeleteMessage(ulong guildId, ulong channelId, ulong messageId)
        {
            IGuild          guild   = null;
            IMessageChannel channel = null;

            if (guildId != 0 && channelId != 0)
            {
                guild = Program.client.GetGuild(guildId);

                if (guild != null)
                {
                    try
                    {
                        var messages = new List <IMessage>();
                        channel = (IMessageChannel)await guild.GetChannelAsync(channelId);

                        messages.Add(await channel.GetMessageAsync(messageId));
                        await channel.DeleteMessagesAsync(messages);
                    }
                    catch (Exception ex)
                    {
                        channel = null;
                    }
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Checks to see if there is an existing tsv file;
        /// and if so, checks if it is valid and the last saved message exists.
        /// (Note the possible thrown ValidationException).
        /// </summary>
        /// <returns>Null if does not exist. The IMessage of the last saved message if exists.</returns>
        /// <exception cref="ValidationException">Thrown upon invalid file (wrong header, message ID invalid, etc).</exception>
        private async Task <IMessage> CheckExisting()
        {
            string tsvPath = Path.Join(_path, WriterThread.TSV_FILE_NAME);

            if (!File.Exists(tsvPath))
            {
                return(null);
            }

            using (StreamReader stream = new StreamReader(tsvPath))
                using (CsvReader csv = new CsvReader(stream, WriterThread.CSV_CONFIG))
                {
                    string tsvChronPath = Path.Join(_path, TSV_CHRON);
                    if (File.Exists(tsvChronPath))
                    {
                        throw new FieldValidationException(csv.Context, $"{tsvChronPath} exists.");
                    }

                    csv.Read();                                               // advance to beginning of file
                    CsvMessage csvMsg = csv.GetRecords <CsvMessage>().Last(); // expensive?
                    IMessage   msg    = await _channel.GetMessageAsync(csvMsg.Id);

                    if (msg == null)
                    {
                        throw new FieldValidationException(csv.Context, $"Discord message {csvMsg.Id} not found in channel.");
                    }

                    return(msg);
                }
        }
Ejemplo n.º 8
0
        public static async Task SetOfflineStream(ulong guildId, string offlineMessage, ulong channelId, ulong messageId)
        {
            IGuild          guild   = null;
            IMessageChannel channel = null;

            if (guildId != 0 && channelId != 0)
            {
                guild = Program.client.GetGuild(guildId);

                if (guild != null)
                {
                    try
                    {
                        channel = (IMessageChannel)await guild.GetChannelAsync(channelId);

                        var message = (IUserMessage)await channel.GetMessageAsync(messageId);

                        await message.ModifyAsync(m => m.Content += offlineMessage);
                    }
                    catch (Exception ex)
                    {
                        channel = null;
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public async Task <bool> HandleMessageUpdatedAsync(IMessageChannel channel, IMessage updatedMessage, Lazy <Task <IMessage> > freshMessageFactory)
        {
            try
            {
                var newMessage = await freshMessageFactory.Value;
                var(success, _, commandArgs) = await VoteService.TryMatchVoteCommand(newMessage);

                if (success)
                {
                    // newMessage has Reactions.Count == 0, always
                    var freshMessage = await channel.GetMessageAsync(newMessage.Id);

                    if (freshMessage is IUserMessage freshUserMessage)
                    {
                        await VoteService.ProcessVoteCommandAsync(freshUserMessage, commandArgs);
                    }

                    return(true);
                }
                else
                {
                    await VoteService.DeleteAssociatedVoteReplyIfExistsAsync(channel, newMessage.Id);
                }
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Could not process updated message {0} in channel {1}", updatedMessage.Id, channel);
            }

            return(false);
        }
Ejemplo n.º 10
0
        public async Task Qu(ulong id, IMessageChannel ch = null)
        {
            #region Grab messages
            IMessage m;
            if (ch == null)
            {
                m = await Context.Channel.GetMessageAsync(id);
            }
            else
            {
                m = await ch.GetMessageAsync(id);
            }
            #endregion

            if (m == null)
            {
                await ReplyAsync("Sorry, I couldn't find the specified message."); return;
            }

            await Context.Message.DeleteAsync();

            var eb = BuildQuote(m);
            if (eb == null)
            {
                await ReplyAsync("Sorry, this message cannot be quoted."); return;
            }

            await Context.Channel.SendMessageAsync(Context.User.Mention + " quoted the following message:",
                                                   embed : eb.Build());
        }
Ejemplo n.º 11
0
        public static async Task <IMessage> GetMessageAsync(ulong uid, IMessageChannel chan)
        {
            IMessage msg;

            if (uid != 0)
            {
                msg = await chan.GetMessageAsync(uid);

                if (msg != null)
                {
                    return(msg);
                }
            }
            if (chan is not ITextChannel textChan || uid == 0)
            {
                return(null);
            }
            foreach (ITextChannel c in await textChan.Guild.GetTextChannelsAsync())
            {
                try
                {
                    msg = await c.GetMessageAsync(uid);

                    if (msg != null)
                    {
                        return(msg);
                    }
                }
                catch (Discord.Net.HttpException)
                { }
            }
            return(null);
        }
Ejemplo n.º 12
0
        public async Task PinMessage([Summary("The ID of the message to pin.")] string messageId, [Remainder, Summary("The ID of the channel the message is in.")] IMessageChannel channel)
        {
            List <ulong> allowedChannels = new List <ulong>()
            {
                681270126657798295, 681273506964701222, 143149937247387649, 448202199852646431
            };

            if (Xml.CommandAllowed("pin", Context) && allowedChannels.Contains(channel.Id))
            {
                if (channel == null)
                {
                    channel = (ITextChannel)Context.Channel;
                }
                var msg = await channel.GetMessageAsync(Convert.ToUInt64(messageId));

                try
                {
                    var pinChannel = await Context.Guild.GetTextChannelAsync(JackFrostBot.UserSettings.Channels.PinsChannelId(Context.Guild.Id));

                    var embed = Embeds.Pin((IGuildChannel)Context.Channel, msg, Context.Message.Author);
                    await pinChannel.SendMessageAsync("", embed : embed).ConfigureAwait(false);
                }
                catch
                {
                    await Context.Channel.SendMessageAsync("Could not find referenced message in the specified channel.");
                }
            }
        }
Ejemplo n.º 13
0
        public async Task Unsign(ulong userID, IMessageChannel channel)
        {
            var signups = _map.GetService <SignupsData>();

            //var user = _client.GetUser(userID);

            if (signups.Missions.Any(x => x.SignupChannel == channel.Id))
            {
                var mission = signups.Missions.Single(x => x.SignupChannel == channel.Id);

                Console.WriteLine($"[{DateTime.Now.ToString()}] {userID} removed from mission {channel.Name} by {Context.User.Username}");

                await mission.Access.WaitAsync(-1);

                try
                {
                    foreach (var team in mission.Teams)
                    {
                        var teamMsg = await channel.GetMessageAsync(team.TeamMsg) as IUserMessage;

                        var embed = teamMsg.Embeds.Single();

                        if (team.Slots.Any(x => x.Signed.Contains(userID)))
                        {
                            team.Slots.Single(x => x.Signed.Contains(userID)).Signed.Remove(userID);
                            mission.SignedUsers.Remove(userID);

                            var newDescription = MiscHelper.BuildTeamSlots(team);

                            var newEmbed = new EmbedBuilder
                            {
                                Title = embed.Title,
                                Color = embed.Color
                            };

                            if (newDescription.Count == 2)
                            {
                                newEmbed.WithDescription(newDescription[0] + newDescription[1]);
                            }
                            else if (newDescription.Count == 1)
                            {
                                newEmbed.WithDescription(newDescription[0]);
                            }

                            if (embed.Footer.HasValue)
                            {
                                newEmbed.WithFooter(embed.Footer.Value.Text);
                            }

                            await teamMsg.ModifyAsync(x => x.Embed = newEmbed.Build());
                        }
                    }
                }
                finally
                {
                    mission.Access.Release();
                }
            }
        }
Ejemplo n.º 14
0
        private async Task QuoteMessage(ulong id, string subtitle = null, IMessageChannel channel = null)
        {
            if (subtitle != null && (subtitle.Contains("@everyone") || subtitle.Contains("@here")))
            {
                return;
            }
            //If the channel is null, use the message context's channel.
            channel = channel ?? Context.Channel;

            //Find the message that was requested and make a link.
            IMessage message = await channel.GetMessageAsync(id);

            string messageLink = "https://discordapp.com/channels/" + Context.Guild.Id + "/"
                                 + (channel == null ? Context.Channel.Id : channel.Id) + "/" + id;

            //Build an embed which contains the quote
            EmbedBuilder builder = new EmbedBuilder()
            {
                Color     = new Color(200, 128, 128),
                Timestamp = message.Timestamp,

                Footer = new EmbedFooterBuilder()
                {
                    Text = $"In channel {message.Channel.Name}"
                },

                Title = new EmbedBuilder()
                {
                    Title = "Linkback",
                    Url   = messageLink
                }.ToString(),

                         Author = new EmbedAuthorBuilder()
                {
                    Name    = message.Author.Username,
                    IconUrl = message.Author.GetAvatarUrl()
                }
            };

            //Add the original message
            builder.AddField("Original Message:", message.Content.Truncate(1024));

            //Add a subtitle if one was given
            string subtitleText = null;

            if (subtitle != null)
            {
                subtitleText = $"{Context.User.Username}: {subtitle}";
                builder.AddField($"{Context.User.Username}: ", subtitle);
            }

            //Build, and send the embed in a message.
            Embed embed = builder.Build();

            await ReplyAsync(subtitleText, false, embed);

            //Delete the requesters command
            await Context.Message.DeleteAsync();
        }
Ejemplo n.º 15
0
        public async Task QuoteMessage(ulong messageId, IMessageChannel channel = null)
        {
            // If channel is null use Context.Channel, else use the provided channel
            channel ??= Context.Channel;
            var message = await channel.GetMessageAsync(messageId);

            if (message == null)
            {
                await Context.Message.DeleteAfterSeconds(seconds : 1);
                await ReplyAsync("No message with that id found.").DeleteAfterSeconds(seconds: 4);

                return;
            }
            if (message.Author.IsBot) // Can't imagine we need to quote the bots
            {
                await Context.Message.DeleteAfterSeconds(seconds : 2);

                return;
            }

            var messageLink = "https://discordapp.com/channels/" + Context.Guild.Id + "/" + channel.Id + "/" + messageId;
            var msgContent  = message.Content == string.Empty ? "" : message.Content.Truncate(1020);

            var msgAttachment = string.Empty;

            if (message.Attachments?.Count > 0)
            {
                msgAttachment = "\t📸";
            }
            var builder = new EmbedBuilder()
                          .WithColor(new Color(200, 128, 128))
                          .WithTimestamp(message.Timestamp)
                          .WithFooter(footer =>
            {
                footer
                .WithText($"Quoted by {Context.User.Username}#{Context.User.Discriminator} • From channel {message.Channel.Name}")
                .WithIconUrl(Context.User.GetAvatarUrl());
            })
                          .WithAuthor(author =>
            {
                author
                .WithName(message.Author.Username)
                .WithIconUrl(message.Author.GetAvatarUrl());
            });

            if (msgContent == string.Empty && msgAttachment != string.Empty)
            {
                msgContent = "📸";
            }

            msgContent         += $"\n\n***[Linkback]({messageLink})***";
            builder.Description = msgContent;

            await ReplyAsync(embed : builder.Build());

            await Context.Message.DeleteAfterSeconds(1.0);
        }
Ejemplo n.º 16
0
        public async Task <IMessage> GetCloseMessage(ulong userId, IMessageChannel chan)
        {
            string closeMsg = await GetCloseMessageId(userId, chan);

            if (closeMsg == "0")
            {
                return(null);
            }
            return(await chan.GetMessageAsync(ulong.Parse(closeMsg)));
        }
Ejemplo n.º 17
0
        Task HandleReactionAsync(IMessageChannel channel,
                                 SocketReaction reaction,
                                 ReactionEvent eventType)
        {
            if (reaction.UserId != _discord.CurrentUser.Id)
            {
                _ = Task.Run(async() =>
                {
                    // retrieve message
                    if (!(await channel.GetMessageAsync(reaction.MessageId) is IUserMessage message))
                    {
                        return;
                    }

                    // retrieve user
                    if (!(await channel.GetUserAsync(reaction.UserId) is IUser user))
                    {
                        return;
                    }

                    // create context
                    var context = new ReactionContext
                    {
                        Client        = _discord,
                        Message       = message,
                        User          = user,
                        GuildSettings = _guildSettingsCache[message.Channel],
                        Reaction      = reaction,
                        Event         = eventType
                    };

                    try
                    {
                        foreach (var handler in _reactionHandlers)
                        {
                            if (await handler.TryHandleAsync(context))
                            {
                                HandledReactions.Increment();
                                break;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        await _errorReporter.ReportAsync(e, context, false);
                    }
                    finally
                    {
                        ReceivedReactions.Increment();
                    }
                });
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 18
0
        public async Task EditAnnouncement(string title = null, string message = null, [Remainder, Summary("Optional message id to edit")] ulong id = 0)
        {
            await Log.LogMessage(Context);

            if (await Permissions.IsWarlord(Context) == false)
            {
                throw new UnauthorizedAccessException();
            }
            if (title == null)
            {
                await ReplyAsync("Please provide a title"); return;
            }
            if (message == null)
            {
                await ReplyAsync("Please provide a message"); return;
            }

            IMessageChannel channel = await Channel.GetChannel(Context, "announcements");

            IUserMessage umessage = null;

            if (id == 0)
            {
                IEnumerable <IMessage> messages = await channel.GetMessagesAsync(1).Flatten();

                foreach (IMessage msg in messages)
                {
                    umessage = (IUserMessage)await channel.GetMessageAsync(msg.Id); break;
                }
            }
            else
            {
                umessage = (IUserMessage)await channel.GetMessageAsync(id);
            }

            if (umessage != null)
            {
                await umessage.ModifyAsync(x => x.Content = Message.FormatAnnouncementMessage(Context, title, message));
                await ReplyAsync("Announcement modified, please verify the result"); return;
            }
        }
Ejemplo n.º 19
0
        private async Task ReadyAsync()
        {
            foreach (IGuild guild in Client.Guilds)
            {
                await OnLogAsync(LogSeverity.Info, Name, $"Joined {guild.Name} ({guild.Id})");
            }

            if (restartChannel != null && restartMessage != null)
            {
                ulong restartMessageId = restartMessage.Id;
                ulong restartChannelId = restartChannel.Id;

                // Attempt to get the channel the bot was restarted from.

                restartChannel = Client.GetChannel(restartChannelId) as IMessageChannel;

                if (restartChannel is null)
                {
                    restartChannel = await Client.GetDMChannelAsync(restartChannelId) as IMessageChannel;
                }

                // Attempt to get the confirmation message.

                if (restartChannel != null)
                {
                    restartMessage = await restartChannel.GetMessageAsync(restartMessageId) as IUserMessage;
                }
                else
                {
                    restartMessage = null;
                }

                if (restartMessage != null)
                {
                    // Modify the confirmation message.

                    await restartMessage.ModifyAsync(async m => {
                        m.Embed = EmbedUtilities.BuildSuccessEmbed($"Restarting {Name.ToBold()}... and we're back!").ToDiscordEmbed();

                        await Task.CompletedTask;
                    });
                }
            }

            restartChannel = null;
            restartMessage = null;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Sends a file to this message channel with an optional caption, then adds it to the command cache.
        /// </summary>
        /// <param name="channel">The source channel.</param>
        /// <param name="cache">The command cache that the messages should be added to.</param>
        /// <param name="commandId">The ID of the command message.</param>
        /// <param name="stream">The <see cref="Stream" /> of the file to be sent.</param>
        /// <param name="filename">The name of the attachment.</param>
        /// <param name="text">The message to be sent.</param>
        /// <param name="isTTS">Whether the message should be read aloud by Discord or not.</param>
        /// <param name="embed">The <see cref="EmbedType.Rich"/> <see cref="Embed"/> to be sent.</param>
        /// <param name="options">The options to be used when sending the request.</param>
        /// <param name="isSpoiler">Whether the message attachment should be hidden as a spoiler.</param>
        /// <param name="allowedMentions">
        /// Specifies if notifications are sent for mentioned users and roles in the message <paramref name="text"/>. If <c>null</c>, all mentioned roles and users will be notified.
        /// </param>
        /// <returns>A task that represents an asynchronous send operation for delivering the message. The task result contains the sent message.</returns>
        public static async Task <IUserMessage> SendCachedFileAsync(this IMessageChannel channel, CommandCacheService cache, ulong commandId, Stream stream, string filename,
                                                                    string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null)
        {
            IUserMessage response;
            bool         found = cache.TryGetValue(commandId, out ulong responseId);

            if (found && (response = (IUserMessage)await channel.GetMessageAsync(responseId)) != null)
            {
                await response.DeleteAsync();
            }

            response = await channel.SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions);

            cache.Add(commandId, response.Id);

            return(response);
        }
Ejemplo n.º 21
0
        private async Task QuoteMessage(ulong id, string subtitle = null, IMessageChannel channel = null)
        {
            // If channel is null use Context.Channel, else use the provided channel
            channel = channel ?? Context.Channel;


            var message = await channel.GetMessageAsync(id);

            string messageLink = "https://discordapp.com/channels/" + Context.Guild.Id + "/" + (channel == null
                                     ? Context.Channel.Id
                                     : channel.Id) + "/" + id;


            var builder = new EmbedBuilder()
                          .WithColor(new Color(200, 128, 128))
                          .WithTimestamp(message.Timestamp)
                          .WithFooter(footer =>
            {
                footer
                .WithText($"In channel {message.Channel.Name}");
            })
                          .WithTitle("Linkback")
                          .WithUrl(messageLink)
                          .WithAuthor(author =>
            {
                author
                .WithName(message.Author.Username)
                .WithIconUrl(message.Author.GetAvatarUrl());
            })
                          .AddField("Original message", message.Content.Truncate(1020));

            if (subtitle != null)
            {
                builder.AddField($"{Context.User.Username}: ", subtitle);
            }

            var embed = builder.Build();

            await ReplyAsync((subtitle == null)? "" : $"*{Context.User.Username}:* {subtitle}", false, embed);

            await Task.Delay(1000);

            await Context.Message.DeleteAsync();
        }
Ejemplo n.º 22
0
        async Task ClosePoll(IMessageChannel channel, ulong messageId, params string[] additionalNotes)
        {
            string additionalNote = String.Join(' ', additionalNotes);
            var    message        = (IUserMessage)await channel.GetMessageAsync(messageId);

            var reactions = message.Reactions;

            string reactionCount = "";

            foreach (var reaction in reactions)
            {
                reactionCount += $" {reaction.Key.Name} ({reaction.Value.ReactionCount})";
            }

            await message.ModifyAsync((properties) =>
            {
                properties.Content = message.Content +
                                     $"\n\nThe poll has been closed. Here's the vote results :{reactionCount}\nAdditional notes : {additionalNote}";
            });
        }
Ejemplo n.º 23
0
        public static async Task <IMessage> GetMessage(string id, IMessageChannel chan)
        {
            ulong uid;

            if (!ulong.TryParse(id, out uid))
            {
                return(null);
            }
            IMessage msg;

            if (uid != 0)
            {
                msg = await chan.GetMessageAsync(uid);

                if (msg != null)
                {
                    return(msg);
                }
            }
            ITextChannel textChan = chan as ITextChannel;

            if (textChan == null || uid == 0)
            {
                return(null);
            }
            foreach (ITextChannel c in await textChan.Guild.GetTextChannelsAsync())
            {
                try
                {
                    msg = await c.GetMessageAsync(uid);

                    if (msg != null)
                    {
                        return(msg);
                    }
                }
                catch (Discord.Net.HttpException)
                { }
            }
            return(null);
        }
Ejemplo n.º 24
0
        protected async Task <bool> InitMessage(IMessageChannel channel, ulong msgId, string[] footer, bool checkLen = true)
        {
            try
            {
                _msg = await channel.GetMessageAsync(msgId) as RestUserMessage;
            }
            catch
            {
                await ReplyAsync(database["string", "errParseMsgId"]);
            }
            if (_msg == null)
            {
                await ReplyAsync(database["string", "errMsgNotFound"]);

                return(false);
            }
            if (_msg.Embeds.Count != 1)
            {
                await ReplyAsync(database["string", "errMsgNotValid"]);

                return(false);
            }
            _oldEmbed = _msg.Embeds.ElementAt(0);
            //don't run this on delete or move
            if (_oldEmbed.Fields.Length >= 20 && checkLen)
            {
                await ReplyAsync(database["string", "errTooManyFields"]);

                return(false);
            }
            if (!footer.Contains(_oldEmbed.Footer.Value.ToString()))
            {
                await ReplyAsync(database["string", "errMsgNotValid"]);
            }
            return(true);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Int 0 is to modify the message, int 1 is to send a new message
        /// </summary>
        public static async Task NotificationControlAsync(ulong messageid, ulong channelid, string msg, int status,
                                                          int num = 0)
        {
            try
            {
                if (num == 0)
                {
                    IMessageChannel channel    = (IMessageChannel)KKK.Client.GetChannel(channelid);
                    IUserMessage    themessage = (IUserMessage)await channel.GetMessageAsync(messageid);

                    await themessage.ModifyAsync(msgProperty => { msgProperty.Embed = Embed(msg, status); });
                }
                else if (num == 1)
                {
                    IMessageChannel channel = (IMessageChannel)KKK.Client.GetChannel(channelid);

                    await channel.SendMessageAsync(null, false, Embed(msg, status));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Tries to delete a message.
        /// </summary>
        /// <param name="channel">The source channel.</param>
        /// <param name="message">The message.</param>
        public static async Task <bool> TryDeleteMessageAsync(this IMessageChannel channel, IMessage message)
        {
            message = await channel.GetMessageAsync(message.Id);

            return(await message.TryDeleteAsync());
        }
Ejemplo n.º 27
0
        private async Task DisplayAdventure(Adventure adventure)
        {
            try
            {
                // Get the channel for this adventure..
                IMessageChannel channel = DiscordSocketClient.GetChannel(adventure.Channel) as IMessageChannel;

                // Get all players associated with this adventure.
                IEnumerable <Player> players = await PlayersRepository.GetAdventuringPlayersAsEnumerable(adventure.Id);

                // Get the adventureMessage that we will update.
                IUserMessage adventureMessage;
                // If we were passed the "RegenerateMessages" flag set to true, or if there is no Adventure Message, then create a new adventureMessage.
                if (adventure.RegenerateMessage || adventure.AdventureMessage == 0)
                {
                    adventureMessage = await channel.SendMessageAsync("<ADVENTURE MESSAGE>") as IUserMessage;
                }
                // If we were passed the "RegenerateMessages" flag set to false, then retrieve the existing adventureMessage.
                else
                {
                    adventureMessage = await channel.GetMessageAsync(adventure.AdventureMessage) as IUserMessage;
                }

                // Alter the messages to now have new status updates.
                EmbedBuilder embedBuilder = new EmbedBuilder();

                embedBuilder.Color = Color.Blue;

                TimeSpan timePassed      = DateTime.UtcNow - adventure.StartTime;
                string   adventureHeader = $"ADVENTURE - {timePassed.ToString(@"mm\:ss")}";
                embedBuilder.Title = adventureHeader;

                List <string> frontlinePlayers = new List <string>();
                List <string> midlinePlayers   = new List <string>();
                List <string> backlinePlayers  = new List <string>();

                foreach (Player player in players)
                {
                    double healthTicksRaw = player.Health / (double)player.MaxHealth;
                    int    healthTicks    = 0;
                    for (int i = 1; i < BarDisplaySize + 1; i++)
                    {
                        if (healthTicksRaw < (i / (double)BarDisplaySize))
                        {
                            break;
                        }
                        healthTicks += 1;
                    }

                    string healthBar = "[";
                    for (int i = 0; i < healthTicks; i++)
                    {
                        healthBar += "+";
                    }
                    for (int i = 0; i < BarDisplaySize - healthTicks; i++)
                    {
                        healthBar += "-";
                    }
                    healthBar += "]";

                    double manaTicksRaw = player.Mana / (double)Player.MaxMana;
                    int    manaTicks    = 0;
                    for (int i = 1; i < BarDisplaySize + 1; i++)
                    {
                        if (manaTicksRaw < (i / (double)BarDisplaySize))
                        {
                            break;
                        }
                        manaTicks += 1;
                    }
                    string manaBar = "[";
                    for (int i = 0; i < manaTicks; i++)
                    {
                        manaBar += "+";
                    }
                    for (int i = 0; i < BarDisplaySize - manaTicks; i++)
                    {
                        manaBar += "-";
                    }
                    manaBar += "]";

                    string display = $"<@{player.Id}> ({player.Class}) \n HP {player.Health}/{player.MaxHealth} {healthBar} \n MP {player.Mana}/{Player.MaxMana} {manaBar}";

                    switch (player.AdventureRank)
                    {
                    case Adventure.Rank.Frontline:
                        frontlinePlayers.Add(display);
                        break;

                    case Adventure.Rank.Midline:
                        midlinePlayers.Add(display);
                        break;

                    case Adventure.Rank.Backline:
                        backlinePlayers.Add(display);
                        break;

                    default:
                        throw new Exception("Invalid Rank!");
                    }
                }

                string frontlinePlayerField = string.Join("\n\n", frontlinePlayers.ToArray());
                if (string.IsNullOrEmpty(frontlinePlayerField))
                {
                    frontlinePlayerField = "<No Players>";
                }

                string midlinePlayerField = string.Join("\n\n", midlinePlayers.ToArray());
                if (string.IsNullOrEmpty(midlinePlayerField))
                {
                    midlinePlayerField = "<No Players>";
                }

                string backlinePlayerField = string.Join("\n\n", backlinePlayers.ToArray());
                if (string.IsNullOrEmpty(backlinePlayerField))
                {
                    backlinePlayerField = "<No Players>";
                }

                embedBuilder.AddField("Player Frontline", frontlinePlayerField);
                embedBuilder.AddField("Player Midline", midlinePlayerField);
                embedBuilder.AddField("Player Backline", backlinePlayerField);
                embedBuilder.AddField("\u200b", "\u200b");

                string adventureLog = string.Join("\n", (adventure.Logs ?? new List <string>()).ToArray());
                if (string.IsNullOrEmpty(adventureLog))
                {
                    adventureLog = "<No Logs>";
                }

                embedBuilder.AddField("Adventure Log", adventureLog);

                await adventureMessage.ModifyAsync(m =>
                {
                    m.Content = "";
                    m.Embed   = embedBuilder.Build();
                });

                // If we were passed the "RegenerateMessages" flag set to true, or if there was no AdventureMessage, then delete old adventureMessage if possible.
                // Then, toggle the "RegenerateMessages" flag to false, and set the new adventureMessage on the Adventure.
                if (adventure.RegenerateMessage || adventure.AdventureMessage == 0)
                {
                    if (adventure.AdventureMessage != 0)
                    {
                        await channel.DeleteMessageAsync(await channel.GetMessageAsync(adventure.AdventureMessage));
                    }

                    await AdventuresRepository.SetNewChannelsForMessages
                    (
                        adventureId : adventure.Id,
                        adventureMessage : adventureMessage.Id
                    );
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public async void Launch(IMessageChannel channel, SocketGuild guild)
        {
            if (cts != null && !cts.IsCancellationRequested)
            {
                return;
            }

            await channel.SendMessageAsync("Служба оповещения включена");

            cts = new CancellationTokenSource();
            var regex = new Regex("\\d\\d.-...");

            groups = guild.Roles
                     .Where(it => regex.IsMatch(it.Name));
            var sch = (await repository.GetAllSchedules())?.Filter(groups: this.groups.Select(it => it.Name));

            lock (key)
            {
                this.schedule = sch;
            }
            if (schedule == null)
            {
                return;
            }
            ScheduleUpdater();

            var msgFromId = 0UL;
            var msgToId   = 0UL;
            var limit     = 0;

            while (true)
            {
                var currentTime = GetMoscowDateTime(DateTime.Now);
                Console.WriteLine("Сервис оповещения о расписании: " + currentTime.ToString());
                var shiftedTime         = currentTime.AddMinutes(10); // Get lesson 10 min before start
                var currentOrder        = Lesson.GetOrder(shiftedTime, false);
                var currentOrderEvening = Lesson.GetOrder(shiftedTime, true);

                var realIsStarted = Lesson.GetTime(currentOrder.Order, currentOrder.Evening).Item1 >=
                                    currentTime.TimeOfDay;
                var realIsStartedEvening = Lesson.GetTime(
                    currentOrderEvening.Order, currentOrderEvening.Evening
                    ).Item1 >= currentTime.TimeOfDay;



                var filteredLessons = schedule.GetSchedule(shiftedTime);
                filteredLessons = filteredLessons.Where(it =>
                                                        !it.GroupIsEvening && currentOrder.Started && realIsStarted && it.Order == currentOrder.Order ||
                                                        it.GroupIsEvening && currentOrderEvening.Started && realIsStartedEvening && it.Order == currentOrderEvening.Order
                                                        ).ToList();

                if (msgFromId != 0UL && msgToId != 0UL)
                {
                    var flag        = false;
                    var collections = channel.GetMessagesAsync(
                        msgToId, Direction.Before, limit: limit
                        );
                    await foreach (var col in collections)
                    {
                        foreach (var message in col)
                        {
                            if (message.Author.IsBot)
                            {
                                await message.DeleteAsync();

                                await Task.Delay(700);
                            }
                            if (message.Id == msgFromId)
                            {
                                flag = true;
                                break;
                            }
                        }

                        if (flag)
                        {
                            break;
                        }
                    }
                    await(await channel.GetMessageAsync(msgToId)).DeleteAsync();
                }
                else if (msgFromId != 0UL)
                {
                    await(await channel.GetMessageAsync(msgFromId)).DeleteAsync();
                }
                limit = 0;
                if (filteredLessons.Count != 0)
                {
                    msgFromId = (await channel.SendMessageAsync("Занятия через 10 минут")).Id;
                    limit     = filteredLessons.Count * 2 + 1;
                    foreach (var lesson in filteredLessons)
                    {
                        var mentions = string.Join(", ",
                                                   lesson.Groups
                                                   .Select(it =>
                        {
                            var q = groups.FirstOrDefault(role =>
                                                          role.Name.Equals(it.Title)
                                                          );
                            return(q?.Mention ?? string.Empty);
                        }
                                                           )
                                                   );
                        await channel.SendMessageAsync(mentions);

                        msgToId = (await ScheduleMessageUtils.SendLesson(channel, lesson, DateTime.Now)).Id;
                        await Task.Delay(700);
                    }
                }
                else
                {
                    msgFromId = (await channel.SendMessageAsync("Через 10 минут занятий нет")).Id;
                    msgToId   = 0UL;
                    Console.WriteLine($"Сейчас {currentOrder.Order + 1}-й занятие или " +
                                      $"{currentOrderEvening.Order + 1}-й занятие");
                }


                var timeToSleep = GetTimeToSleep(currentOrder, currentOrderEvening);

                Console.WriteLine("Следующее оповещение через " + timeToSleep.ToString());

                try
                {
                    await Task.Delay(timeToSleep, cts.Token);
                }
                catch (TaskCanceledException e)
                {
                    Console.WriteLine("Сервис оповещения о расписании остановлен: " + DateTime.Now.ToString());
                    await channel.SendMessageAsync("Служба оповещения остановлена");

                    return;
                }
            }
        }
Ejemplo n.º 29
0
        public async Task ReactionAddedMethod(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction)
        {
            //Test Values
            //ulong corporation = 326378973934256129;


            ulong corporation = 82021499682164736;

            IMessageChannel finalchannel = client.GetGuild(corporation).GetChannel(channel.Id) as IMessageChannel;
            IUserMessage    message      = await finalchannel.GetMessageAsync(cache.Id) as IUserMessage;

            if (reaction.Emote.Name.Contains("Drama") || reaction.Emote.Name.Contains("drama"))
            {
                try
                {
                    archive.InsertDrama(message);
                    await message.AddReactionAsync(new Emoji("\uD83D\uDC6E"));
                }
                catch (Exception ex)
                {
                    await finalchannel.SendMessageAsync(ex.Message);
                }
            }
            else if (reaction.Emote.Name.Contains("1INF"))
            {
                IGuildUser reactionuser = client.GetGuild(corporation).GetUser(reaction.UserId);
                IGuildUser messageuser  = client.GetGuild(corporation).GetUser(message.Author.Id);
                string     user1        = "";
                string     user2        = "";

                if (messageuser.Nickname != null)
                {
                    user1 = messageuser.Nickname;
                }
                else
                {
                    user1 = messageuser.Username;
                }


                if (reactionuser.Nickname != null)
                {
                    user2 = reactionuser.Nickname;
                }
                else
                {
                    user2 = reactionuser.Username;
                }


                SendHttpRequest request = new SendHttpRequest();

                await reactionuser.SendMessageAsync(request.SendInfluence(user2, user1, 1, "INFLUENCE"));
            }
            else if (reaction.Emote.Name.Contains("5INF"))
            {
                IGuildUser reactionuser = client.GetGuild(corporation).GetUser(reaction.UserId);
                IGuildUser messageuser  = client.GetGuild(corporation).GetUser(message.Author.Id);
                string     user1        = "";
                string     user2        = "";

                if (messageuser.Nickname != null)
                {
                    user1 = messageuser.Nickname;
                }
                else
                {
                    user1 = messageuser.Username;
                }


                if (reactionuser.Nickname != null)
                {
                    user2 = reactionuser.Nickname;
                }
                else
                {
                    user2 = reactionuser.Username;
                }


                SendHttpRequest request = new SendHttpRequest();

                await reactionuser.SendMessageAsync(request.SendInfluence(user2, user1, 5, "INFLUENCE"));
            }
            else if (reaction.Emote.Name.Contains("10INF"))
            {
                IGuildUser reactionuser = client.GetGuild(corporation).GetUser(reaction.UserId);
                IGuildUser messageuser  = client.GetGuild(corporation).GetUser(message.Author.Id);
                string     user1        = "";
                string     user2        = "";

                if (messageuser.Nickname != null)
                {
                    user1 = messageuser.Nickname;
                }
                else
                {
                    user1 = messageuser.Username;
                }


                if (reactionuser.Nickname != null)
                {
                    user2 = reactionuser.Nickname;
                }
                else
                {
                    user2 = reactionuser.Username;
                }


                SendHttpRequest request = new SendHttpRequest();

                await reactionuser.SendMessageAsync(request.SendInfluence(user2, user1, 10, "INFLUENCE"));
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Start a channel master for a specific channel in discord
        /// </summary>
        /// <param name="channelconfig">The representation of a channel in discord</param>
        /// <param name="channel">If you already have an instance of the channel master, you can pass it as a parameter</param>
        /// <returns>A bool depicting if the channel handler could be started</returns>
        public async static Task <bool> StartChannelMaster(ChannelConfig channelconfig, IMessageChannel channel = null)
        {
            // Try to get the channel object from  the channel id in the config
            if (channel == null)
            {
                channel = Client.GetChannel(channelconfig.ChannelId) as IMessageChannel;
            }
            else
            {
                channelconfig = Config.Instance.ChannelConfigs.Where(x => x.ChannelId == channel.Id).Single();
            }

            // Create a handler for each type of message the channel should be able to process
            var handlers = new List <IMessageHandler>
            {
                new WelcomeHandler(channelconfig),
                new AttendanceHandler(channelconfig),
                new BorderHandler(channelconfig),
                new ScheduleHandler(channelconfig),
                new AnnouncementHandler(channelconfig)
            };

            // If the client couldn't get the channel, return false
            if (channel == null)
            {
                Config.Instance.DeleteConfig(channelconfig);
            }

            // Get all the messages that have been posted to the channel, remove any that have been deleted
            Dictionary <CommandType, IUserMessage> postedMessages = new Dictionary <CommandType, IUserMessage>();

            if (channelconfig.ChannelData.PostedMessages == null)
            {
                channelconfig.ChannelData.PostedMessages = new Dictionary <CommandType, ulong>();
            }

            // Check if a message has been deleted
            List <CommandType> toRemove = new List <CommandType>();

            foreach (var m in channelconfig.ChannelData.PostedMessages)
            {
                IUserMessage userMessage = null;
                try
                {
                    userMessage = await channel.GetMessageAsync(m.Value) as IUserMessage;
                }
                catch (Exception) { }

                if (userMessage == null)
                {
                    toRemove.Add(m.Key);
                }
                else
                {
                    postedMessages.Add(m.Key, userMessage);
                }
            }
            foreach (var type in toRemove)
            {
                channelconfig.ChannelData.PostedMessages.Remove(type);
            }
            Config.Instance.Write();

            // If a handler doesn't have a message posted in the channel, post it's default message
            foreach (var h in handlers)
            {
                try
                {
                    if (postedMessages.Where(x => x.Key == h.MessageType).Count() == 0)
                    {
                        IUserMessage userMessage = await channel.SendMessageAsync(h.DefaultMessage());

                        postedMessages.Add(h.MessageType, userMessage);
                        channelconfig.ChannelData.PostedMessages.Add(h.MessageType, userMessage.Id);
                    }
                }
                catch (Exception) { }
            }
            Config.Instance.Write();

            // Start a channel handler
            ChannelMaster master = new ChannelMaster(Client.CurrentUser.Id, channel, handlers, postedMessages);

            ChannelMasters.Add(master);
            await Task.Run(() => master.Run());

            return(true);
        }