コード例 #1
0
        private Task SendReplyAsync(EmbedBuilder embed, bool hasFigure)
        {
            var _ = Task.Run(async() =>
            {
                if (_channel != null)
                {
                    if (hasFigure)
                    {
                        var figure = _db.Figure.Include(t => t.Test).Where(f => f.FigureName == CurrentQuestion.FigureName).FirstOrDefault();
                        if (figure != null)
                        {
                            var fileName = $"{figure.Test.TestName}_{figure.FigureName}.png";
                            if (!File.Exists(fileName))
                            {
                                await File.WriteAllBytesAsync(fileName, figure.FigureImage);
                            }
                            embed.WithImageUrl($"attachment://{fileName}");
                            _messages.Add(await _channel.SendFileAsync($"{fileName}", "", false, embed.Build()));
                            File.Delete(fileName);
                        }
                    }
                    else
                    {
                        _messages.Add(await _channel.SendMessageAsync(null, false, embed.Build()));
                    }
                }
                else if (_user != null)
                {
                    if (hasFigure)
                    {
                        var figure = _db.Figure.Include(t => t.Test).Where(f => f.FigureName == CurrentQuestion.FigureName).FirstOrDefault();
                        if (figure != null)
                        {
                            var fileName = $"{figure.Test.TestName}_{figure.FigureName}.png";
                            if (!File.Exists(fileName))
                            {
                                await File.WriteAllBytesAsync(fileName, figure.FigureImage);
                            }
                            embed.WithImageUrl($"attachment://{fileName}");
                            _messages.Add(await _user.SendFileAsync($"{fileName}", "", false, embed.Build()));
                            File.Delete(fileName);
                        }
                    }
                    else
                    {
                        await _user.SendMessageAsync(null, false, embed.Build());
                    }
                }
            });

            return(Task.CompletedTask);
        }
コード例 #2
0
ファイル: Messaging.cs プロジェクト: loglob/SaftbotII
        /// <summary>
        /// Uploads a file to the channel
        /// </summary>
        /// <param name="path">Path to the file</param>
        public virtual async Task Upload(string path, string comment = "")
        {
            await textChannel.SendFileAsync(path, comment);

            Log.Enter($"Uploaded file '{Path.GetFileName(path)}' with comment '{comment}' " +
                      $"to channel '{textChannel.Name}' (Full path: '{path}')");
        }
コード例 #3
0
ファイル: Waifu.cs プロジェクト: zsuatem/sanakan
        public async Task <string> GetArenaViewAsync(DuelInfo info, ITextChannel trashChannel)
        {
            string url            = null;
            string imageUrlWinner = await GetCardUrlIfExistAsync(info.Winner, force : true);

            string imageUrlLooser = await GetCardUrlIfExistAsync(info.Loser, force : true);

            DuelImage dImg   = null;
            var       reader = new Config.JsonFileReader($"./Pictures/Duel/List.json");

            try
            {
                var images = reader.Load <List <DuelImage> >();
                dImg = Fun.GetOneRandomFrom(images);
            }
            catch (Exception) { }

            using (var winner = await _img.GetWaifuCardAsync(imageUrlWinner, info.Winner))
            {
                using (var looser = await _img.GetWaifuCardAsync(imageUrlLooser, info.Loser))
                {
                    using (var img = _img.GetDuelCardImage(info, dImg, winner, looser))
                    {
                        using (var stream = img.ToPngStream())
                        {
                            var msg = await trashChannel.SendFileAsync(stream, $"duel.png");

                            url = msg.Attachments.First().Url;
                        }
                    }
                }
            }

            return(url);
        }
