public static async Task <IUserMessage> SendMessageAsync(this IMessageChannel channel,
                                                                 BaseUser user,
                                                                 Message message,
                                                                 RequestOptions options = null)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var content = new StringBuilder();

            if (user.Notifier.CanNotify)
            {
                content.AppendLine(user.Notifier.Notify(2000 - (message.Text?.Length ?? 0)));
                user.Notifier.LastNotified = DateTime.UtcNow;
            }

            if (!string.IsNullOrWhiteSpace(message.Text))
            {
                content.Append(message.Text);
            }

            if (!string.IsNullOrWhiteSpace(message.AttachmentUrl))
            {
                return(await channel.SendFileAsync(message.AttachmentUrl, content.ToString(), message.IsTTS, message.Embed, options, message.IsSpoiler));
            }

            return(await channel.SendMessageAsync(content.ToString(), message.IsTTS, message.Embed, options));
        }
        public async Task SendAsync(IMessage message)
        {
            if (message.Attachments?.Count > 0)
            {
                foreach (IAttachment attachment in message.Attachments)
                {
                    try
                    {
                        await _channel.SendFileAsync(attachment.Contents, attachment.Name,
                                                     message.Attachments?.Count == 1?message.Text : null);

                        attachment.Contents?.Dispose();
                    }
                    catch (Exception e)
                    {
                        attachment.Contents?.Dispose();
                        Debug.WriteLine(e);
                        return;
                    }
                }
            }
            else
            {
                await _channel.SendMessageAsync(message.Text);
            }
        }
Exemple #3
0
        private void SendUserRecentScore()
        {
            new Thread(async() =>
            {
                var users = LatestUpdate.Keys.ToArray();
                foreach (string username in users)
                {
                    try
                    {
                        Score[] UserRecentScores = await OsuApi.GetUserRecent.WithUser(username).Results();
                        foreach (var recentScore in UserRecentScores.OrderBy(score => score.Date))
                        {
                            if (!(IsNewScore(recentScore) && recentScore.Rank != Rank.F))
                            {
                                continue;
                            }

                            UpdateUser(recentScore.Username, recentScore.Date);
                            Beatmap beatmap = (await OsuApi.GetSpecificBeatmap.WithId(recentScore.BeatmapId).Results()).FirstOrDefault();
                            User user       = await OsuApi.GetUser.WithUser(username).Result();
                            using (var temporaryStream = new MemoryStream())
                            {
                                ScoreImage.CreateScorePanel(user, recentScore, beatmap).Save(temporaryStream, System.Drawing.Imaging.ImageFormat.Png);
                                temporaryStream.Position = 0;
                                await OsuChannel.SendFileAsync(temporaryStream, "osuScoreImage.png");
                            }
                        }
                    }
                    catch { }
                }
            }).Start();
        }
Exemple #4
0
        /// <summary>
        /// Sends the privacy policy to the given channel.
        /// </summary>
        /// <param name="channel">The channel.</param>
        /// <param name="content">The content service.</param>
        /// <param name="feedback">The feedback service.</param>
        /// <returns>A task that must be awaited.</returns>
        public async Task SendPrivacyPolicyAsync
        (
            [NotNull] IMessageChannel channel,
            [NotNull] ContentService content,
            UserFeedbackService feedback
        )
        {
            var result = content.OpenLocalStream(Path.Combine(content.BaseContentPath, "PrivacyPolicy.pdf"));

            if (!result.IsSuccess)
            {
                var errorBuilder = feedback.CreateEmbedBase(Color.Red);
                errorBuilder.WithDescription
                (
                    "Oops. Something went wrong, and I couldn't grab the privacy policy. Please report this to the " +
                    "developer, don't agree to anything, and read it online instead."
                );

                errorBuilder.AddField("Privacy Policy", content.PrivacyPolicyUri);

                await channel.SendMessageAsync(string.Empty, embed : errorBuilder.Build());
            }

            using (var privacyPolicy = result.Entity)
            {
                await channel.SendFileAsync(privacyPolicy, "PrivacyPolicy.pdf");
            }
        }
