public MessageStub(DiscordMessage message, DiscordClient refer)
        {
            mainClientReference = refer;
            InitializeComponent();
            Message = message;
            RefreshContent();
#if DEBUG
            richTextBox.MouseDoubleClick += RichTextBox_MouseDoubleClick;
#endif
        }
Example #2
0
 private void SendDeleteRequest(DiscordMessage message)
 {
     string url;
     //if(!user)
     url = Endpoints.BaseAPI + Endpoints.Channels + $"/{message.channel.ID}" + Endpoints.Messages + $"/{message.ID}";
     //else
     //url = Endpoints.BaseAPI + Endpoints.Channels + $"/{message.channel.id}" + Endpoints.Messages + $"/{message.id}";
     try
     {
         var result = WebWrapper.Delete(url, token);
     }
     catch (Exception ex)
     {
         DebugLogger.Log($"Exception ocurred while deleting message (ID: {message.ID}): " + ex.Message, MessageLevel.Error);
     }
 }
Example #3
0
 /// <summary>
 /// Deletes a specified DiscordMessage.
 /// </summary>
 /// <param name="message"></param>
 public void DeleteMessage(DiscordMessage message)
 {
     SendDeleteRequest(message);
 }
Example #4
0
        public override async Task <(ISource source, string failReason)> FindHandlerAsync(DiscordMessage message, ICollection <IArchiveHandler> handlers)
        {
            if (string.IsNullOrEmpty(message.Content))
            {
                return(null, null);
            }

            var matches = ExternalLink.Matches(message.Content);

            if (matches.Count == 0)
            {
                return(null, null);
            }

            var client = new MegaApiClient();
            await client.LoginAnonymousAsync();

            foreach (Match m in matches)
            {
                try
                {
                    if (m.Groups["mega_link"].Value is string lnk &&
                        !string.IsNullOrEmpty(lnk) &&
                        Uri.TryCreate(lnk, UriKind.Absolute, out var uri))
                    {
                        var node = await client.GetNodeFromLinkAsync(uri).ConfigureAwait(false);

                        if (node.Type == NodeType.File)
                        {
                            var buf = bufferPool.Rent(1024);
                            try
                            {
                                int read;
                                using (var stream = await client.DownloadAsync(uri, doodad, Config.Cts.Token).ConfigureAwait(false))
                                    read = await stream.ReadBytesAsync(buf).ConfigureAwait(false);
                                foreach (var handler in handlers)
                                {
                                    var(canHandle, reason) = handler.CanHandle(node.Name, (int)node.Size, buf.AsSpan(0, read));
                                    if (canHandle)
                                    {
                                        return(new MegaSource(client, uri, node, handler), null);
                                    }
                                    else if (!string.IsNullOrEmpty(reason))
                                    {
                                        return(null, reason);
                                    }
                                }
                            }
                            finally
                            {
                                bufferPool.Return(buf);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Config.Log.Warn(e, $"Error sniffing {m.Groups["mega_link"].Value}");
                }
            }
            return(null, null);
        }
 public void RemoveMessage(DiscordMessage message)
 {
     MessageIDs.Remove(message.id);
     string oldText = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text.Replace(message.content, "");
 }
Example #6
0
 public async Task Quote(CommandContext ctx, [Description("Id of the message to quote")] DiscordMessage message)
 {
     await Service.Quote(ctx, message);
 }
Example #7
0
 public override async Task Execute(Bot bot, DiscordUser user, DiscordMessage message, string[] args)
 {
     var timeString = args[0];
     var removed    = bot.chronoEvents.ClearAtTime(timeString);
     await message.RespondAsync(removed? "Cleared time " + timeString : "Nothing to deregister");
 }
Example #8
0
        public static async Task <(string productCode, TitleInfo info)> LookupGameAsync(DiscordChannel channel, DiscordMessage message, string gameTitle)
        {
            var lastBotMessages = await channel.GetMessagesBeforeAsync(message.Id, 20, DateTime.UtcNow.AddSeconds(-30)).ConfigureAwait(false);

            foreach (var msg in lastBotMessages)
            {
                if (BotReactionsHandler.NeedToSilence(msg).needToChill)
                {
                    return(null, null);
                }
            }

            try
            {
                var requestBuilder = RequestBuilder.Start().SetSearch(gameTitle);
                var status         = await Client.GetCompatResultAsync(requestBuilder, Config.Cts.Token).ConfigureAwait(false);

                if ((status.ReturnCode == 0 || status.ReturnCode == 2) && status.Results.Any())
                {
                    var(code, info, score) = status.GetSortedList().First();
                    Config.Log.Debug($"Looked up \"{gameTitle}\", got \"{info?.Title}\" with score {score}");
                    if (score < 0.51)
                    {
                        return(null, null);
                    }

                    if (!string.IsNullOrEmpty(info?.Title))
                    {
                        StatsStorage.GameStatCache.TryGetValue(info.Title, out int stat);
                        StatsStorage.GameStatCache.Set(info.Title, ++stat, StatsStorage.CacheTime);
                    }

                    return(code, info);
                }
            }
            catch (Exception e)
            {
                Config.Log.Warn(e);
            }
            return(null, null);
        }
Example #9
0
 public static string MessageLink(DiscordMessage msg)
 {
     return($"https://discord.com/channels/{msg.Channel.Guild.Id}/{msg.Channel.Id}/{msg.Id}");
 }
        public static async Task <DiscordMessage> ReportAsync(this DiscordClient client, string infraction, DiscordMessage message, IEnumerable <DiscordUser> reporters, string comment, ReportSeverity severity)
        {
            var getLogChannelTask = client.GetChannelAsync(Config.BotLogId);
            var embedBuilder      = MakeReportTemplate(client, infraction, message, severity);
            var reportText        = string.IsNullOrEmpty(comment) ? "" : comment.Sanitize() + Environment.NewLine;

            embedBuilder.Description = (reportText + embedBuilder.Description).Trim(EmbedPager.MaxDescriptionLength);
            var members = reporters.Select(client.GetMember);

            embedBuilder.AddField("Reporters", string.Join(Environment.NewLine, members.Select(GetMentionWithNickname)));
            var logChannel = await getLogChannelTask.ConfigureAwait(false);

            return(await logChannel.SendMessageAsync(embed : embedBuilder.Build()).ConfigureAwait(false));
        }
        private static DiscordEmbedBuilder MakeReportTemplate(DiscordClient client, string infraction, DiscordMessage message, ReportSeverity severity)
        {
            var content        = message.Content;
            var needsAttention = severity > ReportSeverity.Low;

            if (message.Embeds?.Any() ?? false)
            {
                if (!string.IsNullOrEmpty(content))
                {
                    content += Environment.NewLine;
                }

                var srcEmbed = message.Embeds.First();
                content += $"🔤 {srcEmbed.Title}";
                if (srcEmbed.Fields?.Any() ?? false)
                {
                    content += $"{Environment.NewLine}{srcEmbed.Description}{Environment.NewLine}+{srcEmbed.Fields.Count} fields";
                }
            }
            if (message.Attachments?.Any() ?? false)
            {
                if (!string.IsNullOrEmpty(content))
                {
                    content += Environment.NewLine;
                }
                content += string.Join(Environment.NewLine, message.Attachments.Select(a => "📎 " + a.FileName));
            }

            if (string.IsNullOrEmpty(content))
            {
                content = "🤔 something fishy is going on here, there was no message or attachment";
            }
            DiscordMember author = null;

            try
            {
                author = client.GetMember(message.Author);
            }
            catch (Exception e)
            {
                Config.Log.Warn(e, $"Failed to get the member info for user {message.Author.Id} ({message.Author.Username})");
            }
            var result = new DiscordEmbedBuilder
            {
                Title = infraction,
                Color = GetColor(severity),
            }.AddField("Violator", author == null ? message.Author.Mention : GetMentionWithNickname(author), true)
            .AddField("Channel", message.Channel.Mention, true)
            .AddField("Time (UTC)", message.CreationTimestamp.ToString("yyyy-MM-dd HH:mm:ss"), true)
            .AddField("Content of the offending item", content);

            if (needsAttention)
            {
                result.AddField("Link to the message", message.JumpLink.ToString());
            }
            return(result);
        }
        public static async Task <DiscordMessage> ReportAsync(this DiscordClient client, string infraction, DiscordMessage message, string trigger, string context, ReportSeverity severity)
        {
            var getLogChannelTask = client.GetChannelAsync(Config.BotLogId);
            var embedBuilder      = MakeReportTemplate(client, infraction, message, severity);
            var reportText        = string.IsNullOrEmpty(trigger) ? "" : $"Triggered by: `{trigger}`{Environment.NewLine}";

            if (!string.IsNullOrEmpty(context))
            {
                reportText += $"Triggered in: ```{context.Sanitize()}```{Environment.NewLine}";
            }
            embedBuilder.Description = reportText + embedBuilder.Description;
            var logChannel = await getLogChannelTask.ConfigureAwait(false);

            return(await logChannel.SendMessageAsync(embed : embedBuilder.Build()).ConfigureAwait(false));
        }
Example #13
0
        // TODO: Update to save guild config state. This will run as is, but will not hold any saved data between sessions.
        public async Task MessageReceivedAsync(CommandsNextExtension cnext, DiscordMessage msg, CancellationToken cancellationToken = new CancellationToken())
        {
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (this._commands is null)
                {
                    return;
                }

                var model = cnext.Services.GetRequiredService <ShatterDatabaseContext>();

                var guildConfig = await model.Configs.FindAsync(msg.Channel.GuildId);

                if (guildConfig is null)
                {
                    guildConfig = new GuildConfig
                    {
                        GuildId = msg.Channel.GuildId.Value,
                        Prefix  = this._config.Prefix
                    };

                    model.Configs.Add(guildConfig);

                    await model.SaveChangesAsync();
                }

                cancellationToken.ThrowIfCancellationRequested();

                int prefixPos = await PrefixResolver(msg, guildConfig);

                if (prefixPos == -1)
                {
                    return;                     // Prefix is wrong, dont respond to this message.
                }

                var    prefix        = msg.Content.Substring(0, prefixPos);
                string commandString = msg.Content.Replace(prefix, string.Empty);

                var command = cnext.FindCommand(commandString, out string args);

                cancellationToken.ThrowIfCancellationRequested();

                if (command is null)
                { // Looks like that command does not exsist!
                    await CommandResponder.RespondCommandNotFoundAsync(msg.Channel, prefix);
                }
                else
                {   // We found a command, lets deal with it.
                    if (guildConfig.DisabledCommands.Contains(command.Name))
                    {
                        return;                         // Command is disabled. Dont do a thing.
                    }

                    var moduleAttribute = command.CustomAttributes.FirstOrDefault(x => x is ExecutionModuleAttribute);

                    if (moduleAttribute != default)
                    {
                        var m = moduleAttribute as ExecutionModuleAttribute;
                        if (m is not null && m.GroupName != "config" &&
                            !guildConfig.ActivatedCommands.Contains(command.Name) &&
                            guildConfig.DisabledModules.Contains(m.GroupName))
                        {
                            await CommandResponder.RespondCommandDisabledAsync(msg.Channel, prefix);

                            return; // Command is disabled, dont do a thing.
                        }
                    }

                    var ctx = cnext.CreateContext(msg, prefix, command, args);
                    // We are done here, its up to CommandsNext now.

                    cancellationToken.ThrowIfCancellationRequested();

                    await cnext.ExecuteCommandAsync(ctx);
                }
            }
            finally
            {
                if (!(DiscordBot.CommandsInProgress is null))
                {
                    if (DiscordBot.CommandsInProgress.TryRemove(this, out var taskData))
                    {
                        taskData.Item2.Dispose();
                        taskData.Item1.Dispose();
                    }
                }
            }
        }
Example #14
0
 public override async Task Execute(Bot bot, DiscordUser user, DiscordMessage message, string[] args)
 {
     bot.chronoEvents.SkipDay(args[0]);
 }
Example #15
0
        /// <summary>
        /// Sends a message to a channel, what else did you expect?
        /// </summary>
        /// <param name="message">The text to send</param>
        /// <param name="channel">DiscordChannel object to send the message to.</param>
        /// <returns>A DiscordMessage object of the message sent to Discord.</returns>
        public DiscordMessage SendMessageToChannel(string message, DiscordChannel channel)
        {
            string url = Endpoints.BaseAPI + Endpoints.Channels + $"/{channel.ID}" + Endpoints.Messages;
            try
            {
                JObject result = JObject.Parse(WebWrapper.Post(url, token, JsonConvert.SerializeObject(Utils.GenerateMessage(message))));
                if (result["content"].IsNullOrEmpty())
                    throw new InvalidOperationException("Request returned a blank message, you may not have permission to send messages yet!");

                DiscordMessage m = new DiscordMessage
                {
                    ID = result["id"].ToString(),
                    Attachments = result["attachments"].ToObject<DiscordAttachment[]>(),
                    Author = channel.Parent.GetMemberByKey(result["author"]["id"].ToString()),
                    channel = channel,
                    TypeOfChannelObject = channel.GetType(),
                    Content = result["content"].ToString(),
                    RawJson = result,
                    timestamp = result["timestamp"].ToObject<DateTime>()
                };
                return m;
            }
            catch (Exception ex)
            {
                DebugLogger.Log($"Error ocurred while sending message to channel ({channel.Name}): {ex.Message}", MessageLevel.Error);
            }
            return null;
        }
        public async Task CrosspostAsync(CommandContext ctx, DiscordChannel chn, DiscordMessage msg)
        {
            var message = await chn.CrosspostMessageAsync(msg);

            await ctx.RespondAsync($":ok_hand: Message published: {message.Id}");
        }
 private void AppendMessage(DiscordMessage m)
 {
     if(messagesList.Items.Count > 0)
     {
         var previousStub = (messagesList.Items[messagesList.Items.Count - 1] as MessageStub);
         if ((previousStub.Message.timestamp - m.timestamp) < TimeSpan.FromMinutes(2))
         {
             if (m.author == (messagesList.Items[messagesList.Items.Count - 1] as MessageStub).Message.author)
             {
                 (messagesList.Items[messagesList.Items.Count - 1] as MessageStub).AppendMessage(m);
             }
             else
             {
                 MessageStub stub = new MessageStub(m, mainClientReference);
                 if (stub.Message.author != null)
                     if (App.ClientConfiguration.Settings.IgnoredUserIDs.Contains(stub.Message.author.ID))
                         stub.SetMessageText("<Ignored Message>");
                 stub.IgnoredUserAdded += IgnoreUserUpdate;
                 messagesList.Items.Add(stub);
                 MainScroller.ScrollToBottom();
             }
         }
         else
         {
             MessageStub stub = new MessageStub(m, mainClientReference);
             if (stub.Message.author != null)
                 if (App.ClientConfiguration.Settings.IgnoredUserIDs.Contains(stub.Message.author.ID))
                     stub.SetMessageText("<Ignored Message>");
             stub.IgnoredUserAdded += IgnoreUserUpdate;
             messagesList.Items.Add(stub);
             MainScroller.ScrollToBottom();
         }
     }
     else
     {
         MessageStub stub = new MessageStub(m, mainClientReference);
         if(stub.Message.author != null)
             if (App.ClientConfiguration.Settings.IgnoredUserIDs.Contains(stub.Message.author.ID))
                 stub.SetMessageText("<Ignored Message>");
         stub.IgnoredUserAdded += IgnoreUserUpdate;
         messagesList.Items.Add(stub);
         MainScroller.ScrollToBottom();
     }
 }
 public Task MessageAsync(CommandContext ctx, DiscordMessage msg)
 => ctx.RespondAsync(embed: new DiscordEmbedBuilder()
                     .WithTimestamp(msg.CreationTimestamp)
                     .WithAuthor($"{msg.Author.Username}#{msg.Author.Discriminator}", msg.Author.AvatarUrl)
                     .WithDescription(msg.Content));
Example #19
0
 /// <summary>
 /// Converting the response message
 /// </summary>
 /// <param name="message">Message</param>
 /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
 public virtual Task <TData> ConvertMessage(DiscordMessage message) => Task.FromResult((TData)Convert.ChangeType(message.Content, typeof(TData)));
Example #20
0
        public static async Task <DiscordEmbedBuilder> AsEmbedAsync(this LogParseState state, DiscordClient client, DiscordMessage message, ISource source)
        {
            DiscordEmbedBuilder builder;

            state.CompleteCollection ??= state.WipCollection;
            state.CompleteMultiValueCollection ??= state.WipMultiValueCollection;
            var collection = state.CompleteCollection;

            if (collection?.Count > 0)
            {
                var ldrGameSerial = collection["ldr_game_serial"] ?? collection["ldr_path_serial"];
                if (collection["serial"] is string serial &&
                    KnownDiscOnPsnIds.TryGetValue(serial, out var psnSerial) &&
                    !string.IsNullOrEmpty(ldrGameSerial) &&
                    ldrGameSerial.StartsWith("NP", StringComparison.InvariantCultureIgnoreCase) &&
                    ldrGameSerial.Equals(psnSerial, StringComparison.InvariantCultureIgnoreCase))
                {
                    collection["serial"]        = psnSerial;
                    collection["game_category"] = "HG";
                }
                var titleUpdateInfoTask = psnClient.GetTitleUpdatesAsync(collection["serial"], Config.Cts.Token);
                var gameInfo            = await client.LookupGameInfoAsync(collection["serial"], collection["game_title"], true, category : collection["game_category"]).ConfigureAwait(false);

                try
                {
                    var titleUpdateInfo = await titleUpdateInfoTask.ConfigureAwait(false);

                    if (titleUpdateInfo?.Tag?.Packages?.LastOrDefault()?.Version is string tuVersion)
                    {
                        collection["game_update_version"] = tuVersion;
                    }
                }
                catch {}
                builder = new DiscordEmbedBuilder(gameInfo)
                {
                    Thumbnail = null
                };                                                              // or this will f**k up all formatting
                collection["embed_title"] = builder.Title ?? "";
                if (state.Error == LogParseState.ErrorCode.PiracyDetected)
                {
                    var msg = "__You are being denied further support until you legally dump the game__.\n" +
                              "Please note that the RPCS3 community and its developers do not support piracy.\n" +
                              "Most of the issues with pirated dumps occur due to them having been tampered with in some way " +
                              "and therefore act unpredictably on RPCS3.\n" +
                              "If you need help obtaining legal dumps, please read [the quickstart guide](https://rpcs3.net/quickstart).";
                    builder.WithColor(Config.Colors.LogAlert)
                    .WithTitle("Pirated content detected")
                    .WithDescription(msg);
                }
                else
                {
                    CleanupValues(state);
                    BuildInfoSection(builder, collection);
                    var colA = BuildCpuSection(collection);
                    var colB = BuildGpuSection(collection);
                    BuildSettingsSections(builder, collection, colA, colB);
                    BuildLibsSection(builder, collection);
                    await BuildNotesSectionAsync(builder, state, client).ConfigureAwait(false);
                }
            }
            else
            {
                builder = new DiscordEmbedBuilder
                {
                    Description = "Log analysis failed. Please try again.",
                    Color       = Config.Colors.LogResultFailed,
                };
                if (state.TotalBytes < 2048 || state.ReadBytes < 2048)
                {
                    builder.Description = "Log analysis failed, most likely cause is an empty log. Please try again.";
                }
            }
            builder.AddAuthor(client, message, source, state);
            return(builder);
        }
        public static async Task <(Dictionary <string, Stream>?attachmentContent, List <string>?failedFilenames)> DownloadAttachmentsAsync(this DiscordMessage msg)
        {
            if (msg.Attachments.Count == 0)
            {
                return(null, null);
            }

            var attachmentContent   = new Dictionary <string, Stream>(msg.Attachments.Count);
            var attachmentFilenames = new List <string>();

            using var httpClient = HttpClientFactory.Create(new CompressionMessageHandler());
            foreach (var att in msg.Attachments)
            {
                if (att.FileSize > Config.AttachmentSizeLimit)
                {
                    attachmentFilenames.Add(att.FileName);
                    continue;
                }

                try
                {
                    await using var sourceStream = await httpClient.GetStreamAsync(att.Url).ConfigureAwait(false);

                    var fileStream = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 16384, FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose);
                    await sourceStream.CopyToAsync(fileStream, 16384, Config.Cts.Token).ConfigureAwait(false);

                    fileStream.Seek(0, SeekOrigin.Begin);
                    attachmentContent[att.FileName] = fileStream;
                }
                catch (Exception ex)
                {
                    Config.Log.Warn(ex, $"Failed to download attachment {att.FileName} from deleted message {msg.JumpLink}");
                    attachmentFilenames.Add(att.FileName);
                }
            }
            return(attachmentContent : attachmentContent, failedFilenames : attachmentFilenames);
        }
Example #22
0
        public static async Task LinkPrBuild(DiscordClient client, DiscordMessage message, int pr)
        {
            var prInfo = await githubClient.GetPrInfoAsync(pr, Config.Cts.Token).ConfigureAwait(false);

            if (prInfo.Number == 0)
            {
                await message.ReactWithAsync(client, Config.Reactions.Failure, prInfo.Message ?? "PR not found").ConfigureAwait(false);

                return;
            }

            var prState = prInfo.GetState();
            var embed   = prInfo.AsEmbed();

            if (prState.state == "Open" || prState.state == "Closed")
            {
                var downloadHeader = "Latest PR Build Download";
                var downloadText   = "";
                if (prInfo.StatusesUrl is string statusesUrl)
                {
                    var statuses = await githubClient.GetStatusesAsync(statusesUrl, Config.Cts.Token).ConfigureAwait(false);

                    statuses = statuses?.Where(s => s.Context == appveyorContext).ToList();
                    if (statuses?.Count > 0)
                    {
                        if (statuses.FirstOrDefault(s => s.State == "success") is StatusInfo statusSuccess)
                        {
                            var artifactInfo = await appveyorClient.GetPrDownloadAsync(statusSuccess.TargetUrl, Config.Cts.Token).ConfigureAwait(false);

                            if (artifactInfo == null)
                            {
                                downloadText = $"[⏬ {statusSuccess.Description}]({statusSuccess.TargetUrl})";
                            }
                            else
                            {
                                if (artifactInfo.Artifact.Created is DateTime buildTime)
                                {
                                    downloadHeader = $"{downloadHeader} ({buildTime:u})";
                                }
                                downloadText = $"[⏬ {artifactInfo.Artifact.FileName}]({artifactInfo.DownloadUrl})";
                            }
                        }
                        else if (await appveyorClient.GetPrDownloadAsync(prInfo.Number, prInfo.CreatedAt, Config.Cts.Token).ConfigureAwait(false) is ArtifactInfo artifactInfo)
                        {
                            if (artifactInfo.Artifact.Created is DateTime buildTime)
                            {
                                downloadHeader = $"{downloadHeader} ({buildTime:u})";
                            }
                            downloadText = $"[⏬ {artifactInfo.Artifact.FileName}]({artifactInfo.DownloadUrl})";
                        }
                        else
                        {
                            downloadText = statuses.First().Description;
                        }
                    }
                }
                else if (await appveyorClient.GetPrDownloadAsync(prInfo.Number, prInfo.CreatedAt, Config.Cts.Token).ConfigureAwait(false) is ArtifactInfo artifactInfo)
                {
                    if (artifactInfo.Artifact.Created is DateTime buildTime)
                    {
                        downloadHeader = $"{downloadHeader} ({buildTime:u})";
                    }
                    downloadText = $"[⏬ {artifactInfo.Artifact.FileName}]({artifactInfo.DownloadUrl})";
                }
                if (!string.IsNullOrEmpty(downloadText))
                {
                    embed.AddField(downloadHeader, downloadText);
                }
            }
            else if (prState.state == "Merged")
            {
                var mergeTime  = prInfo.MergedAt.GetValueOrDefault();
                var now        = DateTime.UtcNow;
                var updateInfo = await compatApiClient.GetUpdateAsync(Config.Cts.Token).ConfigureAwait(false);

                if (updateInfo != null)
                {
                    if (DateTime.TryParse(updateInfo.LatestBuild?.Datetime, out var masterBuildTime) && masterBuildTime.Ticks >= mergeTime.Ticks)
                    {
                        embed = await updateInfo.AsEmbedAsync(embed).ConfigureAwait(false);
                    }
                    else
                    {
                        var waitTime = TimeSpan.FromMinutes(5);
                        if (now < (mergeTime + AvgBuildTime))
                        {
                            waitTime = mergeTime + AvgBuildTime - now;
                        }
                        embed.AddField("Latest master build", $"This pull request has been merged, and will be part of `master` very soon.\nPlease check again in {waitTime.AsTimeDeltaDescription()}.");
                    }
                }
            }
            await message.RespondAsync(embed : embed).ConfigureAwait(false);
        }
 public void AppendMessage(DiscordMessage message)
 {
     if(message.author != null && App.ClientConfiguration.Settings.IgnoredUserIDs.Contains(message.author.ID))
     { return; }
     DiscordChannel channel = message.Channel() as DiscordChannel;
     var markdownParser = new Markdown(channel.parent, null);
     var blocks = markdownParser.Transform(message, $"{message.id};{channel.ID}");
     richTextBox.Document.Blocks.AddRange(blocks);
     ToolTip = $"Sent at {message.timestamp}";
     MessageIDs.Add(message.id);
     Messages.Add(message);
 }
 public static Task AddError(this DiscordMessage message)
 {
     return(message.CreateReactionAsync(DiscordEmoji.FromUnicode("🛑")));
 }
        private string NoMarkdown(DiscordMessage message)
        {
            string returnValue = message.content;
            returnValue = returnValue.Trim(new char[] { '`', '*' });
            returnValue = returnValue.Replace("```", "");
            foreach(Match match in Markdown._username.Matches(returnValue))
            {
                string ID = match.Value.Trim(new char[] { '<', '@', '>' });
                DiscordMember user = (Message.Channel() as DiscordChannel).parent.members.Find(x => x.ID == ID);
                returnValue = match.Result($"@{user.Username}");
                Markdown._username.Replace(returnValue, ID);
            }

            return returnValue;
        }
 public static Task AddConfirmation(this DiscordMessage message)
 {
     return(message.CreateReactionAsync(DiscordEmoji.FromUnicode("✅")));
 }
 private void AppendMessage(DiscordMessage m)
 {
     if(messagesList.Items.Count > 0)
     {
         var previousStub = (messagesList.Items[messagesList.Items.Count - 1] as MessageStub);
         if ((previousStub.Message.timestamp - m.timestamp) < TimeSpan.FromMinutes(2))
         {
             if (m.author == (messagesList.Items[messagesList.Items.Count - 1] as MessageStub).Message.author)
             {
                 (messagesList.Items[messagesList.Items.Count - 1] as MessageStub).AppendMessage(m);
             }
             else
             {
                 MessageStub stub = new MessageStub(m);
                 messagesList.Items.Add(stub);
                 MainScroller.ScrollToBottom();
             }
         }
         else
         {
             MessageStub stub = new MessageStub(m);
             messagesList.Items.Add(stub);
             MainScroller.ScrollToBottom();
         }
     }
     else
     {
         MessageStub stub = new MessageStub(m);
         messagesList.Items.Add(stub);
         MainScroller.ScrollToBottom();
     }
 }
Example #28
0
 public static async Task <List <DiscordMessage> > RespondEmbed(this DiscordMessage msg, string message)
 {
     return(await msg.RespondEmbed(message, DiscordColor.Green));
 }
Example #29
0
        /// <summary>
        /// If you screwed up, you can use this method to edit a given message. This sends out an http patch request with a replacement message
        /// </summary>
        /// <param name="MessageID">The ID of the message you want to edit.</param>
        /// <param name="replacementMessage">What you want the text to be edited to.</param>
        /// <param name="channel">The channel the message is in</param>
        /// <returns>the new and improved DiscordMessage object.</returns>
        public DiscordMessage EditMessage(string MessageID, string replacementMessage, DiscordChannel channel)
        {
            string url = Endpoints.BaseAPI + Endpoints.Channels + $"/{channel.ID}" + Endpoints.Messages + $"/{MessageID}";
            try
            {
                string replacement = JsonConvert.SerializeObject(
                    new
                    {
                        content = replacementMessage,
                        mentions = new string[0]
                    }
                );
                JObject result = JObject.Parse(WebWrapper.Patch(url, token, replacement));

                DiscordMessage m = new DiscordMessage
                {
                    RawJson = result,
                    Attachments = result["attachments"].ToObject<DiscordAttachment[]>(),
                    Author = channel.Parent.GetMemberByKey(result["author"]["id"].ToString()),
                    TypeOfChannelObject = channel.GetType(),
                    channel = channel,
                    Content = result["content"].ToString(),
                    ID = result["id"].ToString(),
                    timestamp = result["timestamp"].ToObject<DateTime>()
                };
                return m;
            }
            catch (Exception ex)
            {
                DebugLogger.Log("Exception ocurred while editing: " + ex.Message, MessageLevel.Error);
            }

            return null;
        }
Example #30
0
        public async Task RoleAssignment(DiscordMessage msgInv, CommandContext e, List <DiscordMember> players)
        {
            try
            {
                // Création de tous les channels sans Droit
                Game.WriteDebug(Global.currGame);
                var chsPerso = await Global.Games[Global.currGame].Guild
                               .CreateChannelAsync(Global.Games[Global.currGame].Texts.PersoGroup, ChannelType.Category);
                Global.Games[Global.currGame].DiscordChannels.Add(GameChannel.PersoGroup, chsPerso);

                var wolfGrpChannel =
                    await Global.Games[Global.currGame].Guild
                    .CreateChannelAsync(Global.Games[Global.currGame].Texts.WolvesChannel, ChannelType.Category);
                var townGrpChannel = await Global.Games[Global.currGame].Guild
                                     .CreateChannelAsync(Global.Games[Global.currGame].Texts.TownChannel, ChannelType.Category);


                var townTChannel =
                    await Guild.CreateChannelAsync(Texts.TownChannel, ChannelType.Text, townGrpChannel);

                var townVChannel =
                    await Guild.CreateChannelAsync(Texts.TownChannel, ChannelType.Voice, townGrpChannel);

                DiscordChannels.Add(GameChannel.TownText, townTChannel);
                DiscordChannels.Add(GameChannel.TownVoice, townVChannel);


                var wolfTChannel =
                    await Guild.CreateChannelAsync(Texts.WolvesChannel, ChannelType.Text, wolfGrpChannel);

                var wolfVChannel =
                    await Guild.CreateChannelAsync(Texts.WolvesChannel, ChannelType.Voice, wolfGrpChannel);

                DiscordChannels.Add(GameChannel.WolfText, wolfTChannel);
                DiscordChannels.Add(GameChannel.WolfVoice, wolfVChannel);

                var graveyardGrpChannel =
                    await Guild.CreateChannelAsync(Texts.GraveyardChannel, ChannelType.Category);

                var graveyardTChannel = await Guild.CreateChannelAsync(Texts.GraveyardChannel,
                                                                       ChannelType.Text, graveyardGrpChannel);

                var graveyardVChannel = await Guild.CreateChannelAsync(Texts.GraveyardChannel,
                                                                       ChannelType.Voice, graveyardGrpChannel);

                await graveyardTChannel.AddOverwriteAsync(Global.Roles[CustomRoles.Spectator], GameBuilder.UsrPerms);

                DiscordChannels.Add(GameChannel.GraveyardText, graveyardTChannel);
                DiscordChannels.Add(GameChannel.GraveyardVoice, graveyardVChannel);

                foreach (var discordMember in Guild.Members)
                {
                    if (discordMember.Roles.Contains(Global.Roles[CustomRoles.Spectator]))
                    {
                        await graveyardVChannel.AddOverwriteAsync(discordMember,
                                                                  GameBuilder.CreatePerms(Permissions.UseVoiceDetection, Permissions.UseVoice,
                                                                                          Permissions.Speak));
                    }
                }

                await GameBuilder.CreatePersonnages(this, players);

                await(await e.Channel.GetMessageAsync(msgInv.Id)).ModifyAsync((await townTChannel.CreateInviteAsync())
                                                                              .ToString());
            }
            catch (SystemException ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #31
0
        private void MessageCreateEvents(JObject message)
        {
            //try
            //{
            string tempChannelID = message["d"]["channel_id"].ToString();

            //DiscordServer foundServerChannel = ServersList.Find(x => x.channels.Find(y => y.id == tempChannelID) != null);
            DiscordChannel potentialChannel = GetDiscordChannelByID(message["d"]["channel_id"].ToString());
            if (potentialChannel == null) //private message create
            {
                if (message["d"]["author"]["id"].ToString() != Me.ID)
                {
                    var foundPM = PrivateChannels.Find(x => x.ID == message["d"]["channel_id"].ToString());
                    DiscordPrivateMessageEventArgs dpmea = new DiscordPrivateMessageEventArgs();
                    dpmea.Channel = foundPM;
                    dpmea.Message = message["d"]["content"].ToString();
                    DiscordMember tempMember = new DiscordMember(this);
                    tempMember.Username = message["d"]["author"]["username"].ToString();
                    tempMember.ID = message["d"]["author"]["id"].ToString();
                    dpmea.Author = tempMember;
                    tempMember.parentclient = this;
                    dpmea.RawJson = message;

                    if (PrivateMessageReceived != null)
                        PrivateMessageReceived(this, dpmea);
                }
                else
                {
                    //if (DebugMessageReceived != null)
                    //    DebugMessageReceived(this, new DiscordDebugMessagesEventArgs { message = "Ignoring MESSAGE_CREATE for private channel for message sent from this client." });
                }
            }
            else
            {
                DiscordMessageEventArgs dmea = new DiscordMessageEventArgs();
                dmea.RawJson = message;
                dmea.Channel = potentialChannel;

                dmea.MessageText = message["d"]["content"].ToString();

                DiscordMember tempMember = null;
                tempMember = potentialChannel.Parent.GetMemberByKey(message["d"]["author"]["id"].ToString());
                if (tempMember == null)
                {
                    tempMember = JsonConvert.DeserializeObject<DiscordMember>(message["author"].ToString());
                    tempMember.parentclient = this;
                    tempMember.Parent = potentialChannel.Parent;

                    potentialChannel.Parent.AddMember(tempMember);
                }

                dmea.Author = tempMember;

                DiscordMessage m = new DiscordMessage();
                m.Author = dmea.Author;
                m.channel = dmea.Channel;
                m.TypeOfChannelObject = dmea.Channel.GetType();
                m.Content = dmea.MessageText;
                m.ID = message["d"]["id"].ToString();
                m.RawJson = message;
                m.timestamp = DateTime.Now;
                dmea.Message = m;
                if (!message["d"]["attachments"].IsNullOrEmpty())
                {
                    List<DiscordAttachment> tempList = new List<DiscordAttachment>();
                    foreach (var attachment in message["d"]["attachments"])
                    {
                        tempList.Add(JsonConvert.DeserializeObject<DiscordAttachment>(attachment.ToString()));
                    }
                    m.Attachments = tempList.ToArray();
                }

                if (!message["d"]["mentions"].IsNullOrEmpty())
                {
                    JArray mentionsAsArray = JArray.Parse(message["d"]["mentions"].ToString());
                    foreach (var mention in mentionsAsArray)
                    {
                        string id = mention["id"].ToString();
                        if (id.Equals(Me.ID))
                        {
                            if (MentionReceived != null)
                                MentionReceived(this, dmea);
                        }
                    }
                }

                KeyValuePair<string, DiscordMessage> toAdd = new KeyValuePair<string, DiscordMessage>(message["d"]["id"].ToString(), m);
                MessageLog.Add(message["d"]["id"].ToString(), m);

                if (MessageReceived != null)
                    MessageReceived(this, dmea);
            }
            //}
            //catch (Exception ex)
            //{
            //    DebugLogger.Log("Error ocurred during MessageCreateEvents: " + ex.Message, MessageLevel.Error);
            //}
        }
 private async Task ForwardMessageToEcoChannel(DiscordLink plugin, DiscordMessage message, string ecoChannel)
 {
     Logger.DebugVerbose("Sending Discord message to Eco channel: " + ecoChannel);
     ChatManager.SendChat(await MessageUtil.FormatMessageForEco(message, ecoChannel), plugin.EcoUser);
 }
 public void AddMessage(DiscordMessage message)
 {
     DiscordChannel channel = Convert.ChangeType(message.Channel(), typeof(DiscordChannel));
     messageHistoryCache.Add(message);
     if(currentChannel == message.Channel())
         Dispatcher.Invoke(() => AppendMessage(message));
 }
Example #34
0
        public async Task Play(CommandContext ctx, [Description("The search request")][RemainingText] string search)
        {
            if (ctx.Member.VoiceState == null || ctx.Member.VoiceState.Channel == null)
            {
                await ctx.RespondAsync("You are not in a VC.");

                return;
            }
            LavalinkNodeConnection node = ctx.Client.GetLavalink().ConnectedNodes.Values.First();
            await node.ConnectAsync(ctx.Member.VoiceState.Channel);

            LavalinkGuildConnection conn = node.GetGuildConnection(ctx.Member.VoiceState.Guild);

            if (conn == null)
            {
                await ctx.RespondAsync("Lavalink not connected.");

                return;
            }
            LavalinkLoadResult loadResult = await node.Rest.GetTracksAsync(search, LavalinkSearchType.Youtube);

            if (loadResult.LoadResultType == LavalinkLoadResultType.LoadFailed ||
                loadResult.LoadResultType == LavalinkLoadResultType.NoMatches)
            {
                await ctx.RespondAsync($"Track search failed for {search}");

                return;
            }
            DiscordEmbedBuilder resultsEmbed = new DiscordEmbedBuilder
            {
                Title       = "I found this for you on Youtube:",
                Description = "Respond with the number you would like to play!",
                Color       = DiscordColor.Red
            };
            int index = 0;

            foreach (LavalinkTrack result in loadResult.Tracks)
            {
                index++;
                resultsEmbed.AddField($"{index}:", $"[{result.Title}]({result.Uri})");
                if (index == 10)
                {
                    break;
                }
            }
            DiscordMessage selectOne = await ctx.RespondAsync(resultsEmbed.Build());

            InteractivityExtension interactivity = ctx.Client.GetInteractivity();
            var selection = await interactivity.WaitForMessageAsync(x => x.Channel == ctx.Channel && x.Author == ctx.User);

            LavalinkTrack track = loadResult.Tracks.ElementAt(int.Parse(selection.Result.Content) - 1);

            if (LavalinkService.Instance.Queues != null && LavalinkService.Instance.Queues.ContainsKey(ctx.Guild))
            {
                LavalinkService.Instance.Queues[ctx.Guild].Add(track);
                DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                {
                    Title       = "Added to playlist:",
                    Description = $"[{track.Title}]({track.Uri})",
                    Color       = DiscordColor.Red
                };
                await ctx.RespondAsync(embedBuilder.Build());
            }
            else if (conn.CurrentState.CurrentTrack != null)
            {
                if (LavalinkService.Instance.Queues == null)
                {
                    LavalinkService.Instance.Queues  = new Dictionary <DiscordGuild, List <LavalinkTrack> >();
                    LavalinkService.Instance.Repeats = new Dictionary <DiscordGuild, Repeaters>
                    {
                        { ctx.Guild, Repeaters.off }
                    };
                }
                LavalinkService.Instance.Queues.Add(ctx.Guild, new List <LavalinkTrack> {
                    track
                });
                DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                {
                    Title       = "Added to playlist:",
                    Description = $"[{track.Title}]({track.Uri})",
                    Color       = DiscordColor.Red
                };
                await ctx.RespondAsync(embedBuilder.Build());
            }
            else
            {
                await conn.PlayAsync(track);

                LavalinkService.Instance.Repeats = new Dictionary <DiscordGuild, Repeaters>
                {
                    { ctx.Guild, Repeaters.off }
                };
                DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                {
                    Title       = "Now playing:",
                    Description = $"[{track.Title}]({track.Uri})",
                    Color       = DiscordColor.Red
                };
                await ctx.RespondAsync(embedBuilder.Build());
            }
            await selectOne.DeleteAsync();

            await selection.Result.DeleteAsync();
        }
 public void RemoveMessage(DiscordMessage m)
 {
     RemoveMessage(m.id, (m.Channel() as DiscordChannel).ID);
 }
Example #36
0
 public abstract Task Execute(Bot bot, DiscordUser user, DiscordMessage message, string[] args);