예제 #1
0
        /// <summary>
        /// 发送私聊消息
        /// </summary>
        /// <param name="userId">发送目标用户id</param>
        /// <param name="message">消息</param>
        /// <returns>
        /// <para><see cref="APIStatusType"/> API执行状态</para>
        /// <para><see langword="messageId"/> 消息ID</para>
        /// </returns>
        public async ValueTask <(APIStatusType apiStatus, int messageId)> SendPrivateMessage(long userId, params object[] message)
        {
            if (userId < 10000)
            {
                throw new ArgumentOutOfRangeException($"{nameof(userId)} too small");
            }
            if (message.Length == 0)
            {
                throw new NullReferenceException(nameof(message));
            }
            //消息段列表
            List <CQCode> msgList = new List <CQCode>();

            foreach (object msgObj in message)
            {
                if (msgObj is CQCode cqCode)
                {
                    msgList.Add(cqCode);
                }
                else if (msgObj is IEnumerable <CQCode> cqCodes)
                {
                    msgList.AddRange(cqCodes);
                }
                else
                {
                    msgList.Add(CQCode.CQText(msgObj.ToString()));
                }
            }
            return(((APIStatusType apiStatus, int messageId)) await ApiInterface.SendPrivateMessage(this.ConnectionGuid, userId, msgList));
        }
예제 #2
0
        public void OpenTwitterMonitor()
        {
            var function = new Action <TweeterMonitor, Tweet>(async delegate(TweeterMonitor sender, Tweet tweet)
            {
                var content = GetTweetContent(tweet);
                content.Insert(0, CQCode.CQText($"您监控的{sender.Mark}有新的推文了\n"));
                var sendConfig = _config.Items.Single(c => c.Mark.ToString() == sender.Mark);
                if (sendConfig.Group != null)
                {
                    foreach (var item in sendConfig.Group)
                    {
                        await _soraApi.SendGroupMessage(item, content);
                    }
                }

                if (sendConfig.Private != null)
                {
                    foreach (var item in sendConfig.Private)
                    {
                        await _soraApi.SendPrivateMessage(item, content);
                    }
                }
            });
            var     client  = new WebClient();
            Twitter twitter = new Twitter(ref client);

            foreach (var tw in _config.Items.Select(item => new TweeterMonitor(item.Mark.ToString(), twitter)
            {
                TimeInterval = 60
            }))
            {
                tw.NewTweetEvent += function;
                tw.Start();
            }
        }
예제 #3
0
        /// <summary>
        /// 预处理消息队列
        /// </summary>
        /// <param name="content">消息数据</param>
        internal static List <CQCode> ToCQCodeList(this object[] content)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            List <CQCode> msgList = new();

            foreach (var msgObj in content)
            {
                switch (msgObj)
                {
                case CQCode cqCode:
                    msgList.Add(cqCode);
                    break;

                case IEnumerable <CQCode> cqCodes:
                    msgList.AddRange(cqCodes);
                    break;

                default:
                    msgList.Add(CQCode.CQText(msgObj.ToString()));
                    break;
                }
            }

            return(msgList);
        }
예제 #4
0
 public object GetCosHot()
 {
     if (BiliBili.GetCosHot(out string[] urls))
     {
         return(urls.Select(url => CQCode.CQImage(url)));
     }
     else
     {
         return(CQCode.CQText("获取失败"));
     }
 }
