Пример #1
0
        /// <summary>
        /// This is the main entry point for your service instance.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            /***** Start here *****/
            try
            {
                Heartbeat.Start(_cdsInfo);

                /* Main IoTHub Receiver Here */
                _IoTHubMessageReceiver = new IoTHubMessageReceiver(_cdsInfo);
                await _IoTHubMessageReceiver.Start();

                ListenOnServiceBusTopic(_cdsInfo);
            }
            catch (Exception ex)
            {
                _consoleLog.Error("RunAsync Exception:{0}", ex.Message);
                _consoleLog.BlobLogError("RunAsync Exception:{0}", ex.Message);

                if (_IoTHubMessageReceiver != null)
                {
                    _IoTHubMessageReceiver.Stop().Wait();
                }

                //throw ex;
            }
        }
Пример #2
0
 public unsafe static bool LoadFromPointer(string[] source)
 {
     try {
         return(loader.LoadFromSourceFunctions(source));
     } catch (Exception ex) {
         // TODO: Implement error handling
         log.Error(ex.Message, ex);
         return(false);
     }
 }
Пример #3
0
        /// <summary>
        /// 修改会战进度(无视当前出刀进度和历史出刀)
        /// </summary>
        /// <returns>
        /// <para><see langword="true"/> 修改成功</para>
        /// <para><see langword="false"/> 修改失败</para>
        /// </returns>
        public bool ModifyProgress(int round, int bossOrder, long hp, long totalHP, int phase)
        {
            try
            {
                using SqlSugarClient dbClient = SugarUtils.CreateSqlSugarClient(DBPath);

                //更新数据
                return(dbClient.Updateable(new GuildInfo
                {
                    HP = hp,
                    TotalHP = totalHP,
                    Round = round,
                    Order = bossOrder,
                    BossPhase = phase,
                })
                       .Where(guild => guild.Gid == GuildEventArgs.SourceGroup.Id)
                       .UpdateColumns(info => new
                {
                    info.HP, info.TotalHP, info.Round, info.Order, info.BossPhase
                })
                       .ExecuteCommandHasChange());
            }
            catch (Exception e)
            {
                ConsoleLog.Error("Database error", ConsoleLog.ErrorLogBuilder(e));
                return(false);
            }
        }
Пример #4
0
 /// <summary>
 /// 获取今天的出刀列表
 /// </summary>
 /// <returns>
 /// <para>出刀表</para>
 /// <para><see langword="null"/> 数据库错误</para>
 /// </returns>
 public List <GuildBattle> GetTodayAttacks(long?uid = null)
 {
     try
     {
         using SqlSugarClient dbClient = SugarUtils.CreateSqlSugarClient(DBPath);
         if (uid == null)
         {
             //查询所有人的出刀表
             return(dbClient.Queryable <GuildBattle>()
                    .AS(BattleTableName)
                    .Where(i => i.Time >= BotUtils.GetUpdateStamp())
                    .OrderBy(i => i.Aid)
                    .ToList());
         }
         else
         {
             //查询单独成员的出刀表
             return(dbClient.Queryable <GuildBattle>()
                    .AS(BattleTableName)
                    .Where(i => i.Time >= BotUtils.GetUpdateStamp() && i.Uid == uid)
                    .OrderBy(i => i.Aid)
                    .ToList());
         }
     }
     catch (Exception e)
     {
         ConsoleLog.Error("Database error", ConsoleLog.ErrorLogBuilder(e));
         return(null);
     }
 }
Пример #5
0
 /// <summary>
 /// 向数据库插入一刀数据
 /// </summary>
 /// <param name="uid">出刀者UID</param>
 /// <param name="guildInfo">公会信息</param>
 /// <param name="dmg">伤害</param>
 /// <param name="attackType">出刀类型</param>
 /// <returns>
 /// <para>本次出刀刀号</para>
 /// <para><see langword="-1"/> 数据库错误</para>
 /// </returns>
 public int NewAttack(long uid, GuildInfo guildInfo, long dmg, AttackType attackType)
 {
     try
     {
         using SqlSugarClient dbClient = SugarUtils.CreateSqlSugarClient(DBPath);
         //插入一刀数据
         var insertData = new GuildBattle()
         {
             Uid    = uid,
             Time   = Utils.GetNowTimeStamp(),
             Order  = guildInfo.Order,
             Round  = guildInfo.Round,
             Damage = dmg,
             Attack = attackType
         };
         return(dbClient.Insertable(insertData)
                .AS(BattleTableName)
                .ExecuteReturnIdentity());
     }
     catch (Exception e)
     {
         ConsoleLog.Error("Database error", ConsoleLog.ErrorLogBuilder(e));
         return(-1);
     }
 }