Exemple #5
0
        public static async Task ImageLog(IMessageChannel Chanel, string text)
        {
            GetImageSize(text);

            int lenText = text.Length;


            Bitmap b = new Bitmap(wPlus, hPlus);

            using (Graphics g = Graphics.FromImage(b))
            {
                SolidBrush brush = new SolidBrush(System.Drawing.Color.BlueViolet);
                g.FillRectangle(brush, 0, 0, wPlus, hPlus);

                brush.Color = System.Drawing.Color.Red;
                g.FillRectangle(brush, 10, 5, wPlus - 20, hPlus - 10);

                brush.Color = System.Drawing.Color.Black;
                Font         drawFont   = new Font("Arial", 48);
                StringFormat drawFormat = new StringFormat();
                g.DrawString(text, drawFont, brush, new PointF(10, 5), drawFormat);
            }

            b.Save(@"image\register.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

            await Chanel.SendFileAsync(@"image\register.jpg");
        }
Exemple #6
0
        public static async Task RandomMessage(IUser insulted_user, IMessageChannel channel)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(@"..\..\Insults.xml");

            XmlNodeList gameNodes    = doc.DocumentElement.SelectNodes("/insult_group/game/insult");
            XmlNodeList generalNodes = doc.DocumentElement.SelectNodes("/insult_group/general/insult");
            XmlNodeList userNodes    = doc.DocumentElement.SelectNodes($"/insult_group/{Utility.ids_to_names[insulted_user.Id]}/insult");
            //XmlNodeList userNodes = doc.DocumentElement.SelectNodes($"/insult_group/ska/insult");
            XmlNodeList groupToUse;

            int percentage = Utility.numgen.Next(1, 101);

            if (insulted_user.Game == null)
            {
                if (percentage <= 25)
                {
                    groupToUse = userNodes;
                }
                else
                {
                    groupToUse = generalNodes;
                }
            }
            else
            {
                if (percentage <= 25)
                {
                    groupToUse = userNodes;
                }
                else if (percentage <= 50)
                {
                    groupToUse = gameNodes;
                }
                else
                {
                    groupToUse = generalNodes;
                }
            }

            XmlNode insultNode = groupToUse[Utility.numgen.Next(0, groupToUse.Count)];
            string  insult     = insultNode.InnerText;

            insult = insult.Replace("^user^", insulted_user.Mention);
            if (insulted_user.Game != null)
            {
                insult = insult.Replace("^game^", insulted_user.Game.ToString());
            }

            if (insult.Contains("^image^"))
            {
                insult = insult.Replace("^image^", "");
                await channel.SendFileAsync(insultNode.NextSibling.InnerText, insult);
            }
            else
            {
                await channel.SendMessageAsync(insult);
            }
        }
Exemple #7
0
        public async Task <IMessage> SendAsync(IMessage message)
        {
            IMessage result = null;

            if (message.Attachments?.Count > 0)
            {
                foreach (IAttachment attachment in message.Attachments)
                {
                    try
                    {
                        result = new DiscordMessage(await _channel.SendFileAsync(attachment.Contents, attachment.Name,
                                                                                 message.Attachments?.Count == 1 ? message.Text : null));
                        break;
                    }
                    catch (Exception e)
                    {
                        Log.Exception(e, "Discord file send fail");
                        return(null);
                    }
                }
                message.Attachments.ForEach(x => x.Contents?.Dispose());
                IsTyping = false;
            }
            else
            {
                result   = new DiscordMessage(await _channel.SendMessageAsync(message.Text));
                IsTyping = false;
            }

            return(result);
        }
Exemple #8
0
        public async Task <IDiscordMessage> SendToChannel(ulong channelId)
        {
            IMessageChannel m = (Bot.instance.Client.GetChannel(channelId) as IMessageChannel);

            if (m as IGuildChannel != null)
            {
                if (!(await(m as IGuildChannel).Guild.GetCurrentUserAsync()).GuildPermissions.EmbedLinks)
                {
                    if (string.IsNullOrWhiteSpace(ImageUrl))
                    {
                        return(new RuntimeMessage(await m.SendMessageAsync(ToMessageBuilder().Build(), false)));
                    }

                    using (WebClient wc = new WebClient())
                    {
                        byte[] image = wc.DownloadData(ImageUrl);
                        using (MemoryStream ms = new MemoryStream(image))
                        {
                            return(new RuntimeMessage(await m.SendFileAsync(ms, ImageUrl, ToMessageBuilder().Build())));
                        }
                    }
                }
            }
            return(new RuntimeMessage(await m.SendMessageAsync("", false, embed)));
        }