예제 #5
0
        private async ValueTask CallBack(TweeterMonitor monitor, Tweet tweet)
        {
            if (_api == null)
            {
                return;
            }
            var content = new List <CQCode>();

            await GetTweetContent(content, tweet);

            content.Insert(0, CQCode.CQText($"您订阅的{monitor.Name}有新推文了\n"));
            var video = content.Where(c => c.Type == CQCodeType.Video).ToArray();

            content = content.Where(c => c.Type != CQCodeType.Video).ToList();
            var sendConfig = _globalService.TwitterSetting.Monitor[monitor.Name];

            if (sendConfig.Group != null)
            {
                foreach (var item in sendConfig.Group)
                {
                    await Task.Delay(1000);

                    if (content.Any())
                    {
                        await _api.SendGroupMsg(item, content);
                    }
                    await Task.Delay(1000);

                    if (video.Any())
                    {
                        await _api.SendGroupMsg(item, video);
                    }
                }
            }

            if (sendConfig.Private != null)
            {
                foreach (var item in sendConfig.Private)
                {
                    await Task.Delay(1000);

                    if (content.Any())
                    {
                        await _api.SendPrivateMsg(item, null, content);
                    }
                    await Task.Delay(1000);

                    if (video.Any())
                    {
                        await _api.SendPrivateMsg(item, null, video);
                    }
                }
            }
        }
예제 #6
0
        public async Task <CQCode> RefreshInvokeConfig()
        {
            var temp =
                JsonSerializer.Deserialize <InvokeConfig>(await File.ReadAllTextAsync("InvokeConfig.json"), _options);

            if (temp == null)
            {
                return(null);
            }
            _invokeConfig.GroupConfigs     = temp.GroupConfigs;
            _invokeConfig.PrivateConfigs   = temp.PrivateConfigs;
            _invokeConfig.BlackLists       = temp.BlackLists;
            _invokeConfig.UniversalConfigs = temp.UniversalConfigs;
            HandleInvokeParams(_invokeConfig);
            return(CQCode.CQText("已经成功刷新了调用配置"));
        }
예제 #7
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));
     }
 }
예제 #8
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());
            }
        }
예제 #9
0
파일: Commands.cs 프로젝트: nidbCN/Sora
        public static async ValueTask Echo(GroupMessageEventArgs eventArgs)
        {
            //处理开头字符串
            if (eventArgs.Message.MessageList[0].Function == CQFunction.Text)
            {
                if (eventArgs.Message.MessageList[0].CQData is Text str && str.Content.StartsWith("echo "))
                {
                    if (str.Content.Equals("echo "))
                    {
                        eventArgs.Message.MessageList.RemoveAt(0);
                    }
                    else
                    {
                        eventArgs.Message.MessageList[0] = CQCode.CQText(str.Content.Substring(5));
                    }
                }
            }

            //复读
            if (eventArgs.Message.MessageList.Count != 0)
            {
                await eventArgs.Reply(eventArgs.Message.MessageList);
            }
        }
예제 #10
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);
        }
예제 #11
0
        /// <summary>
        /// 加入除机器人外的所有成员
        /// 没有人数限制
        /// </summary>
        private async void JoinAll()
        {
            //检查公会是否存在
            if (DBHelper.GuildExists() != 1)
            {
                await SourceGroup.SendGroupMessage("该群未创建公会");

                return;
            }

            //获取所有成员的信息
            var(apiStatus, groupMemberList) = await SourceGroup.GetGroupMemberList();

            if (apiStatus != APIStatusType.OK)
            {
                Log.Error("API error", $"api ret code {(int) apiStatus}");
                await SourceGroup.SendGroupMessage(CQCode.CQAt(Sender), "\r\nAPI调用错误请重试");

                return;
            }

            //移除机器人的成员信息
            groupMemberList.RemoveAt(groupMemberList.FindIndex(member => member.UserId == MessageEventArgs.LoginUid));
            //添加成员到公会
            Dictionary <long, int> databaseRet = new Dictionary <long, int>();

            foreach (GroupMemberInfo member in groupMemberList)
            {
                //获取群成员名
                string memberName = groupMemberList.Any(memberInfo => memberInfo.UserId == member.UserId)
                    ? groupMemberList.Where(memberInfo => memberInfo.UserId == member.UserId)
                                    .Select(memberInfo =>
                                            string.IsNullOrEmpty(memberInfo.Card)
                                                     ? memberInfo.Nick
                                                     : memberInfo.Card)
                                    .First()
                    : "N/A";
                //添加成员
                databaseRet.Add(member.UserId,
                                DBHelper.JoinGuild(member.UserId, SourceGroup, memberName));
            }

            //构建格式化信息
            List <CQCode> responseMsg = new List <CQCode>();

            if (databaseRet.Any(ret => ret.Value == 0)) //成员成功加入
            {
                responseMsg.Add(CQCode.CQText("以下成员已加入:"));
                foreach (long member in databaseRet.Where(member => member.Value == 0)
                         .Select(member => member.Key)
                         .ToList())
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                    responseMsg.Add(CQCode.CQAt(member));
                }
            }

            if (databaseRet.Any(ret => ret.Value == 1)) //成员已存在
            {
                if (responseMsg.Count != 0)
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                }
                responseMsg.Add(CQCode.CQText("以下成员已在公会中,仅更新信息:"));
                foreach (long member in databaseRet.Where(member => member.Value == 1)
                         .Select(member => member.Key)
                         .ToList())
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                    responseMsg.Add(CQCode.CQAt(member));
                }
            }

            if (databaseRet.Any(ret => ret.Value == -1)) //数据库错误
            {
                if (responseMsg.Count != 0)
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                }
                responseMsg.Add(CQCode.CQText("以下成员在加入时发生错误:"));
                foreach (long member in databaseRet.Where(member => member.Value == -1)
                         .Select(member => member.Key)
                         .ToList())
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                    responseMsg.Add(CQCode.CQAt(member));
                }
            }

            //发送信息
            await SourceGroup.SendGroupMessage(responseMsg);
        }