Пример #6
0
 /// <summary>
 /// 结束会战
 /// </summary>
 /// <returns>
 /// <para><see langword="1"/> 成功结束统计</para>
 /// <para><see langword="0"/> 未开始会战</para>
 /// <para><see langword="-1"/> 数据库错误</para>
 /// </returns>
 public int EndBattle()
 {
     try
     {
         using SqlSugarClient dbClient = SugarUtils.CreateSqlSugarClient(DBPath);
         if (SugarUtils.TableExists <GuildBattle>(dbClient, BattleTableName))
         {
             ConsoleLog.Warning("会战管理数据库", "结束一期会战统计删除旧表");
             SugarUtils.DeletTable <GuildBattle>(dbClient, BattleTableName);
             return(dbClient.Updateable(new GuildInfo {
                 InBattle = false
             })
                    .Where(guild => guild.Gid == GuildEventArgs.SourceGroup.Id)
                    .UpdateColumns(i => new { i.InBattle })
                    .ExecuteCommandHasChange()
                 ? 1
                 : -1);
         }
         else
         {
             ConsoleLog.Info("会战管理数据库", "会战表为空,请确认是否已经开始会战统计");
             return(0);
         }
     }
     catch (Exception e)
     {
         ConsoleLog.Error("Database error", ConsoleLog.ErrorLogBuilder(e));
         return(-1);
     }
 }
Пример #7
0
        /// <summary>
        /// 从指定Url获取byte数据并转为string输出
        /// </summary>
        /// <param name="url">目标url</param>
        /// <returns>返回一个string</returns>
        public static string GetDataFromURL(string url)
        {
            string    pageString;
            WebClient webClient = new WebClient
            {
                Credentials = CredentialCache.DefaultCredentials
            };

            try
            {
                Byte[]       pageData = webClient.DownloadData(url);
                MemoryStream ms       = new MemoryStream(pageData);

                using (StreamReader sr = new StreamReader(ms, Encoding.GetEncoding("GB2312")))
                {
                    pageString = sr.ReadLine();
                }
            }
            catch (Exception e)
            {
                ConsoleLog.Error("网络线程错误", $"下载文件时发生错误\n{e}");
                throw e;
            }
            return(pageString);
        }
Пример #8
0
 /// <summary>
 /// 查询今日余刀
 /// 用于查刀和催刀
 /// </summary>
 /// <returns>余刀表</returns>
 public Dictionary <long, int> GetTodayAtkCount()
 {
     try
     {
         using SqlSugarClient dbClient = SugarUtils.CreateSqlSugarClient(DBPath);
         return(dbClient.Queryable <GuildBattle>()
                .AS(BattleTableName)
                .Where(attack => attack.Time > BotUtils.GetUpdateStamp() &&
                       attack.Attack != AttackType.Compensate &&
                       attack.Attack != AttackType.CompensateKill)
                .GroupBy(member => member.Uid)
                .Select(member => new
         {
             member.Uid,
             times = SqlFunc.AggregateCount(member.Uid)
         })
                .ToList()
                .ToDictionary(member => member.Uid,
                              member => member.times));
     }
     catch (Exception e)
     {
         ConsoleLog.Error("Database error", ConsoleLog.ErrorLogBuilder(e));
         return(null);
     }
 }
Пример #9
0
 /// <summary>
 /// 触发后查找数据库返回读取到的值
 /// </summary>
 /// <returns>状态值
 /// 包含当前好感度和调用数据的Dictionary
 /// "favor_rate":当前的好感度[int]
 /// "use_date":上次调用时间戳[long]
 /// </returns>
 public void SignIn()
 {
     try
     {
         using SqlSugarClient SQLiteClient = SugarUtils.CreateSqlSugarClient(DBPath);
         if (Convert.ToBoolean(
                 SQLiteClient.Queryable <SuiseiData>().Where(user => user.Uid == QQID && user.Gid == GroupId).Count()
                 ))              //查找是否有记录
         {
             //查询数据库数据
             UserData = SQLiteClient.Queryable <SuiseiData>()
                        .Where(userInfo => userInfo.Uid == QQID && userInfo.Gid == GroupId)
                        .First();
             IsExists         = true;
             CurrentFavorRate = UserData.FavorRate; //更新当前好感值
         }
         else //未找到签到记录
         {
             UserData = new SuiseiData   //创建用户初始化数据
             {
                 Uid       = QQID,       //用户QQ
                 Gid       = GroupId,    //用户所在群号
                 FavorRate = 0,          //好感度
                 ChatDate  = TriggerTime //签到时间
             };
             IsExists         = false;
             CurrentFavorRate = 0;
         }
     }
     catch (Exception e)
     {
         SuiseiGroupMessageEventArgs.FromGroup.SendGroupMessage($"数据库出现错误\n请向管理员反馈此错误\n{e}");
         ConsoleLog.Error("suisei签到", $"数据库出现错误\n{e}");
     }
 }