Exemple #9
0
        /// <summary>
        /// Реализация
        /// </summary>
        /// <param name="iAttachments">Прикрепленные файлы к сообщению</param>
        /// <param name="messageChannel">Чат-канал</param>
        private async Task ReturnBack(IEnumerable <Attachment> iAttachments, IMessageChannel messageChannel)
        {
            var attachments = new List <Attachment>();

            foreach (var attachment in iAttachments)
            {
                attachments.Add(attachment);
            }

            if (attachments.Count <= 0)
            {
                await messageChannel.SendMessageAsync("Нет прикрепленных файлов");

                return;
            }

            for (int i = 0; i < attachments.Count; i++)
            {
                if (string.IsNullOrWhiteSpace(attachments[i].Filename))
                {
                    return;
                }
                DownloadFile(attachments[i].Url, attachments[i].Filename);
            }

            for (int i = 0; i < attachments.Count; i++)
            {
                var sentMessage = await messageChannel.SendFileAsync(attachments[i].Filename);

                var robot = new Emoji("🤖");
                await sentMessage.AddReactionAsync(robot);
            }
        }
        protected async Task UploadDatabaseBackupAsync(IMessageChannel channel, string databaseFilePath)
        {
            bool backupInProgress = GetDatabaseStatus(databaseFilePath).BackupInProgress;

            if (backupInProgress)
            {
                await DiscordUtilities.ReplyErrorAsync(channel, "A backup is already in progress. Please wait until it has completed.");
            }
            else
            {
                GetDatabaseStatus(databaseFilePath).BackupInProgress = true;

                if (System.IO.File.Exists(databaseFilePath))
                {
                    try {
                        await DiscordUtilities.ReplyInfoAsync(channel,
                                                              string.Format("Uploading database backup ({0:0.##} MB).\nThe backup will be posted in this channel when it is complete.",
                                                                            new System.IO.FileInfo(databaseFilePath).Length / 1024000.0));

                        await channel.SendFileAsync(databaseFilePath, string.Format("`Database backup ({0})`", DateUtilities.GetCurrentDateUtc()));
                    }
                    catch (Exception) {
                        await DiscordUtilities.ReplyErrorAsync(channel, "Database file cannot be accessed.");
                    }
                }
                else
                {
                    await DiscordUtilities.ReplyErrorAsync(channel, "Database file does not exist at the specified path.");
                }

                GetDatabaseStatus(databaseFilePath).BackupInProgress = false;
            }
        }
 public static async Task SendTextAsFile(IMessageChannel channel, string data, string filename = "message.txt")
 {
     ASCIIEncoding encoder = new ASCIIEncoding();
     var           bytes   = encoder.GetBytes(data);
     MemoryStream  stream  = new MemoryStream(bytes);
     await channel.SendFileAsync(stream, filename);
 }
Exemple #12
0
        public async Task PostAsync(IMessageChannel chan, string text, AGame _)
        {
            try
            {
                var result = await StaticObjects.HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, text));

                var length = int.Parse(result.Content.Headers.GetValues("content-length").ElementAt(0));
                if (length < 8000000)
                {
                    await chan.SendFileAsync((await StaticObjects.HttpClient.GetAsync(text)).Content.ReadAsStream(), "image" + Path.GetExtension(text));
                }
                else // Too big to be sent on Discord
                {
                    await chan.SendMessageAsync(text);
                }
            }
            catch (Discord.Net.HttpException dne)
            {
                if (dne.DiscordCode == DiscordErrorCode.MissingPermissions)
                {
                    throw new GameLost("Missing permissions to send files");
                }
                else
                {
                    throw;
                }
            }
        }
Exemple #13
0
        public async Task <IUserMessage> RepostMessageAsync(IChannel c, IMessage msg, Embed embed = null)
        {
            try
            {
                if (msg == null)
                {
                    return(null);
                }
                IMessageChannel chan = c as IMessageChannel;
                if (!this.CanSendMessage(chan))
                {
                    return(null);
                }

                if (msg.Attachments.Count > 0)
                {
                    IAttachment attachment = msg.Attachments.First();
                    using (Stream stream = await this.HttpClient.GetStreamAsync(attachment.ProxyUrl))
                        return(await chan.SendFileAsync(stream, attachment.Filename, msg.Content, embed : embed));
                }
                else
                {
                    return(await chan.SendMessageAsync(msg.Content, embed : embed));
                }
            }
            catch (Exception ex)
            {
                this.LogFailedMessage(c, ex);
            }

            return(null);
        }
        public async Task <IUserMessage> RandomImage(IMessageChannel channel, string text = null, bool spoiler = false)
        {
            if (!CommandState.ContainsKey(channel.Id))
            {
                return(null);
            }

            var cmd = CommandState[channel.Id];

            if (cmd == null)
            {
                return(null);
            }

            var index = Config.GetIndex(cmd);

            if (index == -1)
            {
                return(null);
            }

            if (Images[index] == null)
            {
                return(null);
            }

            var i    = random.Next(0, Images[index].Length - 1);
            var file = Images[index][i];

            switch (Images.UriBase[index].Scheme)
            {
            case "file":
                logger.LogInformation($"RandomImage for {channel.Name} <#{channel.Id}>: {file}");
                return(await channel.SendFileAsync(file, text, false, null, null, spoiler));

            case "http":
            case "https":
                var request = WebRequest.Create(Images.UriBase + file);
                logger.LogInformation($"RandomImage for {channel.Name} <#{channel.Id}>: {Images.UriBase + file}");
                using (var response = await request.GetResponseAsync())
                {
                    return(await channel.SendFileAsync(response.GetResponseStream(), file, text, false, null, null, spoiler));
                }
            }

            throw new Exception("Unknown Scheme");
        }
