예제 #1
0
        public static async void GetIllustDetail(SoraMessage e, int id)
        {
            var detail = await Illust.Get(id);

            if (detail == null)
            {
                await e.ReplyToOriginal("数据获取失败,请稍后再试");
            }
            else
            {
                ArrayList msg = new();
                foreach (var img in detail.Images)
                {
                    msg.Add(CQCode.CQImage(ImageUrls.ToPixivCat(img.Medium)));
                }
                msg.Add(new StringBuilder().AppendLine()
                        .AppendLine(detail.Title)
                        .AppendLine($"Author: {detail.Author}")
                        .AppendLine(detail.Caption)
                        .AppendLine($"Tags: {string.Join(" | ", detail.Tags)}")
                        .AppendLine($"Publish Date: {detail.CreateDate:yyyy-MM-dd hh:mm:ss}")
                        .AppendLine($"Bookmarks: {detail.TotalBookmarks} Comments:{detail.TotalComments} Views:{detail.TotalView}")
                        .Append(detail.Url)
                        .ToString());
                await e.Reply(msg.ToArray());

                await e.RemoveCoins(5);
            }
        }
예제 #2
0
        public CQCode GetRandCos()
        {
            //https://moe.ci/api.php https://moe.ci/Store/03-808P/0448.jpg
            var url = HttpNet.GetRedirectUrl("https://moe.ci/api.php");

            return(CQCode.CQImage(url, useCache: true));
        }
예제 #3
0
        public static async ValueTask <CQCode> Image(string url, CQFileType type = default, IHttpClientFactory httpClientFactory = default)
        {
            HttpClient client;

            byte[] data;
            switch (type)
            {
            case CQFileType.Url:
                return(CQCode.CQImage(url));

            case CQFileType.Base64:
                client = httpClientFactory == default ? new HttpClient() : httpClientFactory.CreateClient("default");
                data   = await client.GetByteArrayAsync(url);

                return(CQCode.CQImage("base64://" + Convert.ToBase64String(data)));

            case CQFileType.File:
                Uri uri = new(url);
                client = httpClientFactory == default ? new HttpClient() : httpClientFactory.CreateClient("default");
                data   = await client.GetByteArrayAsync(uri);

                var filePath = ImageCachePath + HashHelp.MD5Encrypt(data) + Path.GetExtension(uri.Segments.Last());
                await File.WriteAllBytesAsync(filePath, data);

                return(CQCode.CQImage(new Uri(filePath).AbsoluteUri));

            default:
                return(null);
            }
        }
예제 #4
0
 /// <summary>
 /// 私聊处理
 /// </summary>
 public static async ValueTask PrivateMessageParse(object sender, PrivateMessageEventArgs privateMessage)
 {
     //简单的机器人响应
     if (privateMessage.Message.RawText.Equals("在"))
     {
         await privateMessage.Sender.SendPrivateMessage(CQCode.CQImage("https://i.loli.net/2020/11/02/2OgZ1M6YNV5kntS.gif"));
     }
 }
예제 #5
0
        static async Task SendGif(SoraMessage e, Image <Rgba32> gif)
        {
            var file = Path.GetTempFileName();

            SaveGif(gif, file);
            await e.Reply(CQCode.CQImage(file));

            await e.RemoveCoins(5);
        }
예제 #6
0
 internal static async ValueTask GroupPokeEventParse(object sender, GroupPokeEventArgs groupPokeEventArgs)
 {
     if (groupPokeEventArgs.TargetUser == groupPokeEventArgs.LoginUid &&
         !CheckInCD.isInCD(groupPokeEventArgs.SourceGroup, groupPokeEventArgs.SendUser))
     {
         await groupPokeEventArgs.SourceGroup.SendGroupMessage(CQCode.CQAt(groupPokeEventArgs.SendUser),
                                                               "\r\n你今晚必被爽哥杀害\r\n",
                                                               CQCode.CQImage("https://i.loli.net/2020/10/20/zWPyocxFEVp2tDT.jpg"));
     }
 }
예제 #7
0
 public object GetCosHot()
 {
     if (BiliBili.GetCosHot(out string[] urls))
     {
         return(urls.Select(url => CQCode.CQImage(url)));
     }
     else
     {
         return(CQCode.CQText("获取失败"));
     }
 }
예제 #8
0
 public async ValueTask GroupPokeEventParse(object sender, GroupPokeEventArgs eventArgs)
 {
     if (eventArgs.TargetUser == eventArgs.LoginUid &&
         !CheckInCD.IsInCD(eventArgs.SourceGroup, eventArgs.SendUser))
     {
         await eventArgs
         .SourceGroup
         .SendGroupMessage(
             CQCode.CQAt(eventArgs.SendUser),
             "\r\n再戳锤爆你的头\r\n",
             CQCode.CQImage("https://i.loli.net/2020/10/20/zWPyocxFEVp2tDT.jpg"));
     }
 }
예제 #9
0
        private async void SendLocalPic(Hso hso)
        {
            string[] picNames = Directory.GetFiles(IOUtils.GetHsoPath());
            if (picNames.Length == 0)
            {
                await QQGroup.SendGroupMessage("机器人管理者没有在服务器上塞色图\r\n你去找他要啦!");

                return;
            }

            Random randFile     = new Random();
            string localPicPath = $"{picNames[randFile.Next(0, picNames.Length - 1)]}";

            Log.Debug("发送图片", localPicPath);
            await QQGroup.SendGroupMessage(hso.CardImage
                                           ?CQCode.CQCardImage(localPicPath)
                                           : CQCode.CQImage(localPicPath));
        }