Пример #10
0
 /// <summary>
 /// 更新当前的好感度
 /// </summary>
 public void FavorRateUp()
 {
     try
     {
         //更新好感度数据
         this.CurrentFavorRate++;
         UserData.FavorRate = CurrentFavorRate;  //更新好感度
         using SqlSugarClient SQLiteClient = SugarUtils.CreateSqlSugarClient(DBPath);
         //判断用户记录是否已经存在
         if (IsExists)                        //已存在则更新数据
         {
             UserData.ChatDate = TriggerTime; //更新触发时间
             SQLiteClient.Updateable(UserData).ExecuteCommand();
         }
         else //不存在插入新行
         {
             SQLiteClient.Insertable(UserData).ExecuteCommand(); //向数据库写入新数据
         }
     }
     catch (Exception e)
     {
         SuiseiGroupMessageEventArgs.FromGroup.SendGroupMessage($"数据库出现错误\n请向管理员反馈此错误\n{e}");
         ConsoleLog.Error("suisei签到", $"数据库出现错误\n{e}");
     }
 }
Пример #11
0
        public void RetrieveCompetitionsBySeason(int seasonStartYear)
        {
            ConsoleLog.Start("Retrieving competitions");

            var competitions = this.footballDataRepository.RetriveCompetitionsBySeason(seasonStartYear);

            ConsoleLog.Information($"Competitions retrieved", $"{competitions.Count()}");

            if (competitions != null && competitions.Any())
            {
                foreach (var competition in competitions)
                {
                    ConsoleLog.Start($"Retrieving fxtures for {competition.Caption}");

                    var fixtureHeader = this.footballDataRepository.RetrieveFixturesForCompetition(competition.Id);

                    if (fixtureHeader.Fixtures != null && fixtureHeader.Fixtures.Any())
                    {
                        competition.Fixtures = fixtureHeader.Fixtures.Where(w => w.Status == "FINISHED" || string.IsNullOrEmpty(w.Status)).ToList();

                        ConsoleLog.Information($"Fixtures retrieved for {competition.Caption}", $"{competition.Fixtures.Count()}");

                        if (competition.Fixtures != null && competition.Fixtures.Any())
                        {
                            this.MapRecords(competition, seasonStartYear);
                        }
                    }
                    else
                    {
                        ConsoleLog.Error($"No fixtures found", $"{competition.Caption} - {seasonStartYear}");
                    }
                }
            }
        }
Пример #12
0
        public async ValueTask PrivateMessageParse(object sender, PrivateMessageEventArgs eventArgs)
        {
            //配置文件实例
            config = new(eventArgs.LoginUid);
            //读取配置文件
            if (!config.LoadUserConfig(out UserConfig userConfig))
            {
                await eventArgs.Sender.SendPrivateMessage("读取配置文件(User)时发生错误\r\n请检查配置文件然后重启");

                ConsoleLog.Error("Qiushui机器人管理", "无法读取用户配置文件");
                return;
            }

            //人工智障
            //var service = new DealInstruction(ConsoleLog, userConfig);
            var all    = _keyWordServices.Query(t => t.ID > 0);
            var result = _keyWordServices.Query(t => t.Keys.Contains(eventArgs.Message.RawText)) ?? new List <LianKeyWords>();

            if (result.Count > 0 && result != null)
            {
                var strSb = new StringBuilder();
                strSb.Append($"已找到所有符合项:\r\n");
                foreach (var item in result)
                {
                    strSb.Append($"{item.Words}\r\n");
                }
                await eventArgs.Reply(strSb.ToString());
            }
            else
            {
                await eventArgs.Reply("没有找到任何符合要求记录");
            }
            //执行人工智障
            //await eventArgs.Reply("数据密码");
        }
 public void GetChat() //消息接收并判断是否响应
 {
     try
     {
         //获取第二个字符开始到空格为止的PCR命令
         PCRGuildCommand = PCRGuildEventArgs.Message.RawText.Substring(1).Split(' ')[0];
         //公会管理指令
         if (CommandType > 0 && (int)CommandType < 100)
         {
             GuildManager guildManager = new GuildManager(PCRGuildEventArgs, CommandType);
             guildManager.GuildManagerResponse();
         }
         //出刀管理指令
         else if ((int)CommandType > 100 && (int)CommandType < 200)
         {
             GuildBattleManager battleManager = new GuildBattleManager(PCRGuildEventArgs, CommandType);
             battleManager.GuildBattleResponse();
         }
     }
     catch (Exception e)
     {
         //命令无法被正确解析
         ConsoleLog.Error("PCR公会管理", $"指令解析发生错误\n{e}");
     }
 }