예제 #12
0
        /// <summary>
        /// 退会
        /// </summary>
        private async void QuitGuild()
        {
            //检查公会是否存在
            if (DBHelper.GuildExists() != 1)
            {
                await SourceGroup.SendGroupMessage("该群未创建公会");

                return;
            }

            //获取成员参数
            List <long> quitList = new List <long>();

            switch (BotUtils.CheckForLength(CommandArgs, 1))
            {
            case LenType.Illegal:
                quitList.Add(Sender);
                break;

            case LenType.Legitimate:     //只有单一成员时需判断uid参数
                quitList.AddRange(MessageEventArgs.Message.GetAllAtList());
                if (quitList.Count == 0)
                {
                    if (long.TryParse(CommandArgs[1], out long uid))
                    {
                        quitList.Add(uid);
                    }
                    else
                    {
                        await SourceGroup.SendGroupMessage("没有At任何成员");

                        return;
                    }
                }

                break;

            case LenType.Extra:
                quitList.AddRange(MessageEventArgs.Message.GetAllAtList());
                if (quitList.Count == 0)
                {
                    await SourceGroup.SendGroupMessage("没有At任何成员");

                    return;
                }

                break;
            }

            //检查列表中是否有机器人
            if (quitList.Any(member => member == MessageEventArgs.LoginUid))
            {
                quitList.Remove(MessageEventArgs.LoginUid);
                await SourceGroup.SendGroupMessage("不要在成员中At机器人啊kora");

                if (quitList.Count == 0)
                {
                    return;
                }
            }

            Log.Debug("Guild Mgr", $"Get quit list count={quitList.Count}");
            Dictionary <long, int> databaseRet = new Dictionary <long, int>();

            //删除退会成员
            foreach (long member in quitList)
            {
                databaseRet.Add(member,
                                DBHelper.QuitGuild(member, SourceGroup));
            }

            //构建格式化信息
            List <CQCode> responseMsg = new List <CQCode>();

            if (databaseRet.Any(ret => ret.Value == 0))
            {
                responseMsg.Add(CQCode.CQText("以下成员已退出:"));
                foreach (long member in databaseRet.Where(member => member.Value == 0)
                         .Select(member => member.Key)
                         .ToList())
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                    responseMsg.Add(CQCode.CQAt(member));
                }
            }

            if (databaseRet.Any(ret => ret.Value == 1))
            {
                if (responseMsg.Count != 0)
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                }
                responseMsg.Add(CQCode.CQText("以下成员并不在公会中:"));
                foreach (long member in databaseRet.Where(member => member.Value == 1)
                         .Select(member => member.Key)
                         .ToList())
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                    responseMsg.Add(CQCode.CQAt(member));
                }
            }

            if (databaseRet.Any(ret => ret.Value == -1))
            {
                if (responseMsg.Count != 0)
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                }
                responseMsg.Add(CQCode.CQText("以下成员在退出时发生错误:"));
                foreach (long member in databaseRet.Where(member => member.Value == -1)
                         .Select(member => member.Key)
                         .ToList())
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                    responseMsg.Add(CQCode.CQAt(member));
                }
            }

            //发送信息
            await SourceGroup.SendGroupMessage(responseMsg);
        }