コード例 #4
0
ファイル: Waifu.cs プロジェクト: zsuatem/sanakan
        public async Task <Embed> BuildCardViewAsync(Card card, ITextChannel trashChannel, SocketUser owner)
        {
            string imageUrl = await GetCardUrlIfExistAsync(card, true);

            if (imageUrl != null)
            {
                var msg = await trashChannel.SendFileAsync(imageUrl);

                imageUrl = msg.Attachments.First().Url;
            }

            string imgUrls     = $"[_obrazek_]({imageUrl})\n[_możesz zmienić obrazek tutaj_]({card.GetCharacterUrl()}/edit_crossroad)";
            string ownerString = ((owner as SocketGuildUser)?.Nickname ?? owner?.Username) ?? "????";

            return(new EmbedBuilder
            {
                ImageUrl = imageUrl,
                Color = EMType.Info.Color(),
                Footer = new EmbedFooterBuilder
                {
                    Text = $"Należy do: {ownerString}"
                },
                Description = $"{card.GetDesc()}{imgUrls}".TrimToLength(1800)
            }.Build());
        }
コード例 #5
0
        /// <summary>
        ///     Send a welcome message to a user.
        /// </summary>
        /// <param name="user">The user to welcome.</param>
        /// <param name="channel">The channel in which the message should be send.</param>
        public async Task Welcome(IGuildUser user, ITextChannel channel = null)
        {
            var settings = await Load(user.GuildId);

            if (channel == null)
            {
                if (settings.ChannelId == null)
                {
                    throw new InvalidWelcomeException("The welcome message is not enabled on this server.");
                }

                channel = await user.Guild.GetTextChannelAsync(settings.ChannelId.Value);

                if (channel == null)
                {
                    throw new InvalidChannelException("The channel does not exist in this server.");
                }
            }

            var msg = string.Format(settings.Message, user.Mention);

            if (!settings.UseImage)
            {
                await channel.SendMessageAsync(msg);
            }
            else
            {
                await channel.SendFileAsync(ImageExtensions.GetImagePath("GasaiYunoWelcome.jpg"), msg);
            }
        }
コード例 #6
0
ファイル: Waifu.cs プロジェクト: zsuatem/sanakan
        public async Task <string> GetSafariViewAsync(SafariImage info, ITextChannel trashChannel)
        {
            string uri = info != null?info.Uri(SafariImage.Type.Mystery) : SafariImage.DefaultUri(SafariImage.Type.Mystery);

            var msg = await trashChannel.SendFileAsync(uri);

            return(msg.Attachments.First().Url);
        }
コード例 #7
0
ファイル: Analyze.cs プロジェクト: Xwilarg/Konari
        public static async Task <List <string> > CheckImageUrl(string url, SocketUserMessage msg, SocketMessage arg, ITextChannel reportChan)
        {
            if (Utils.IsImage(url.Split('.').Last()))
            {
                var image = await Google.Cloud.Vision.V1.Image.FetchFromUriAsync(url);

                List <string>        flags    = new List <string>();
                SafeSearchAnnotation response = await Program.P.imageClient.DetectSafeSearchAsync(image);

                if (response.Adult > Likelihood.Possible || response.Medical > Likelihood.Possible ||
                    response.Racy > Likelihood.Possible || response.Violence > Likelihood.Possible)
                {
                    if (response.Adult > Likelihood.Possible)
                    {
                        flags.Add("Adult(" + response.Adult.ToString() + ")");
                    }
                    if (response.Medical > Likelihood.Possible)
                    {
                        flags.Add("Medical(" + response.Medical.ToString() + ")");
                    }
                    if (response.Racy > Likelihood.Possible)
                    {
                        flags.Add("Racy(" + response.Racy.ToString() + ")");
                    }
                    if (response.Violence > Likelihood.Possible)
                    {
                        flags.Add("Violence(" + response.Violence.ToString() + ")");
                    }
                    string fileName = "SPOILER_" + GenerateFileName() + "." + url.Split('.').Last();
                    using (HttpClient hc = new HttpClient())
                        File.WriteAllBytes(fileName, await hc.GetByteArrayAsync(url));
                    string word = (reportChan == null) ? "deleted" : "reported";
                    string text = "The message of " + arg.Author.ToString() + " was " + word + " because it trigger the following flags: " + string.Join(", ", flags);
                    if (reportChan == null)
                    {
                        await msg.Channel.SendMessageAsync(text);

                        await msg.Channel.SendFileAsync(fileName);

                        await msg.DeleteAsync();
                    }
                    else
                    {
                        await reportChan.SendMessageAsync(text);

                        await reportChan.SendFileAsync(fileName);
                    }
                    File.Delete(fileName);
                    return(flags.Select(x => x.Split('(')[0]).ToList());
                }
                flags.Add("SAFE");
                return(flags);
            }
            return(null);
        }