Пример #14
0
        /// <summary>
        /// 收到信息的函数
        /// 并匹配相应指令
        /// </summary>
        public async void GetChat(RegexCommand cmdType)
        {
            if (PCREventArgs == null || Sender == null)
            {
                return;
            }
            switch (cmdType)
            {
            //查询公会排名
            case RegexCommand.GetGuildRank:
                //以群名为查询名
                if (PCREventArgs.Message.RawText.Length <= 6)
                {
                    var groupInfo = await QQGroup.GetGroupInfo();

                    if (groupInfo.apiStatus != APIStatusType.OK)
                    {
                        await QQGroup.SendGroupMessage("调用onebot API时发生错误");

                        ConsoleLog.Error("api error", $"调用onebot API时发生错误 Status={groupInfo.apiStatus}");
                        return;
                    }
                    await BiliWikiRank(groupInfo.groupInfo.GroupName);
                }
                else     //手动指定
                {
                    await BiliWikiRank(PCREventArgs.Message.RawText.Substring(6));
                }
                break;
            }
        }
Пример #15
0
 /// <summary>
 /// 装逼大图
 /// </summary>
 /// <param name="imageFile">图片名/绝对路径/URL/base64</param>
 /// <param name="source">来源名称</param>
 /// <param name="iconUrl">来源图标 URL</param>
 /// <param name="minWidth">最小 Width</param>
 /// <param name="minHeight">最小 Height</param>
 /// <param name="maxWidth">最大 Width</param>
 /// <param name="maxHeight">最大 Height</param>
 public static CQCode CQCardImage(string imageFile,
                                  string source  = null,
                                  string iconUrl = null,
                                  long minWidth  = 400,
                                  long minHeight = 400,
                                  long maxWidth  = 400,
                                  long maxHeight = 400)
 {
     if (string.IsNullOrEmpty(imageFile))
     {
         throw new NullReferenceException(nameof(imageFile));
     }
     (string dataStr, bool isDataStr) = ParseDataStr(imageFile);
     if (!isDataStr)
     {
         ConsoleLog.Error("CQCode|CQCardImage", $"非法参数({imageFile}),已忽略CQ码");
         return(CQIlleage());
     }
     return(new CQCode(CQFunction.CardImage,
                       new CardImage
     {
         ImageFile = dataStr,
         Source = source,
         Icon = iconUrl,
         MinWidth = minWidth,
         MinHeight = minHeight,
         MaxWidth = maxWidth,
         MaxHeight = maxHeight
     }));
 }
Пример #16
0
 /// <summary>
 /// 设置成员SL
 /// 同时自动下树
 /// 如果只清空则不会修改状态
 /// </summary>
 /// <param name="uid">成员UID</param>
 /// <param name="cleanSL">是否清空SL</param>
 /// <returns>
 /// <para><see langword="true"/> 写入成功</para>
 /// <para><see langword="false"/> 数据库错误</para>
 /// </returns>
 public bool SetMemberSL(long uid, bool cleanSL = false)
 {
     try
     {
         using SqlSugarClient dbClient = SugarUtils.CreateSqlSugarClient(DBPath);
         if (cleanSL) //清空SL
         {
             return(dbClient
                    .Updateable(new MemberInfo
             {
                 SL = 0
             })
                    .UpdateColumns(i => new { i.SL })
                    .Where(i => i.Gid == GuildEventArgs.SourceGroup.Id && i.Uid == uid)
                    .ExecuteCommandHasChange());
         }
         else //设置新的SL
         {
             return(dbClient
                    .Updateable(new MemberInfo
             {
                 Flag = FlagType.IDLE, SL = Utils.GetNowTimeStamp(), Time = Utils.GetNowTimeStamp(), Info = null
             })
                    .UpdateColumns(i => new { i.Flag, i.SL, i.Time, i.Info })
                    .Where(i => i.Gid == GuildEventArgs.SourceGroup.Id && i.Uid == uid)
                    .ExecuteCommandHasChange());
         }
     }
     catch (Exception e)
     {
         ConsoleLog.Error("Database error", ConsoleLog.ErrorLogBuilder(e));
         return(false);
     }
 }