예제 #13
0
        private async ValueTask GetTweetContent(List <CQCode> codes, Tweet tweet)
        {
            //var temp = new List<CQCode> { CQCode.CQText(tweet.Content) };
            codes.Add(CQCode.CQText(tweet.Content));
            var img = new List <CQCode>();

            if (tweet.Media != null)
            {
                foreach (var item in tweet.Media)
                {
                    try
                    {
                        img.Add(await CQHelper.Image(item["media_url_https"].ToString(), CQFileType.Base64, _httpClientFactory));
                    }
                    catch (Exception e)
                    {
                        img.Add(CQCode.CQText($"Error: {e.Message}"));
                    }

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

                    case "video":
                    case "animated_gif":
                        var mp4 = item["video_info"]["variants"]
                                  .FirstOrDefault(video => video["content_type"].ToString() == "video/mp4");
                        if (mp4 != null)
                        {
                            var videoUrl = mp4["url"].ToString();
                            img.Add(CQCode.CQText(videoUrl));
                            img.Add(await CQHelper.Video(videoUrl, CQFileType.File, null, _httpClientFactory));
                        }
                        else
                        {
                            img.Add(CQCode.CQText(item["video_info"]["variants"][0]["url"].ToString()));
                        }

                        break;
                    }
                }
            }

            if (img.Count == 0 && tweet.Retweet == null)
            {
                if (tweet.Entities.TryGetValue("urls", out var urls))
                {
                    var temp = await TryGetUrlImage(((JArray)urls)[0]["expanded_url"].ToString(), tweet.UserId);

                    if (temp != null)
                    {
                        codes.AddRange(temp);
                    }
                }
            }

            if (tweet.IsOnlyRetweet)
            {
                if (tweet.Retweet == null)
                {
                    //return new List<CQCode> { CQCode.CQText("error") };
                    codes.Add(CQCode.CQText("error"));
                }
                else
                {
                    //var a = new List<CQCode> { CQCode.CQText(tweet.Retweet.UserName + ":\n") };
                    //a.AddRange(await GetTweetContent(tweet.Retweet));
                    //return a;
                    codes.Add(CQCode.CQText(tweet.Retweet.UserName + ":\n"));
                    await GetTweetContent(codes, tweet.Retweet);
                }
            }
            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;
                    codes.AddRange(img);
                    codes.Add(time);
                }
                else
                {
                    //temp.AddRange(img);
                    //temp.Add(time);
                    //temp.Add(CQCode.CQText("\n" + tweet.Retweet.UserName + ":\n"));
                    //temp.AddRange(await GetTweetContent(tweet.Retweet));
                    //return temp;
                    codes.AddRange(img);
                    codes.Add(time);
                    codes.Add(CQCode.CQText("\n" + tweet.Retweet.UserName + ":\n"));
                    await GetTweetContent(codes, tweet.Retweet);
                }
            }
        }