コード例 #8
0
ファイル: Waifu.cs プロジェクト: zsuatem/sanakan
        public async Task <string> GetWaifuProfileImageAsync(Card card, ITextChannel trashCh)
        {
            using (var cardImage = await _img.GetWaifuInProfileCardAsync(card))
            {
                cardImage.SaveToPath($"./GOut/Profile/P{card.Id}.png");

                using (var stream = cardImage.ToPngStream())
                {
                    var fs = await trashCh.SendFileAsync(stream, $"P{card.Id}.png");

                    var im = fs.Attachments.FirstOrDefault();
                    return(im.Url);
                }
            }
        }
コード例 #9
0
        /// <summary>
        ///     Send a welcome message to a couple of users.
        /// </summary>
        /// <param name="channel">The channel in which the message should be send.</param>
        /// <param name="users">The users to welcome.</param>
        /// <returns></returns>
        public async Task Welcome(ITextChannel channel, params IGuildUser[] users)
        {
            var settings = await Load(channel.GuildId);

            var names = string.Join(", ", users.Select(u => u.Mention)).ReplaceLast(", ", " and ");
            var msg   = string.Format(settings.Message, names);

            if (!settings.UseImage)
            {
                await channel.SendMessageAsync(msg);
            }
            else
            {
                await channel.SendFileAsync(ImageExtensions.GetImagePath("GasaiYunoWelcome.jpg"), msg);
            }
        }