Пример #17
0
        /// <summary>
        /// 进入下一个周目
        /// </summary>
        /// <param name="guildInfo">公会信息</param>
        /// <returns>
        /// <para><see langword="true"/> 写入成功</para>
        /// <para><see langword="false"/> 数据库错误</para>
        /// </returns>
        public bool GotoNextRound(GuildInfo guildInfo)
        {
            try
            {
                using SqlSugarClient dbClient = SugarUtils.CreateSqlSugarClient(DBPath);

                int nextPhase = GetNextRoundPhase(guildInfo, dbClient);
                //获取下一个周目boss的信息
                GuildBattleBoss nextBossData = dbClient.Queryable <GuildBattleBoss>()
                                               .Where(i => i.ServerId == guildInfo.ServerId &&
                                                      i.Phase == nextPhase &&
                                                      i.Order == 1)
                                               .First();
                GuildInfo updateBossData =
                    new GuildInfo()
                {
                    BossPhase = nextBossData.Phase,
                    Order     = 1,
                    Round     = guildInfo.Round + 1,
                    HP        = nextBossData.HP,
                    TotalHP   = nextBossData.HP
                };
                return(dbClient.Updateable(updateBossData)
                       .UpdateColumns(i => new { i.Order, i.HP, i.BossPhase, i.Round, i.TotalHP })
                       .Where(i => i.Gid == GuildEventArgs.SourceGroup.Id)
                       .ExecuteCommandHasChange());
            }
            catch (Exception e)
            {
                ConsoleLog.Error("Database error", ConsoleLog.ErrorLogBuilder(e));
                return(false);
            }
        }
Пример #18
0
 /// <summary>
 /// 加载服务器全局配置文件
 /// 读取成功后写入到私有属性中,第二次读取则不需要重新读取
 /// </summary>
 /// <param name="globalConfig">读取到的配置文件数据</param>
 /// <param name="reload">重新读取</param>
 public bool LoadGlobalConfig(out GlobalConfig globalConfig, bool reload = true)
 {
     if (!reload)
     {
         globalConfig = this.LoadedGlobalConfig;
         return(this.LoadedGlobalConfig != null);
     }
     ConsoleLog.Debug("ConfigIO", "读取全局配置");
     try
     {
         //反序列化配置文件
         Serializer serializer = new Serializer();
         using TextReader reader = File.OpenText(GlobalConfigPath);
         this.LoadedGlobalConfig = serializer.Deserialize <GlobalConfig>(reader);
         //参数合法性检查
         if ((int)LoadedGlobalConfig.LogLevel is < 0 or > 3 ||
             this.LoadedGlobalConfig.HeartBeatTimeOut == 0 ||
             this.LoadedGlobalConfig.ApiTimeOut == 0 ||
             this.LoadedGlobalConfig.Port is 0 or > 65535)
         {
             ConsoleLog.Error("读取全局配置", "参数值超出合法范围,重新生成配置文件");
             globalConfig = null;
             return(false);
         }
         globalConfig = this.LoadedGlobalConfig;
         return(true);
     }
     catch (Exception e)
     {
         ConsoleLog.Error("读取全局配置文件时发生错误", ConsoleLog.ErrorLogBuilder(e));
         globalConfig = null;
         return(false);
     }
 }
Пример #19
0
 public virtual async Task <IEnumerable <RssSchema> > Read()
 {
     return(await Task.Run(() =>
     {
         IEnumerable <RssSchema> rss = null;
         for (var i = 0; i < Source.Length; i++)
         {
             try
             {
                 var data = Utils.HttpGET(Source[i]);
                 if (!string.IsNullOrEmpty(data))
                 {
                     var parser = new RssParser();
                     rss = parser.Parse(data);
                     break;
                 }
             }
             catch (Exception ex)
             {
                 ConsoleLog.Error("Feed", ex.GetFormatString());
                 ConsoleLog.Error("Feed", "Target Url: ".CreateStringBuilder()
                                  .AppendLine(Source[i]).Append(ConsoleLog.ErrorLogBuilder(ex, true)).ToString());
             }
         }
         return rss;
     }));
 }