Exemple #15
0
 public static async Task <IUserMessage> SendBitmapAsync(this IMessageChannel channel, Bitmap bitmap, ImageFormat format, string filename, string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null)
 {
     using (var stream = new MemoryStream()) {
         bitmap.Save(stream, format);
         stream.Position = 0;
         return(await channel.SendFileAsync(stream, filename, text, isTTS, embed, options).ConfigureAwait(false));
     }
 }
Exemple #16
0
 public static async Task <IUserMessage> SendFileAsync(this IMessageChannel channel, byte[] data, string filename, string message = null)
 {
     using (var ms = new MemoryStream(data))
     {
         ms.Position = 0;
         return(await channel.SendFileAsync(ms, filename, message).ConfigureAwait(false));
     }
 }
Exemple #17
0
        /// <summary>
        /// Send an error message.
        /// Used for precondition errors.
        /// </summary>
        /// <param name="channel">Channel to send message to.</param>
        /// <param name="command">Command that was executing.</param>
        /// <param name="message">Message to send.</param>
        /// <returns>The sent message.</returns>
        public static async Task <IUserMessage> SendErrorMessage(IMessageChannel channel, string command, string message)
        {
            Connections.CopyFile(ERROR_IMAGE);
            IUserMessage msg = await channel.SendFileAsync(ERROR_IMAGE, embed : BuildErrorEmbed(command, message));

            Connections.DeleteFile(ERROR_IMAGE);
            return(msg);
        }
Exemple #18
0
        public static async Task SendPKMAsync(this IMessageChannel channel, PKM pkm, string msg = "")
        {
            var tmp = Path.Combine(Path.GetTempPath(), Util.CleanFileName(pkm.FileName));

            File.WriteAllBytes(tmp, pkm.DecryptedPartyData);
            await channel.SendFileAsync(tmp, msg).ConfigureAwait(false);

            File.Delete(tmp);
        }
Exemple #19
0
 private async Task SendImage(Image <Rgba32> image, IMessageChannel channel, string imagename)
 {
     using (var memoryStream = new MemoryStream())
     {
         image.Save(memoryStream, new PngEncoder());
         memoryStream.Seek(0, SeekOrigin.Begin);
         await channel.SendFileAsync(memoryStream, $"{imagename}-.png");
     }
 }
Exemple #20
0
 /// <summary>
 /// Sends a file to a channel delayed and deletes it after another delay.
 /// </summary>
 /// <param name="channel">The target Channel.</param>
 /// <param name="sendDelay">The time to wait before sending the file.</param>
 /// <param name="deleteDelay">The time to wait between sending and deleting the file.</param>
 /// <param name="filestream">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="Embed"/> to be sent.</param>
 /// <param name="options">The options to be used when sending the request.</param>
 /// <returns></returns>
 public void DelayedSendFileAndDeleteAsync(IMessageChannel channel, TimeSpan?sendDelay = null, TimeSpan?deleteDelay = null,
                                           Stream filestream = null, string filename = null,
                                           string text       = null, bool isTTS      = false, Embed embed = null, RequestOptions options = null) => _ = Task.Run(async() =>
 {
     await Task.Delay(sendDelay ?? TimeSpan.Zero).ConfigureAwait(false);
     var msg = await channel.SendFileAsync(filestream, filename, text, isTTS, embed, options).ConfigureAwait(false);
     await Task.Delay(deleteDelay ?? DefaultTimeout).ConfigureAwait(false);
     await msg.DeleteAsync().ConfigureAwait(false);
 });