예제 #10
0
        private async ValueTask <EventResult <BaseMsgQuickOperation> > Handler(BaseMessageEventArgs args, IOneBotApi api)
        {
            long?groupId = null;
            long?userId  = null;

            if (args is GroupMsgEventArgs groupArgs)
            {
                groupId = groupArgs.GroupId;
            }
            else
            {
                userId = args.UserId;
            }

            if (args.RawMessage.Equals(_globalService.YandeSetting.HotImg.Command,
                                       StringComparison.CurrentCultureIgnoreCase))
            {
                var(data, rating) = await _yandeService.Value.GetHotImgAsync(_globalService.YandeSetting.HotImg.Rating);

                var replay = CQCode.CQImage("base64://" + Convert.ToBase64String(data));
                return(1, replay);
            }

            foreach (var customTags in _globalService.YandeSetting.CustomTags)
            {
                if (args.RawMessage.Equals(customTags.Command, StringComparison.CurrentCultureIgnoreCase))
                {
                    var page = await _yandeService.Value.GetTagsPageAsync(customTags.Tag);

                    for (var i = 0; i < customTags.Count; i++)
                    {
                        var _ = Task.Run(async() =>
                        {
                            var(data, rating) = await _yandeService.Value.GetImageByTagsAsync(customTags.Tag, page, customTags.Rating);
                            await api.SendMsg(userId, groupId, new[] { CQCode.CQImage("base64://" + Convert.ToBase64String(data)) });
                        });
                    }

                    return(1);
                }
            }

            return(null);
        }
예제 #11
0
        static async Task Main(string[] args)
        {
            ConsoleLog.SetLogLevel(LogLevel.Debug);
            ConsoleLog.Debug("dotnet version", Environment.Version);

            SoraWSServer server = new SoraWSServer(new ServerConfig {
                Port = 8080
            });

            //服务器连接事件
            server.ConnManager.OnOpenConnectionAsync += (connectionInfo, eventArgs) =>
            {
                ConsoleLog.Debug("Sora_Test",
                                 $"connectionId = {connectionInfo.Id} type = {eventArgs.Role}");
                return(ValueTask.CompletedTask);
            };
            //服务器连接关闭事件
            server.ConnManager.OnCloseConnectionAsync += (connectionInfo, eventArgs) =>
            {
                ConsoleLog.Debug("Sora_Test",
                                 $"connectionId = {connectionInfo.Id} type = {eventArgs.Role}");
                return(ValueTask.CompletedTask);
            };
            //服务器心跳包超时事件
            server.ConnManager.OnHeartBeatTimeOut += (connectionInfo, eventArgs) =>
            {
                ConsoleLog.Debug("Sora_Test",
                                 $"Get heart beat time out from[{connectionInfo.Id}] uid[{eventArgs.SelfId}]");
                return(ValueTask.CompletedTask);
            };
            //群聊消息事件
            server.Event.OnGroupMessage += async(sender, eventArgs) =>
            {
                await eventArgs.SourceGroup.SendGroupMessage("好耶");
            };
            //私聊消息事件
            server.Event.OnPrivateMessage += async(sender, eventArgs) =>
            {
                await eventArgs.Sender.SendPrivateMessage(CQCode.CQImage("E:\\P\\83128088_p0.png"));
            };

            await server.StartServer().RunCatch();
        }
예제 #12
0
 public CQCode GetHotImg(int rating = 7, bool 防止和谐 = true, bool 发送提示 = true)
 {
     if (发送提示)
     {
         _eventArgs.Reply(CQCode.CQText("少女祈祷中..."));
     }
     try
     {
         var data = _yande.GetHotImg(out string imgRating, rating);
         if (防止和谐 && (imgRating == "Explicit" || imgRating == "Questionable"))
         {
             data = ChangeMd5(data);
         }
         return(CQCode.CQImage("base64://" + Convert.ToBase64String(data)));
     }
     catch (Exception e)
     {
         return(CQCode.CQText("请求发生了错误:\n" + e.Message));
     }
 }
예제 #13
0
 /// <summary>
 /// 获取需要发送的消息
 /// </summary>
 /// <param name="entity">Feedlist</param>
 /// <returns></returns>
 public object[] GetMessages(Feedlist entity)
 {
     object[] o;
     //有图
     if (entity.moment.imgs != null)
     {
         o    = new object[entity.moment.imgs.Length + 1];
         o[0] = entity.user.userName + ":" + entity.moment.replaceUbbText;;
         for (int i = 1; i <= entity.moment.imgs.Length; i++)
         {
             o[i] = CQCode.CQImage(entity.moment.imgs[i - 1].originUrl);
         }
     }
     //无图
     else
     {
         o    = new object[1];
         o[0] = entity.user.userName + ":" + entity.moment.replaceUbbText;
     }
     return(o);
 }
예제 #14
0
        public async void GetImgByTag(string tag, int count = 1, bool 防止和谐 = true,
                                      bool 发送提示             = true)
        {
            if (发送提示)
            {
                _eventArgs.Reply(CQCode.CQText("少女祈祷中..."));
            }
            int page = _yande.GetTagsPage(tag);

            if (page == 0)
            {
                _eventArgs.Reply(CQCode.CQText("发生了未知错误"));
            }
            else
            {
                var tasks = new List <Task>();
                for (int i = 0; i < count; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        try
                        {
                            var data = _yande.GetImageByTags(tag, out string imgRating, page > 20 ? 20 : page);
                            if (防止和谐 && (imgRating == "Explicit" || imgRating == "Questionable"))
                            {
                                data = ChangeMd5(data);
                            }
                            _eventArgs.Reply(CQCode.CQImage("base64://" + Convert.ToBase64String(data)));
                        }
                        catch (Exception e)
                        {
                            _eventArgs.Reply(CQCode.CQText("请求发生了错误:\n" + e.Message));
                        }
                    }));
                }

                await Task.WhenAll(tasks.ToArray());
            }
        }