Пример #20
0
 /// <summary>
 /// 初始化全局配置文件并返回当前配置文件内容
 /// 初始化成功后写入到私有属性中,第二次读取则不需要重新读取
 /// </summary>
 public void GlobalConfigFileInit()
 {
     try
     {
         //当读取到文件时直接返回
         if (File.Exists(GlobalConfigPath) && LoadGlobalConfig(out _))
         {
             ConsoleLog.Debug("ConfigIO", "读取配置文件");
             return;
         }
         //没读取到文件时创建新的文件
         ConsoleLog.Error("ConfigIO", "未找到配置文件");
         ConsoleLog.Warning("ConfigIO", "创建新的配置文件");
         string initConfigText = Encoding.UTF8.GetString(InitRes.InitGlobalConfig);
         using (TextWriter writer = File.CreateText(GlobalConfigPath))
         {
             writer.Write(initConfigText);
             writer.Close();
         }
         //读取生成的配置文件
         if (!LoadGlobalConfig(out _))
         {
             throw new IOException("无法读取生成的配置文件");
         }
     }
     catch (Exception e)
     {
         ConsoleLog.Fatal("ConfigIO ERROR", ConsoleLog.ErrorLogBuilder(e));
         Thread.Sleep(5000);
         Environment.Exit(-1);
     }
 }
Пример #21
0
 /// <summary>
 /// 加载用户配置文件
 /// 读取成功后写入到私有属性中,第二次读取则不需要重新读取
 /// </summary>
 /// <param name="userConfig">读取到的配置文件数据</param>
 /// <param name="reload">重新读取</param>
 public bool LoadUserConfig(out UserConfig userConfig, bool reload = true)
 {
     if (!reload)
     {
         userConfig = this.LoadedUserConfig;
         return(this.LoadedUserConfig != null);
     }
     ConsoleLog.Debug("ConfigIO", "读取用户配置");
     try
     {
         //反序列化配置文件
         Serializer serializer = new Serializer();
         using TextReader reader = File.OpenText(UserConfigPath);
         this.LoadedUserConfig   = serializer.Deserialize <UserConfig>(reader);
         //参数合法性检查
         if (LoadedUserConfig.SubscriptionConfig.FlashTime <= 10 ||
             LoadedUserConfig.HsoConfig.SizeLimit < 1)
         {
             ConsoleLog.Error("读取用户配置", "参数值超出合法范围,重新生成配置文件");
             userConfig = null;
             return(false);
         }
         userConfig = this.LoadedUserConfig;
         return(true);
     }
     catch (Exception e)
     {
         ConsoleLog.Error("读取用户配置文件时发生错误", ConsoleLog.ErrorLogBuilder(e));
         userConfig = null;
         return(false);
     }
 }
Пример #22
0
 public static async void GetMojiraList(SoraMessage e, DateTime from, DateTime to)
 {
     Issue[] issues = null;
     try
     {
         issues = JiraExtension.GetMCFixedIssues(from, to);
     }
     catch (Exception ex)
     {
         ConsoleLog.Error("Minecraft Jira Checker", ConsoleLog.ErrorLogBuilder(ex));
         await e.ReplyToOriginal(new StringBuilder()
                                 .AppendLine("获取信息时发生错误:")
                                 .Append(ex.GetFormatString())
                                 .ToString());
     }
     if (issues.Length > 0)
     {
         await e.ReplyToOriginal(new StringBuilder()
                                 .AppendLine("[Minecraft Jira]")
                                 .AppendLine("哇哦,Bugjang杀死了这些虫子:")
                                 .AppendLine(string.Join(Environment.NewLine, issues.Select(x => x.Title)))
                                 .Append($"统计时间: {from:yyyy-MM-dd HH:mm} ~ {to:yyyy-MM-dd HH:mm}")
                                 .ToString());
     }
     else
     {
         await e.ReplyToOriginal(new StringBuilder()
                                 .AppendLine("[Minecraft Jira]")
                                 .AppendLine("可恶,这段时间Bugjang一个虫子也没有杀")
                                 .Append($"统计时间: {from:yyyy-MM-dd HH:mm} ~ {to:yyyy-MM-dd HH:mm}")
                                 .ToString());
     }
 }