Exemple #21
0
 public static Task SendFileRetry(this IMessageChannel user,
                                  string path,
                                  string text = null)
 {
     return(Utility.FileIO(async() => {
         using (var file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
             await user.SendFileAsync(file, Path.GetFileName(path), text);
         }
     }));
 }
Exemple #22
0
 public static async Task <IUserMessage> SendFile(Stream stream, IMessageChannel Channel, string fileEnd, string fileName = "", string text = "")
 {
     Saver.SaveChannel(Channel);
     if (fileName == "")
     {
         fileName = DateTime.Now.ToBinary().ToString();
     }
     stream.Position = 0;
     return(await Channel.SendFileAsync(stream, fileName + "." + fileEnd.TrimStart('.'), text));
 }
        public async Task ChangeChannel(IMessageChannel socketChannel = null)
        {
            if (socketChannel == null)
            {
                socketChannel = Context.Channel;
            }
            var player = _music.GetLavalinkCluster().GetPlayer <Player>(Context.Guild.Id);

            player.Channel = socketChannel;
            await socketChannel.SendFileAsync("Now, i will send the music messages here :)");
        }
 /// <summary>
 /// Sends an attachment to this message channel.
 /// </summary>
 public static async Task <IUserMessage> SendAttachmentAsync(this IMessageChannel channel,
                                                             IAttachment attachment,
                                                             string text                     = null,
                                                             bool isTTS                      = false,
                                                             Embed embed                     = null,
                                                             RequestOptions options          = null,
                                                             bool isSpoiler                  = false,
                                                             AllowedMentions allowedMentions = null)
 {
     return(await channel.SendFileAsync(attachment.Url, text, isTTS, embed, options, isSpoiler, allowedMentions));
 }
Exemple #25
0
 public async Task SendFile(string path, IMessageChannel channel)
 {
     if (File.Exists(path))
     {
         await channel.SendFileAsync(path, "Here you go!");
     }
     else
     {
         await channel.SendMessageAsync($"Error: Did not find requested file. ({path})");
     }
 }
        /// <summary>
        /// Sends a message object to this message channel.
        /// </summary>
        public static async Task <IUserMessage> SendMessageAsync(this IMessageChannel channel,
                                                                 Message message,
                                                                 RequestOptions options          = null,
                                                                 AllowedMentions allowedMentions = null)
        {
            if (Check.NotNull(message.AttachmentUrl))
            {
                return(await channel.SendFileAsync(message.AttachmentUrl, message.Text, message.IsTTS, message.Embed, options, message.IsSpoiler, allowedMentions));
            }

            return(await channel.SendMessageAsync(message.Text, message.IsTTS, message.Embed, options, allowedMentions));
        }
Exemple #27
0
 public static async Task SendMemoryFile(this IMessageChannel channel,
                                         string name,
                                         string value,
                                         string text = null)
 {
     using (var stream = new MemoryStream()) {
         var writer = new StreamWriter(stream);
         writer.Write(value);
         writer.Flush();
         stream.Position = 0;
         await channel.SendFileAsync(stream, name, text);
     }
 }
Exemple #28
0
        public static async Task <string> UploadFileAsync(IMessageChannel channel, string filePath, FileUploadOptions options = FileUploadOptions.None)
        {
            IUserMessage result = await channel.SendFileAsync(filePath);

            string url = result.Attachments.FirstOrDefault()?.Url;

            if (!string.IsNullOrEmpty(url) && options.HasFlag(FileUploadOptions.DeleteFileAfterUpload))
            {
                IOUtilities.TryDeleteFile(filePath);
            }

            return(url);
        }
Exemple #29
0
        public async Task PostAsync(IMessageChannel chan, string text, AGame _)
        {
            var result = await StaticObjects.HttpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, text));

            var length = int.Parse(result.Content.Headers.GetValues("content-length").ElementAt(0));

            if (length < 8000000)
            {
                await chan.SendFileAsync(await StaticObjects.HttpClient.GetStreamAsync(text), "image" + Path.GetExtension(text));
            }
            else // Too big to be sent on Discord
            {
                await chan.SendMessageAsync(text);
            }
        }
Exemple #30
0
 public async override Task <IUserMessage> SendAsync(IMessageChannel channel)
 {
     if (DescriptionAsStream != null)
     {
         return(await channel.SendFileAsync(
                    stream : DescriptionAsStream,
                    filename : $"{Embed?.Title}_desc.txt",
                    embed : new WarningMessage("A message was too long, so it was uploaded as a file.").Embed,
                    messageReference : MessageReference));
     }
     else
     {
         return(await base.SendAsync(channel));
     }
 }