예제 #15
0
        public static async void ServerStatus(SoraMessage e, string target)
        {
            var    x    = _ServerRegex.Match(target);
            string host = x.Groups["host"].Value;
            ushort port = 25565;

            if (ushort.TryParse(x.Groups["port"].Value, out ushort _port))
            {
                port = _port;
            }
            ServerInfo info = new ServerInfo(host, port);
            await info.StartGetServerInfoAsync();

            if (info.State == ServerInfo.StateType.GOOD)
            {
                var sb = new StringBuilder();
                sb.AppendLine("[Minecraft Server Status]");
                sb.AppendLine($"IP: {host}:{port}");
                sb.AppendLine($"Version: {info.GameVersion}");
                sb.AppendLine($"Players: {info.CurrentPlayerCount} / {info.MaxPlayerCount}");
                sb.AppendLine($"Latency: {info.Ping}ms");
                sb.AppendLine($"MOTD:").Append(info.MOTD);
                if (info.IconData != null)
                {
                    var icon = new MemoryImage(new Bitmap(new MemoryStream(info.IconData)));
                    await e.Reply(CQCode.CQImage(icon.ToBase64File()), Environment.NewLine, sb.ToString());
                }
                else
                {
                    await e.Reply(sb.ToString());
                }
            }
            else
            {
                await e.ReplyToOriginal("未能成功获取到目标服务器的数据,可能为参数输入错误或目标已离线");
            }
        }
예제 #16
0
        public static async void Play(SoraMessage e, long id)
        {
            var detail = await CloudMusicApi.GetSongDetail(id);

            if (detail == null)
            {
                await e.ReplyToOriginal("曲目信息获取失败");
            }
            else
            {
                var url = await CloudMusicApi.GetSongUrl(id, 128000);

                if (url.Id == detail.Id && url.Id == id)
                {
                    await e.Reply(CQCode.CQImage(detail.Album.GetPicUrl(512, 512)),
                                  new StringBuilder().AppendLine()
                                  .AppendLine("♬ " + detail.Name)
                                  .AppendLine("✎ " + string.Join(" / ", detail.Artists))
                                  .AppendLine(detail.Url)
                                  .Append("√ 曲目链接已解析,正在下载中……")
                                  .ToString());

                    await e.Reply(CQCode.CQRecord(url.Url));
                }
                else
                {
                    await e.Reply(CQCode.CQImage(detail.Album.GetPicUrl(512, 512)),
                                  new StringBuilder().AppendLine()
                                  .AppendLine("♬ " + detail.Name)
                                  .AppendLine("✎ " + string.Join(" / ", detail.Artists))
                                  .AppendLine(detail.Url)
                                  .Append("× 解析曲目链接失败")
                                  .ToString());
                }
            }
        }
예제 #17
0
        /// <summary>
        /// 构建发送用的消息段
        /// </summary>
        /// <param name="picInfo">图片信息Json</param>
        /// <param name="cardImg">是否为装逼大图</param>
        /// <param name="picStr">图片路径/b64字符串</param>
        private List <CQCode> HsoMessageBuilder(JToken picInfo, bool cardImg, string picStr)
        {
            StringBuilder textBuilder = new StringBuilder();

            textBuilder.Append(picInfo["title"]);
            textBuilder.Append("\r\nid:");
            textBuilder.Append(picInfo["pid"]);
            if (picInfo["index"] != null)
            {
                textBuilder.Append(" - ");
                textBuilder.Append(picInfo["index"]);
            }

            textBuilder.Append("\r\n作者:");
            textBuilder.Append(picInfo["author"]);
            //构建消息
            List <CQCode> msg = new();

            msg.Add(cardImg
                        ? CQCode.CQCardImage(picStr)
                        : CQCode.CQImage(picStr));
            msg.Add(CQCode.CQText(textBuilder.ToString()));
            return(msg);
        }