コード例 #10
0
ファイル: Extensions.cs プロジェクト: darkclouddev/Rift
        public static async Task <IUserMessage> SendIonicMessageAsync(this ITextChannel channel, IonicMessage message)
        {
            if (message is null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (!string.IsNullOrWhiteSpace(message.ImageUrl))
            {
                var request = WebRequest.Create(message.ImageUrl);

                await using var stream = (await request.GetResponseAsync()).GetResponseStream();
                return(await channel.SendFileAsync(stream, ImageFileName, message.Text ?? "", embed : message.Embed));
            }

            return(await channel.SendMessageAsync(message.Text ?? "", embed : message.Embed)
                   .ConfigureAwait(false));
        }
コード例 #11
0
        public async Task ShowProfile(string welcome, ulong id, IUser user, ITextChannel channel, string cardbg)
        {
            try
            {
                if (userBG.ContainsKey(user.Id))
                {
                    //await DrawText(user.GetAvatarUrl(), user, Context);
                    await DrawProfile(user.GetAvatarUrl(), user, id, welcome, cardbg);
                }
                else
                {
                    //await DrawText2(user.GetAvatarUrl(), user, Context);
                    await DrawProfile(user.GetAvatarUrl(), user, id, welcome, cardbg);
                }
                //await Context.Channel.SendMessageAsync($"Image \n{img}");
                if (File.Exists($"{user.Id}.png"))
                {
                    await channel.SendFileAsync($"{user.Id}.png", $"<@{user.Id}>", false, null);


                    File.Delete($"{user.Id}.png");
                    File.Delete($"{user.Id}Avatar.png");
                    File.Delete($"{user.Id}AvatarF.png");


                    return;
                }
                else
                {
                    await channel.SendMessageAsync($"Failed to create Image! This may be due to the Image you linked is damaged or unsupported. Try a new Custom Pic or use the default Image (p setbg with no parameter sets it to the default image)\n\n Welcome <@{user.Id}> to The server");

                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return;
            }
        }
コード例 #12
0
        /// <summary>
        /// Obtains a Proxied URL from a given Image URL.
        /// </summary>
        /// <param name="ImageURL">The URL of the target image.</param>
        /// <param name="ImageName">The Name to give the image once downloaded.</param>
        /// <param name="DiscordSocketClient">A Discord Socket Client service to parse the storage channel.</param>
        /// <param name="ProposalConfiguration">Configuration holding the storage channel ID.</param>
        /// <returns>A <c>Task</c> object, which can be awaited until this method completes successfully.</returns>

        public static async Task <string> GetProxiedImage(this string ImageURL, string ImageName, DiscordSocketClient DiscordSocketClient, ProposalConfiguration ProposalConfiguration)
        {
            string ImageCacheDir = Path.Combine(Directory.GetCurrentDirectory(), "ImageCache");

            if (!Directory.Exists(ImageCacheDir))
            {
                Directory.CreateDirectory(ImageCacheDir);
            }

            string FilePath = Path.Combine(ImageCacheDir, $"{ImageName}{Path.GetExtension(ImageURL.Split("?")[0])}");

            using WebClient WebClient = new();

            await WebClient.DownloadFileTaskAsync(ImageURL, FilePath);

            ITextChannel Channel = DiscordSocketClient.GetChannel(ProposalConfiguration.StorageChannelID) as ITextChannel;

            IUserMessage AttachmentMSG = await Channel.SendFileAsync(FilePath);

            File.Delete(FilePath);

            return(AttachmentMSG.Attachments.FirstOrDefault().ProxyUrl);
        }
コード例 #13
0
ファイル: Waifu.cs プロジェクト: zsuatem/sanakan
        public async Task <string> GetSafariViewAsync(SafariImage info, Card card, ITextChannel trashChannel)
        {
            string uri = info != null?info.Uri(SafariImage.Type.Truth) : SafariImage.DefaultUri(SafariImage.Type.Truth);

            var cardUri = await GetCardUrlIfExistAsync(card);

            using (var cardImage = await _img.GetWaifuCardAsync(cardUri, card))
            {
                int posX = info != null?info.GetX() : SafariImage.DefaultX();

                int posY = info != null?info.GetY() : SafariImage.DefaultY();

                using (var pokeImage = _img.GetCatchThatWaifuImage(cardImage, uri, posX, posY))
                {
                    using (var stream = pokeImage.ToJpgStream())
                    {
                        var msg = await trashChannel.SendFileAsync(stream, $"poke.jpg");

                        return(msg.Attachments.First().Url);
                    }
                }
            }
        }
コード例 #14
0
        public static async Task HandleUserJoinAsync(SocketGuildUser user, IJoinService joinService)
        {
            if (!GlobalConfiguration.JoinImageEnabled)
            {
                return;
            }

            try
            {
                Stream avatarStream = await joinService.GetStreamFromAvatarUrlAsync(user.GetAvatarUrl(Discord.ImageFormat.Auto, 256));

                Stream templateStream = await joinService.GenerateWelcomeImageAsync(user.Username, user.Discriminator, avatarStream);

                avatarStream.Dispose();

                // TODO: Allow configuration of this channel and message to go with the file.
                ITextChannel textChannel = (ITextChannel)user.Guild.GetChannel(ulong.Parse(GlobalConfiguration.JoinImageChannel));
                await textChannel.SendFileAsync(templateStream, "the-salmon-king-welcomes-you.png", null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #15
0
 public async Task MegaMan(ITextChannel channel)
 {
     DiscordReply("<@!455015701166686208> This you? ");
     await channel.SendFileAsync(Path.Combine(Handler._Config.SavePath, @"ChatFiles\megaman.png")); return;
 }
コード例 #16
0
ファイル: BooruModule.cs プロジェクト: drogs/Sanara
#pragma warning restore CS1998

        /// <summary>
        /// Get an image given various informations
        /// </summary>
        /// <param name="booru">Which booru is concerned (see above)</param>
        /// <param name="tags">Tags that need to be contain on the image</param>
        /// <param name="chan">Channel the image will be post in</param>
        /// <param name="currName">Temporary name of the file</param>
        /// <param name="isSfw">Is the channel safe for work ?</param>
        /// <param name="isGame">If the request from Game module (doesn't count dl for stats and don't get informations about tags)</param>
        public static async void getImage(Booru booru, string[] tags, ITextChannel chan, string currName, bool isSfw, bool isGame)
        {
            if (!isSfw && !chan.IsNsfw)
            {
                await chan.SendMessageAsync(Sentences.chanIsNotNsfw(chan.GuildId));

                return;
            }
            IGuildUser me = await chan.Guild.GetUserAsync(Sentences.myId);

            if (!me.GuildPermissions.AttachFiles)
            {
                await chan.SendMessageAsync(Sentences.needAttachFile(chan.GuildId));

                return;
            }
            if (!isGame)
            {
                await chan.SendMessageAsync(Sentences.prepareImage(chan.GuildId));
            }
            string url = getBooruUrl(booru, tags);

            if (url == null)
            {
                await chan.SendMessageAsync(Sentences.tagsNotFound(tags));
            }
            else
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Headers.Add("User-Agent: Sanara");
                    string json      = wc.DownloadString(url);
                    string image     = booru.getFileUrl(json);
                    string imageName = currName + "." + image.Split('.')[image.Split('.').Length - 1];
                    wc.Headers.Add("User-Agent: Sanara");
                    wc.DownloadFile(image, imageName);
                    FileInfo file = new FileInfo(imageName);
                    Program.p.statsMonth[(int)booru.getId()] += file.Length;
                    if (file.Length >= 8000000)
                    {
                        await chan.SendMessageAsync(Sentences.fileTooBig(chan.GuildId));
                    }
                    else
                    {
                        while (true)
                        {
                            try
                            {
                                await chan.SendFileAsync(imageName);

                                break;
                            }
                            catch (RateLimitedException) { }
                        }
                        if (!isGame)
                        {
                            List <string> finalStr = getTagsInfos(json, booru);
                            foreach (string s in finalStr)
                            {
                                await chan.SendMessageAsync(s);
                            }
                        }
                    }
                    File.Delete(imageName);
                }
                if (!isGame)
                {
                    string finalStrModule = "";
                    foreach (long i in Program.p.statsMonth)
                    {
                        finalStrModule += i + "|";
                    }
                    finalStrModule = finalStrModule.Substring(0, finalStrModule.Length - 1);
                    File.WriteAllText("Saves/MonthModules.dat", finalStrModule + Environment.NewLine + Program.p.lastMonthSent);
                }
            }
        }
コード例 #17
0
 public async Task tOne(ITextChannel channel)
 {
     DiscordReply("Terraria One is a Multiplayer Server");
     await channel.SendFileAsync(Path.Combine(Handler._Config.SavePath, @"ChatFiles\tone.mov")); return;
 }
コード例 #18
0
 public async Task Tucanu(ITextChannel channel)
 {
     DiscordReply("<@340227862990684162> This you? ");
     await channel.SendFileAsync(Path.Combine(Handler._Config.SavePath, @"ChatFiles\tucanu.png")); return;
 }
コード例 #19
0
ファイル: SystemExtensions.cs プロジェクト: Ultz/Volte
 public static Task <IUserMessage> SendFileToAsync(this MemoryStream stream,
                                                   ITextChannel channel, string filename, string text = null, bool isTts = false, Embed embed = null,
                                                   RequestOptions options = null,
                                                   bool isSpoiler         = false, AllowedMentions allowedMentions = null, MessageReference reference = null)
 => channel.SendFileAsync(stream, filename, text, isTts, embed, options, isSpoiler, allowedMentions,
                          reference);