예제 #14
0
        /// <summary>
        /// 加入公会
        /// </summary>
        private async void JoinGuild()
        {
            //检查公会是否存在
            if (DBHelper.GuildExists() != 1)
            {
                await SourceGroup.SendGroupMessage("该群未创建公会");

                return;
            }

            //处理需要加入的成员列表
            List <long> joinList = new List <long>();

            switch (BotUtils.CheckForLength(CommandArgs, 1))
            {
            case LenType.Illegal:
                joinList.Add(Sender);
                break;

            case LenType.Extra:
            case LenType.Legitimate:
                joinList.AddRange(MessageEventArgs.Message.GetAllAtList());
                if (joinList.Count == 0)
                {
                    await SourceGroup.SendGroupMessage("没有At任何成员");

                    return;
                }

                break;
            }

            //检查列表中是否有机器人
            if (joinList.Any(member => member == MessageEventArgs.LoginUid))
            {
                joinList.Remove(MessageEventArgs.LoginUid);
                await SourceGroup.SendGroupMessage("不要在成员中At机器人啊kora");

                if (joinList.Count == 0)
                {
                    return;
                }
            }

            Log.Debug("Guild Mgr", $"Get join list count={joinList.Count}");
            //从API获取成员信息
            Log.Debug("Guild Mgr", "Get group member infos");
            var(apiStatus, groupMemberList) = await SourceGroup.GetGroupMemberList();

            if (apiStatus != APIStatusType.OK)
            {
                Log.Error("API error", $"api ret code {(int) apiStatus}");
                await SourceGroup.SendGroupMessage(CQCode.CQAt(Sender), "\r\nAPI调用错误请重试");

                return;
            }

            //加入待加入的成员
            Dictionary <long, int> databaseRet = new Dictionary <long, int>();

            foreach (long member in joinList)
            {
                //获取群成员名
                string memberName = groupMemberList.Any(memberInfo => memberInfo.UserId == member)
                    ? groupMemberList.Where(memberInfo => memberInfo.UserId == member)
                                    .Select(memberInfo =>
                                            string.IsNullOrEmpty(memberInfo.Card)
                                                     ? memberInfo.Nick
                                                     : memberInfo.Card)
                                    .First()
                    : "N/A";
                //添加成员
                databaseRet.Add(member,
                                DBHelper.JoinGuild(member, SourceGroup, memberName));
            }

            //构建格式化信息
            List <CQCode> responseMsg = new List <CQCode>();

            if (databaseRet.Any(ret => ret.Value == 0)) //成员成功加入
            {
                responseMsg.Add(CQCode.CQText("以下成员已加入:"));
                foreach (long member in databaseRet.Where(member => member.Value == 0)
                         .Select(member => member.Key)
                         .ToList())
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                    responseMsg.Add(CQCode.CQAt(member));
                }
            }

            if (databaseRet.Any(ret => ret.Value == 1)) //成员已存在
            {
                if (responseMsg.Count != 0)
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                }
                responseMsg.Add(CQCode.CQText("以下成员已在公会中,仅更新信息:"));
                foreach (long member in databaseRet.Where(member => member.Value == 1)
                         .Select(member => member.Key)
                         .ToList())
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                    responseMsg.Add(CQCode.CQAt(member));
                }
            }

            if (databaseRet.Any(ret => ret.Value == -1)) //数据库错误
            {
                if (responseMsg.Count != 0)
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                }
                responseMsg.Add(CQCode.CQText("以下成员在加入时发生错误:"));
                foreach (long member in databaseRet.Where(member => member.Value == -1)
                         .Select(member => member.Key)
                         .ToList())
                {
                    responseMsg.Add(CQCode.CQText("\r\n"));
                    responseMsg.Add(CQCode.CQAt(member));
                }
            }

            //发送信息
            await SourceGroup.SendGroupMessage(responseMsg);
        }
예제 #15
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);
            }
        }
예제 #16
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("数据库", "更新动态记录时发生了数据库错误");
                }
            }
        }
예제 #17
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);
                }
            }
        }
예제 #18
0
파일: Helper.cs 프로젝트: nidbCN/Sora
 public static void AddText(this List <CQCode> msgList, string text) =>
 msgList.Add(CQCode.CQText(text));
예제 #19
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);
        }