예제 #18
0
        /// <summary>
        /// <para>从色图源获取色图</para>
        /// <para>不会支持R18的哦</para>
        /// </summary>
        /// <param name="hso">hso配置实例</param>
        private async Task GiveMeSetu(Hso hso)
        {
            string  localPicPath;
            JObject response;

            ConsoleLog.Debug("源", hso.Source);
            //本地模式
            if (hso.Source == SetuSourceType.Local)
            {
                string[] picNames = Directory.GetFiles(IOUtils.GetHsoPath());
                if (picNames.Length == 0)
                {
                    await QQGroup.SendGroupMessage("机器人管理者没有在服务器上塞色图\r\n你去找他要啦!");

                    return;
                }
                Random randFile = new Random();
                localPicPath = $"{picNames[randFile.Next(0, picNames.Length - 1)]}";
                ConsoleLog.Debug("发送图片", localPicPath);
                await QQGroup.SendGroupMessage(hso.CardImage
                                               ?CQCode.CQCardImage(localPicPath)
                                               : CQCode.CQImage(localPicPath));

                return;
            }
            //网络部分
            try
            {
                ConsoleLog.Info("NET", "尝试获取色图");
                await QQGroup.SendGroupMessage("正在获取色图中...");

                string apiKey;
                string serverUrl;
                //源切换
                switch (hso.Source)
                {
                case SetuSourceType.Mix:
                    Random randSource = new Random();
                    if (randSource.Next(1, 100) > 50)
                    {
                        serverUrl = "https://api.lolicon.app/setu/";
                        apiKey    = hso.LoliconApiKey ?? string.Empty;
                    }
                    else
                    {
                        serverUrl = "https://api.yukari.one/setu/";
                        apiKey    = hso.YukariApiKey ?? string.Empty;
                    }
                    break;

                case SetuSourceType.Yukari:
                    serverUrl = "https://api.yukari.one/setu/";
                    apiKey    = hso.YukariApiKey ?? string.Empty;
                    break;

                case SetuSourceType.Lolicon:
                    serverUrl = "https://api.yukari.one/setu/";
                    apiKey    = hso.YukariApiKey ?? string.Empty;
                    break;

                default:
                    await QQGroup.SendGroupMessage("发生了未知错误");

                    ConsoleLog.Error("Hso", "发生了未知错误");
                    return;
                }
                //向服务器发送请求
                ReqResponse reqResponse = await Requests.GetAsync(serverUrl, new ReqParams
                {
                    Timeout = 3000,
                    Params  = new Dictionary <string, string>
                    {
                        { "apikey", apiKey }
                    }
                });

                if (reqResponse.StatusCode != HttpStatusCode.OK)
                {
                    ConsoleLog.Error("Net", $"{serverUrl} return code {(int)reqResponse.StatusCode}");
                    await HsoEventArgs.SourceGroup.SendGroupMessage($"哇哦~发生了网络错误[{reqResponse.StatusCode}],请联系机器人所在服务器管理员");

                    return;
                }
                response = reqResponse.Json();
                ConsoleLog.Debug("Get Json", response);
            }
            catch (Exception e)
            {
                //网络错误
                await QQGroup.SendGroupMessage("哇哦~发生了网络错误,请联系机器人所在服务器管理员");

                ConsoleLog.Error("网络发生错误", ConsoleLog.ErrorLogBuilder(e.InnerException));
                return;
            }
            //json处理
            try
            {
                if ((int)response["code"] == 0)
                {
                    //图片链接
                    string picUrl = response["data"]?[0]?["url"]?.ToString() ?? "";
                    ConsoleLog.Debug("获取到图片", picUrl);
                    //本地图片存储路径
                    localPicPath = $"{IOUtils.GetHsoPath()}/{Path.GetFileName(picUrl)}".Replace('\\', '/');
                    if (File.Exists(localPicPath)) //检查是否已缓存过图片
                    {
                        await QQGroup.SendGroupMessage(hso.CardImage
                                                       ?CQCode.CQCardImage(localPicPath)
                                                       : CQCode.CQImage(localPicPath));
                    }
                    else
                    {
                        //文件名处理(mirai发送网络图片时pixivcat会返回403暂时无法使用代理发送图片
                        //QQGroup.SendGroupMessage(CQApi.Mirai_UrlImage(picUrl));

                        //检查是否有设置代理
                        if (!string.IsNullOrEmpty(hso.PximyProxy))
                        {
                            string[]      fileNameArgs    = Regex.Split(Path.GetFileName(picUrl), "_p");
                            StringBuilder proxyUrlBuilder = new StringBuilder();
                            proxyUrlBuilder.Append(hso.PximyProxy);
                            //图片Pid部分
                            proxyUrlBuilder.Append(hso.PximyProxy.EndsWith("/") ? $"{fileNameArgs[0]}" : $"/{fileNameArgs[0]}");
                            //图片Index部分
                            proxyUrlBuilder.Append(fileNameArgs[1].Split('.')[0].Equals("0") ? string.Empty : $"/{fileNameArgs[1].Split('.')[0]}");
                            ConsoleLog.Debug("Get Proxy Url", proxyUrlBuilder);
                            DownloadFileFromURL(proxyUrlBuilder.ToString(), localPicPath, hso.UseCache, hso.CardImage);
                        }
                        else
                        {
                            DownloadFileFromURL(picUrl, localPicPath, hso.UseCache, hso.CardImage);
                        }
                    }
                    return;
                }
                if (((int)response["code"] == 401 || (int)response["code"] == 429) &&
                    hso.Source == SetuSourceType.Lolicon)
                {
                    ConsoleLog.Warning("API Token 失效", $"code:{response["code"]}");
                }
                else
                {
                    ConsoleLog.Warning("没有找到图片信息", "服务器拒绝提供信息");
                }
                await QQGroup.SendGroupMessage("哇奧色图不见了\n请联系机器人服务器管理员");
            }
            catch (Exception e)
            {
                ConsoleLog.Error("色图下载失败", $"网络下载数据错误\n{ConsoleLog.ErrorLogBuilder(e)}");
            }
        }