Пример #23
0
        Task LogClientAsync(LogMessage msg)
        {
            switch (msg.Severity)
            {
            case LogSeverity.Critical:
            case LogSeverity.Error:
                ConsoleLog.Fatal("Discord", $"[{msg.Source}] " + msg.Message.ToString());
                if (msg.Severity == LogSeverity.Error)
                {
                    ConsoleLog.Error("Discord", $"[{msg.Source}] " + ConsoleLog.ErrorLogBuilder(msg.Exception));
                }
                break;

            case LogSeverity.Warning:
                ConsoleLog.Warning("Discord", $"[{msg.Source}] " + msg.Message.ToString());
                break;

            case LogSeverity.Info:
                ConsoleLog.Info("Discord", $"[{msg.Source}] " + msg.Message.ToString());
                break;

            case LogSeverity.Verbose:
            case LogSeverity.Debug:
                ConsoleLog.Debug("Discord", $"[{msg.Source}] " + msg.Message.ToString());
                break;

            default:
                break;
            }
            ;
            return(Task.CompletedTask);
        }
Пример #24
0
 public void GetChat() //消息接收并判断是否响应
 {
     try
     {
         //获取第二个字符开始到空格为止的PCR命令
         PCRGuildCommand = PCRGuildEventArgs.Message.Text.Substring(1).Split(' ')[0];
         //获取指令类型
         PCRGuildCmd.PCRGuildCommands.TryGetValue(PCRGuildCommand, out PCRGuildCmdType commandType);
         ConsoleLog.Debug("Guild Command", $"user={PCRGuildEventArgs.FromQQ.Id} command={commandType}");
         this.CommandType = commandType;
         //未知指令
         if (CommandType == 0)
         {
             GetUnknowCommand(PCRGuildEventArgs);
             ConsoleLog.Info("PCR公会管理", CommandType == 0 ? "解析到未知指令" : $"解析指令{CommandType}");
             return;
         }
         //公会管理指令
         if (CommandType > 0 && (int)CommandType < 100)
         {
             PCRHandler.GuildMgrResponse(Sender, PCRGuildEventArgs, CommandType);
         }
         //出刀管理指令
         else if ((int)CommandType > 100 && (int)CommandType < 200)
         {
             GuildBattleManager battleManager = new GuildBattleManager(PCRGuildEventArgs, CommandType);
             battleManager.GuildBattleResponse();
         }
     }
     catch (Exception e)
     {
         //命令无法被正确解析
         ConsoleLog.Error("PCR公会管理", $"指令解析发生错误\n{e}");
     }
 }
Пример #25
0
        public static async void LimitImageScale(string path, int maxWidth, int maxHeight)
        {
            await Task.Run(() =>
            {
                try
                {
                    IImageFormat format   = Image.DetectFormat(path);
                    IImageEncoder encoder = null;
                    if (format == Png)
                    {
                        encoder = PngEncoder;
                    }
                    else if (format == Jpeg)
                    {
                        encoder = JpegEncoder;
                    }
                    else if (format == Bmp)
                    {
                        encoder = BmpEncoder;
                    }
                    else if (format == Gif)
                    {
                        encoder = GifEncoder;
                    }
                    else
                    {
                        return;
                    }

                    var image  = Image.Load <Rgba32>(path);
                    bool flag  = false;
                    var width  = image.Width;
                    var height = image.Height;
                    if (width > maxWidth)
                    {
                        flag     = true;
                        var rate = (double)maxWidth / width;
                        width    = Convert.ToInt32(Math.Floor(width *rate));
                        height   = Convert.ToInt32(Math.Floor(height *rate));
                    }
                    if (height > maxHeight)
                    {
                        flag     = true;
                        var rate = (double)maxHeight / height;
                        width    = Convert.ToInt32(Math.Floor(width *rate));
                        height   = Convert.ToInt32(Math.Floor(height *rate));
                    }
                    if (flag)
                    {
                        image.Mutate(x => x.Resize(width, height, new BoxResampler()));
                        image.Save(path, encoder);
                    }
                }
                catch (Exception ex)
                {
                    ConsoleLog.Error("Image Utils", ex.GetFormatString());
                }
            });
        }