예제 #19
0
        /// <summary>
        /// 下载图片保存到本地
        /// </summary>
        /// <param name="url">目标URL</param>
        /// <param name="receivePath">接收文件的地址</param>
        /// <param name="useCache">是否启用本地缓存</param>
        /// <param name="cardImg">使用装逼大图</param>
        private void DownloadFileFromURL(string url, string receivePath, bool useCache, bool cardImg)
        {
            try
            {
                int      progressPercentage = 0;
                long     bytesReceived      = 0;
                DateTime flashTime          = DateTime.Now;
                Console.WriteLine(@"开始从网络下载文件");
                WebClient client = new WebClient();
                //文件下载
                client.DownloadProgressChanged += (sender, args) =>
                {
                    if (progressPercentage == args.ProgressPercentage)
                    {
                        return;
                    }
                    progressPercentage = args.ProgressPercentage;
                    ConsoleLog
                    .Debug("Download Pic", $"Downloading {args.ProgressPercentage}% " +
                           $"({(args.BytesReceived - bytesReceived) / 1024.0 / ((DateTime.Now - flashTime).TotalMilliseconds / 1000)}KB/s) ");
                    flashTime     = DateTime.Now;
                    bytesReceived = args.BytesReceived;
                };
                //文件下载完成
                client.DownloadFileCompleted += async(sender, args) =>
                {
                    ConsoleLog.Info("Hso", "下载数据成功,发送图片");
                    var(code, _) = await QQGroup.SendGroupMessage(cardImg
                                                                  ?CQCode.CQCardImage(receivePath)
                                                                  : CQCode.CQImage(receivePath));

                    ConsoleLog.Debug("file", Path.GetFileName(receivePath));
                    if (code == APIStatusType.OK)
                    {
                        ConsoleLog.Info("Hso", "色图发送成功");
                    }
                    else
                    {
                        ConsoleLog.Error("Hso", $"色图发送失败 code={(int) code}");
                        await QQGroup.SendGroupMessage($"哇奧色图不见了\r\n色图发送失败了\r\nAPI ERROR [{code}]");
                    }
                    //检查是否出现空文件
                    if (code == APIStatusType.OK || !File.Exists(receivePath))
                    {
                        return;
                    }
                    FileInfo file = new FileInfo(receivePath);
                    ConsoleLog.Debug("File Size Check", file.Length);
                    if (file.Length != 0)
                    {
                        return;
                    }
                    ConsoleLog.Error("Hso", "色图下载失败");
                    //删除下载失败的文件
                    try
                    {
                        file.Delete();
                    }
                    catch (Exception e)
                    {
                        ConsoleLog.Error("IO", ConsoleLog.ErrorLogBuilder(e));
                    }
                };
                client.DownloadDataCompleted += async(sender, args) =>
                {
                    ConsoleLog.Info("Hso", "下载数据成功,发送图片");
                    try
                    {
                        StringBuilder ImgBase64Str = new StringBuilder();
                        ImgBase64Str.Append("base64://");
                        ImgBase64Str.Append(Convert.ToBase64String(args.Result));
                        var(code, _) = await QQGroup.SendGroupMessage(cardImg
                                                                      ?CQCode.CQCardImage(ImgBase64Str.ToString())
                                                                      : CQCode.CQImage(ImgBase64Str.ToString()));

                        if (code == APIStatusType.OK)
                        {
                            ConsoleLog.Info("Hso", "色图发送成功");
                        }
                        else
                        {
                            ConsoleLog.Error("Hso", $"色图发送失败 code={(int) code}");
                            await QQGroup.SendGroupMessage($"哇奧色图不见了\r\n色图发送失败了\r\nAPI ERROR [{code}]");
                        }
                        ConsoleLog.Debug("base64 length", ImgBase64Str.Length);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                };
                if (useCache)
                {
                    client.DownloadFileAsync(new Uri(url), receivePath);
                }
                else
                {
                    client.DownloadDataAsync(new Uri(url));
                }
            }
            catch (Exception e)
            {
                ConsoleLog.Error("色图下载失败", $"网络下载数据错误\n{ConsoleLog.ErrorLogBuilder(e)}");
            }
        }
예제 #20
0
        private static async ValueTask GetLiveStatus(SoraApi soraApi, long biliUser, List <long> groupId,
                                                     SubscriptionDBHelper dbHelper)
        {
            LiveInfo      live;
            UserSpaceInfo biliUserInfo;

            //获取数据
            try
            {
                biliUserInfo = UserApis.GetLiveRoomInfo(biliUser);
                live         = LiveAPIs.GetLiveRoomInfo(biliUserInfo.LiveRoomInfo.ShortId);
            }
            catch (Exception e)
            {
                Log.Error("获取直播状态时发生错误", Log.ErrorLogBuilder(e));
                return;
            }

            //需要更新数据的群
            Dictionary <long, LiveStatusType> updateDict = groupId
                                                           .Where(gid => dbHelper.GetLastLiveStatus(gid, biliUser) !=
                                                                  live.LiveStatus)
                                                           .ToDictionary(gid => gid, _ => live.LiveStatus);

            //更新数据库
            foreach (var status in updateDict)
            {
                if (!dbHelper.UpdateLiveStatus(status.Key, biliUser, live.LiveStatus))
                {
                    Log.Error("Database", "更新直播订阅数据失败");
                }
            }

            //需要消息提示的群
            var targetGroup = updateDict.Where(group => group.Value == LiveStatusType.Online)
                              .Select(group => group.Key)
                              .ToList();

            if (targetGroup.Count == 0)
            {
                return;
            }
            //构建提示消息
            List <CQCode> msgList = new();
            StringBuilder message = new StringBuilder();

            message.Append(biliUserInfo.Name);
            message.Append(" 正在直播!\r\n");
            message.Append(biliUserInfo.LiveRoomInfo.Title);
            msgList.Add(CQCode.CQText(message.ToString()));
            msgList.Add(CQCode.CQImage(biliUserInfo.LiveRoomInfo.CoverUrl));
            message.Clear();
            message.Append("直播间地址:");
            message.Append(biliUserInfo.LiveRoomInfo.LiveUrl);
            msgList.Add(CQCode.CQText(message.ToString()));
            foreach (var gid in targetGroup)
            {
                Log.Info("直播订阅", $"获取到{biliUserInfo.Name}正在直播,向群[{gid}]发送动态信息");
                await soraApi.SendGroupMessage(gid, msgList);
            }
        }
예제 #21
0
        private static async ValueTask GetDynamic(SoraApi soraApi, long biliUser, List <long> groupId,
                                                  SubscriptionDBHelper dbHelper)
        {
            string        textMessage;
            Dynamic       biliDynamic;
            List <string> imgList = new();

            //获取动态文本
            try
            {
                var cardData = DynamicAPIs.GetLatestDynamic(biliUser);
                switch (cardData.cardType)
                {
                //检查动态类型
                case CardType.PlainText:
                    PlainTextCard plainTextCard = (PlainTextCard)cardData.cardObj;
                    textMessage = plainTextCard.ToString();
                    biliDynamic = plainTextCard;
                    break;

                case CardType.TextAndPic:
                    TextAndPicCard textAndPicCard = (TextAndPicCard)cardData.cardObj;
                    imgList.AddRange(textAndPicCard.ImgList);
                    textMessage = textAndPicCard.ToString();
                    biliDynamic = textAndPicCard;
                    break;

                case CardType.Forward:
                    ForwardCard forwardCard = (ForwardCard)cardData.cardObj;
                    textMessage = forwardCard.ToString();
                    biliDynamic = forwardCard;
                    break;

                case CardType.Video:
                    VideoCard videoCard = (VideoCard)cardData.cardObj;
                    imgList.Add(videoCard.CoverUrl);
                    textMessage = videoCard.ToString();
                    biliDynamic = videoCard;
                    break;

                case CardType.Error:
                    //Log.Error("动态获取", $"ID:{biliUser}的动态获取失败");
                    return;

                default:
                    Log.Debug("动态获取", $"ID:{biliUser}的动态获取成功,动态类型未知");
                    foreach (var gid in groupId)
                    {
                        if (!dbHelper.UpdateDynamic(gid, biliUser, BotUtils.GetNowStampLong()))
                        {
                            Log.Error("数据库", "更新动态记录时发生了数据库错误");
                        }
                    }

                    return;
                }
            }
            catch (Exception e)
            {
                Log.Error("获取动态更新时发生错误", Log.ErrorLogBuilder(e));
                return;
            }

            //获取用户信息
            UserInfo sender = biliDynamic.GetUserInfo();

            Log.Debug("动态获取", $"{sender.UserName}的动态获取成功");
            //检查是否是最新的
            List <long> targetGroups = groupId
                                       .Where(@group => !dbHelper.IsLatestDynamic(@group, sender.Uid,
                                                                                  biliDynamic.UpdateTime))
                                       .ToList();

            //没有群需要发送消息
            if (targetGroups.Count == 0)
            {
                Log.Debug("动态获取", $"{sender.UserName}的动态已是最新");
                return;
            }

            //构建消息
            List <CQCode> msgList    = new();
            StringBuilder msgBuilder = new();

            msgBuilder.Append("获取到了来自 ");
            msgBuilder.Append(sender.UserName);
            msgBuilder.Append(" 的动态:\r\n");
            msgBuilder.Append(textMessage);
            msgList.Add(CQCode.CQText(msgBuilder.ToString()));
            //添加图片
            imgList.ForEach(imgUrl => msgList.Add(CQCode.CQImage(imgUrl)));
            msgBuilder.Clear();
            msgBuilder.Append("\r\n更新时间:");
            msgBuilder.Append(biliDynamic.UpdateTime.ToString("MM-dd HH:mm:ss"));
            msgList.Add(CQCode.CQText(msgBuilder.ToString()));
            //向未发生消息的群发送消息
            foreach (var targetGroup in targetGroups)
            {
                Log.Info("动态获取", $"获取到{sender.UserName}的最新动态,向群{targetGroup}发送动态信息");
                await soraApi.SendGroupMessage(targetGroup, msgList);

                if (!dbHelper.UpdateDynamic(targetGroup, sender.Uid, biliDynamic.UpdateTime))
                {
                    Log.Error("数据库", "更新动态记录时发生了数据库错误");
                }
            }
        }
예제 #22
0
        /// <summary>
        /// <para>从色图源获取色图</para>
        /// <para>不会支持R18的哦</para>
        /// </summary>
        /// <param name="hso">hso配置实例</param>
        private static async Task GeneaterHso(Hso hso, Sora.Entities.Group group)
        {
            string localPicPath;

            ConsoleLog.Debug("源", hso.Source);
            //本地模式
            if (hso.Source == SetuSourceType.Local)
            {
                string[] picNames = Directory.GetFiles(IOUtils.GetHsoPath());
                if (picNames.Length == 0)
                {
                    await group.SendGroupMessage("机器人管理者没有在服务器上塞色图\r\n你去找他要啦!");

                    return;
                }
                Random randFile = new();
                localPicPath = $"{picNames[randFile.Next(0, picNames.Length - 1)]}";
                ConsoleLog.Debug("发送图片", localPicPath);
                await group.SendGroupMessage(hso.CardImage
                                             ?CQCode.CQCardImage(localPicPath)
                                             : CQCode.CQImage(localPicPath));

                return;
            }
            //网络部分
            try
            {
                ConsoleLog.Info("NET", "尝试获取色图");
                string apiKey;
                string serverUrl;
                //源切换
                switch (hso.Source)
                {
                case SetuSourceType.Mix:
                    Random randSource = new();
                    if (randSource.Next(1, 100) > 50)
                    {
                        serverUrl = "https://api.lolicon.app/setu/";
                        apiKey    = hso.LoliconApiKey ?? string.Empty;
                    }
                    else
                    {
                        serverUrl = "https://api.yukari.one/setu/";
                        apiKey    = hso.YukariApiKey ?? string.Empty;
                    }
                    break;

                case SetuSourceType.Yukari:
                    serverUrl = "https://api.yukari.one/setu/";
                    apiKey    = hso.YukariApiKey ?? string.Empty;
                    break;

                case SetuSourceType.Lolicon:
                    serverUrl = "https://api.yukari.one/setu/";
                    apiKey    = hso.LoliconApiKey ?? string.Empty;
                    break;

                default:
                    await group.SendGroupMessage("发生了未知错误");

                    ConsoleLog.Error("Hso", "发生了未知错误");
                    return;
                }
                //向服务器发送请求
                var json = await HttpHelper.HttpGetAsync($"{serverUrl}?apikey={apiKey}&r18={hso.R18}");

                var result = JsonConvert.DeserializeObject <HsoResponseModel>(json);
                if (result != null && result.Code == 0)
                {
                    await group.SendGroupMessage(GetResult(result));

                    await group.SendGroupMessage(CQCode.CQImage(result.Data.First().Url));
                }
                else
                {
                    await group.SendGroupMessage("发生了未知错误");
                }
                ConsoleLog.Debug("Get Json", json);
            }
            catch (Exception e)
            {
                //网络错误
                await group.SendGroupMessage("网络错误,暂时没有请求到~");

                ConsoleLog.Error("网络发生错误", ConsoleLog.ErrorLogBuilder(e.InnerException));
                return;
            }
            //https://dotnet.microsoft.com/download/dotnet/current/runtime
        }
예제 #23
0
        static async void _GetIllustDetail(int id, Action <object[]> Reply, Action <object[]> SendMessage, bool slient = false)
        {
            try
            {
                var detail = await Illust.Get(id);

                if (detail == null)
                {
                    if (!slient)
                    {
                        Reply?.Invoke(new object[] { $"数据(pid:{id})获取失败,请稍后再试" });
                    }
                    return;
                }
                ArrayList msg = new();
                if (detail.IsUgoira)
                {
                    var ugoira = await detail.GetUgoira();

                    if (ugoira == null)
                    {
                        if (!slient)
                        {
                            Reply?.Invoke(new object[] { $"动图数据(pid:{id})获取失败" });
                        }
                    }
                    else
                    {
                        if (!slient)
                        {
                            Reply?.Invoke(new object[] { $"动图数据(pid:{id})获取成功,正在进行压缩..." });
                        }
                        var img = await ugoira.LimitGifScale(500, 500);

                        var file = await img.SaveGifToTempFile();

                        msg.Add(CQCode.CQImage(file));
                    }
                }
                else
                {
                    foreach (var img in detail.Images)
                    {
                        var cache = await DownloadManager.GetCache(img.Medium);

                        if (string.IsNullOrEmpty(cache))
                        {
                            var url = ImageUrls.ToPixivCat(img.Medium);
                            cache = await DownloadManager.GetCache(url);

                            if (string.IsNullOrEmpty(cache))
                            {
                                cache = await DownloadManager.Download(url);

                                if (string.IsNullOrEmpty(cache))
                                {
                                    cache = await DownloadManager.Download(img.Medium, detail.Url);

                                    if (string.IsNullOrEmpty(cache))
                                    {
                                        msg.Add("[图像缓存失败]");
                                        continue;
                                    }
                                }
                            }
                        }
                        ImageUtils.LimitImageScale(cache, 1500, 1500);
                        msg.Add(CQCode.CQImage(cache));
                    }
                }
                msg.Add(detail.ToString());
                SendMessage?.Invoke(msg.ToArray());
            }
            catch (Exception ex)
            {
                ConsoleLog.Debug("QQ Command - Pixiv", ex.GetFormatString(true));
                if (!slient)
                {
                    Reply?.Invoke(new object[] { $"处理作品(pid:{id})时发生异常错误,任务已终止" });
                }
            }
        }
예제 #24
0
 public CQCode GetRandom()
 {
     return(CQCode.CQImage(Urls[random.Next(Urls.Length)], useCache: false));
 }
예제 #25
0
        private List <CQCode> GetTweetContent(Tweet tweet)
        {
            var temp = new List <CQCode> {
                CQCode.CQText(tweet.Content)
            };
            var img = new List <CQCode>();

            if (tweet.Media != null)
            {
                foreach (var item in tweet.Media)
                {
                    try
                    {
                        var data = HttpNet.Get(item["media_url_https"].ToString(), proxy: _config.Proxy);
                        img.Add(CQCode.CQImage("base64://" + Convert.ToBase64String(data), useCache: true));
                    }
                    catch (Exception e)
                    {
                        img.Add(CQCode.CQText($"Error: {e.Message}"));
                    }

                    switch (item["type"].ToString())
                    {
                    case "photo":
                    {
                        break;
                    }

                    case "video":
                    {
                        var mp4 = item["video_info"]["variants"]
                                  .FirstOrDefault(video => video["content_type"].ToString() == "video/mp4");

                        if (mp4 != null)
                        {
                            img.Add(CQCode.CQText(mp4["url"].ToString()));
                            var data     = HttpNet.Get(mp4["url"].ToString(), proxy: _config.Proxy);
                            var tempPath = AppDomain.CurrentDomain.BaseDirectory + "cache\\" + HashHelp.MD5Encrypt(data);
                            File.WriteAllBytes(tempPath, data);
                            img.Add(CQCode.CQVideo(tempPath, useCache: true));
                        }
                        else
                        {
                            img.Add(CQCode.CQText(item["video_info"]["variants"][0]["url"].ToString()));
                        }
                        break;
                    }

                    case "animated_gif":
                    {
                        var mp4 = item["video_info"]["variants"]
                                  .FirstOrDefault(video => video["content_type"].ToString() == "video/mp4");
                        if (mp4 != null)
                        {
                            img.Add(CQCode.CQText(mp4["url"].ToString()));
                            var data     = HttpNet.Get(mp4["url"].ToString(), proxy: _config.Proxy);
                            var tempPath = AppDomain.CurrentDomain.BaseDirectory + "cache\\" + HashHelp.MD5Encrypt(data);
                            File.WriteAllBytes(tempPath, data);
                            img.Add(CQCode.CQVideo(tempPath, useCache: true));
                        }
                        else
                        {
                            img.Add(CQCode.CQText(item["video_info"]["variants"][0]["url"].ToString()));
                        }
                        break;
                    }
                    }
                }
            }

            if (tweet.IsOnlyRetweet)
            {
                if (tweet.Retweet == null)
                {
                    return(new List <CQCode> {
                        CQCode.CQText("error")
                    });
                }
                else
                {
                    var a = new List <CQCode> {
                        CQCode.CQText(tweet.Retweet.UserName + ":\n")
                    };
                    a.AddRange(GetTweetContent(tweet.Retweet));
                    return(a);
                }
            }
            else
            {
                var time = CQCode.CQText("\n发送时间:" + tweet.CreatTime.ToString("yyyy-MM-dd HH:mm"));
                if (tweet.Retweet == null)
                {
                    temp.AddRange(img);
                    temp.Add(time);
                    return(temp);
                }
                else
                {
                    temp.AddRange(img);
                    temp.Add(time);
                    temp.Add(CQCode.CQText("\n" + tweet.Retweet.UserName + ":\n"));
                    temp.AddRange(GetTweetContent(tweet.Retweet));
                    return(temp);
                }
            }
        }
예제 #26
0
        public static async void Normal(SoraMessage e, string line1, string line2)
        {
            await e.Reply(CQCode.CQImage($"https://api.akiraxie.me/5000choyen?upper={Utils.UrlEncode(line1)}&lower={Utils.UrlEncode(line2)}"));

            await e.RemoveCoins(1);
        }
예제 #27
0
 public static async void Login(SoraMessage e)
 {
     await Task.Run(() => Library.Bilibili.Bilibili.QRCodeLoginRequest(
                        async(bitmap) =>
     {
         if (e.IsGroupMessage)
         {
             await e.ReplyToOriginal("登录任务已建立,请前往私聊等待登录二维码的发送");
         }
         else
         {
             await e.ReplyToOriginal("登录任务已建立,请等待登录二维码的发送");
         }
         var qr   = new MemoryImage(bitmap);
         var path = qr.ToBase64File();
         await e.SendPrivateMessage(CQCode.CQImage(path), "\n请使用Bilibili客户端扫码登录");
     },
                        async() => await e.SendPrivateMessage("检测到扫描事件,请在客户端中确认登录"),
                        async(cookie) =>
     {
         if (int.TryParse(cookie.Split(";").Where(x => x.StartsWith("DedeUserID=")).First()[11..], out var id))
         {
             await e.SendPrivateMessage("登录成功\n数据储存中……");
             var data = await Database.FindAsync <UserData>(x => x.QQ == e.Sender.Id || x.Bilibili == id);
             if (data != null)
             {
                 data.QQ             = e.Sender.Id;
                 data.Bilibili       = id;
                 data.BilibiliCookie = cookie;
                 await Database.UpdateAsync(data).ContinueWith(async x =>
                 {
                     if (x.Result > 0)
                     {
                         await e.SendPrivateMessage("记录数据已更新");
                     }
                     else if (x.IsFaulted && x.Exception != null)
                     {
                         await e.SendPrivateMessage(new StringBuilder()
                                                    .AppendLine("记录数据因异常导致更新失败,错误信息:")
                                                    .Append(ConsoleLog.ErrorLogBuilder(x.Exception))
                                                    .ToString());
                     }
                     else
                     {
                         await e.SendPrivateMessage("记录数据因未知原因导致更新失败,请稍后重试");
                     }
                 });
             }
             else
             {
                 data = new()
                 {
                     QQ             = e.Sender.Id,
                     Bilibili       = id,
                     BilibiliCookie = cookie
                 };
                 await Database.InsertAsync(data).ContinueWith(async x =>
                 {
                     if (x.Result > 0)
                     {
                         await e.SendPrivateMessage("记录数据已添加");
                     }
                     else if (x.IsFaulted && x.Exception != null)
                     {
                         await e.SendPrivateMessage(new StringBuilder()
                                                    .AppendLine("记录数据因异常导致更新失败,错误信息:")
                                                    .Append(ConsoleLog.ErrorLogBuilder(x.Exception))
                                                    .ToString());
                     }
                     else
                     {
                         await e.SendPrivateMessage("记录数据因未知原因导致更新失败,请稍后重试");
                     }
                 });
             }
         }
예제 #28
0
        private static Task GetDynamic(SoraApi soraApi, long biliUser, List <long> groupId, SubscriptionDBHelper dbHelper)
        {
            string        textMessage;
            Dynamic       biliDynamic;
            List <string> imgList = new List <string>();

            //获取动态文本
            try
            {
                JObject cardData = DynamicAPIs.GetBiliDynamicJson((ulong)biliUser, out CardType cardType);
                switch (cardType)
                {
                //检查动态类型
                case CardType.PlainText:
                    PlainTextCard plainTextCard = new PlainTextCard(cardData);
                    textMessage = plainTextCard.ToString();
                    biliDynamic = plainTextCard;
                    break;

                case CardType.TextAndPic:
                    TextAndPicCard textAndPicCard = new TextAndPicCard(cardData);
                    imgList.AddRange(textAndPicCard.ImgList);
                    textMessage = textAndPicCard.ToString();
                    biliDynamic = textAndPicCard;
                    break;

                default:
                    ConsoleLog.Warning("动态获取", $"ID:{biliUser}的动态获取成功,动态类型未知");
                    return(Task.CompletedTask);
                }
            }
            catch (Exception e)
            {
                ConsoleLog.Error("获取动态更新时发生错误", ConsoleLog.ErrorLogBuilder(e));
                return(Task.CompletedTask);
            }
            //获取用户信息
            BiliUserInfo sender = biliDynamic.GetUserInfo();

            ConsoleLog.Debug("动态获取", $"{sender.UserName}的动态获取成功");
            //检查是否是最新的

            List <long> targetGroups = new List <long>();

            foreach (long group in groupId)
            {
                //检查是否已经发送过消息
                if (!dbHelper.IsLatest(group, sender.Uid, biliDynamic.UpdateTime))
                {
                    targetGroups.Add(group);
                }
            }
            //没有群需要发送消息
            if (targetGroups.Count == 0)
            {
                ConsoleLog.Debug("动态获取", $"{sender.UserName}的动态已是最新");
                return(Task.CompletedTask);
            }
            //构建消息
            List <CQCode> msgList = new List <CQCode>();
            StringBuilder sb      = new StringBuilder();

            sb.Append("获取到了来自 ");
            sb.Append(sender.UserName);
            sb.Append(" 的动态:\r\n");
            sb.Append(textMessage);
            msgList.Add(CQCode.CQText(sb.ToString()));
            //添加图片
            imgList.ForEach(imgUrl => msgList.Add(CQCode.CQImage(imgUrl)));
            sb.Clear();
            sb.Append("\r\n更新时间:");
            sb.Append(biliDynamic.UpdateTime);
            msgList.Add(CQCode.CQText(sb.ToString()));
            //向未发生消息的群发送消息
            foreach (long targetGroup in targetGroups)
            {
                ConsoleLog.Info("动态获取", $"获取到{sender.UserName}的最新动态,向群{targetGroup}发送动态信息");
                soraApi.SendGroupMessage(targetGroup, msgList);
                if (!dbHelper.Update(targetGroup, sender.Uid, biliDynamic.UpdateTime))
                {
                    ConsoleLog.Error("数据库", "更新动态记录时发生了数据库错误");
                }
            }
            return(Task.CompletedTask);
        }