Пример #26
0
        /// <summary>
        /// 数据库发生错误时的消息提示
        /// </summary>
        public static async ValueTask DatabaseFailedTips(GroupMessageEventArgs groupEventArgs)
        {
            await groupEventArgs.SourceGroup.SendGroupMessage(CQCode.CQAt(groupEventArgs.Sender.Id),
                                                              "\r\nERROR",
                                                              "\r\n数据库错误");

            ConsoleLog.Error("database", "database error");
        }
        public override async Task <CheckResult.Base.SubscribeCheckResult> Check()
        {
            RssSchema version;

            try
            {
                var feed = await Feed.Read();

                version = feed.FirstOrDefault();
            }
            catch (Exception e)
            {
                ConsoleLog.Error("Minecraft Version Checker", ConsoleLog.ErrorLogBuilder(e));
                return(new MinecraftVersionCheckResult());
            }
            if (version == null)
            {
                return(new MinecraftVersionCheckResult());
            }
            var t = await Database.Data.Table <SubscribeStatusRecord>().ToListAsync();

            if (t != null && t.Count > 0)
            {
                var record = t.Where(x => x.Type == type && x.Target == "java").FirstOrDefault();
                if (record != null)
                {
                    if (record.Status != version.Content)
                    {
                        record.Status = version.Content;
                        await Database.Data.UpdateAsync(record);

                        return(new MinecraftVersionCheckResult()
                        {
                            Updated = true,
                            Title = version.Content,
                            Time = version.PublishDate
                        });
                    }
                    else
                    {
                        return(new MinecraftVersionCheckResult());
                    }
                }
            }
            await Database.Data.InsertAsync(new SubscribeStatusRecord()
            {
                Type   = type,
                Target = "java",
                Status = version.Content
            });

            return(new MinecraftVersionCheckResult()
            {
                Updated = true,
                Title = version.Content,
                Time = version.PublishDate
            });
        }
Пример #28
0
        private static void FriendlyException(UnhandledExceptionEventArgs args)
        {
            var e = args.ExceptionObject as Exception;

            if (e is JsonSerializationException)
            {
                ConsoleLog.Error("Sora", "出现错误,可能是go-cqhttp配置出现问题。请把go-cqhttp配置中的post_message_format从String改为Array。");
            }
            ConsoleLog.UnhandledExceptionLog(args);
        }
Пример #29
0
 /// <summary>
 /// At CQ码
 /// </summary>
 /// <param name="uid">用户uid</param>
 public static CQCode CQAt(long uid)
 {
     if (uid < 10000)
     {
         ConsoleLog.Error("CQCode|CQAt", $"非法参数,已忽略CQ码[uid超出范围限制({uid})]");
         return CQIlleage();
     }
     return new CQCode(CQFunction.At,
                       new At {Traget = uid.ToString()});
 }
Пример #30
0
        static void Launch()
        {
            var cfg = Config = Config.LoadConfig();

#if DEBUG
            ConsoleLog.SetLogLevel(LogLevel.Debug);
            ConsoleLog.Debug("Main", "当前正在使用Debug模式");
#else
            if (cfg.IsDebug)
            {
                ConsoleLog.SetLogLevel(LogLevel.Debug);
                ConsoleLog.Debug("Main", "当前正在使用Debug模式");
            }
            else
            {
                ConsoleLog.SetLogLevel(LogLevel.Info);
            }
#endif
            ConsoleLog.Debug("Main", "Config:\r\n" + JsonConvert.SerializeObject(cfg, Formatting.Indented));

            ConsoleLog.Info("Main", "初始化数据库中……");
            Database.Init(cfg.DatabasePath);
            ConsoleLog.Info("Main", "数据库已装载");

            ConsoleLog.Info("Main", "订阅系统启动中……");
            SubscribeManager.Init();
            ConsoleLog.Info("Main", "订阅系统已装载");

            if (!string.IsNullOrWhiteSpace(Config.Roll_Api_Id) && !string.IsNullOrWhiteSpace(Config.Roll_Api_Secret))
            {
                Library.Roll.RollApi.Init(Config.Roll_Api_Id, Config.Roll_Api_Secret);
                ConsoleLog.Info("Main", "Roll Api 已初始化");
            }

            if (cfg.Discord)
            {
                Working = true;
                ConsoleLog.Info("Main", "已启用Discord功能");
                new Thread(() =>
                {
                    try
                    {
                        DiscordServer = new(cfg.DiscordToken);
                        DiscordServer.Start();
                    }
                    catch (Exception ex)
                    {
                        ConsoleLog.Fatal("Main", "Discord功能启动失败");
                        ConsoleLog.Error("Main", ConsoleLog.ErrorLogBuilder(ex));
                        Working = false;
                    }
                })
                {
                    IsBackground = true
                }.Start();