public static void Reload() { CommandManager.ClearExternalCommands(); CFormat.WriteLine("[CommandManager] Cleared loaded external commands.", ConsoleColor.Gray); CFormat.JumpLine(); CommandManager.LoadExternalCommands(true); }
public static void LoadXmlConfig() { if (!File.Exists(Properties.Settings.Default.configFileName)) { CreateFile(); return; } CFormat.Print("Chargement du fichier de configuration.", "XmlManager", DateTime.Now, ConsoleColor.Yellow); FileStream reader = new FileStream(Properties.Settings.Default.configFileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read); try { Config._INSTANCE = (Config)_Serializer.ReadObject(reader); reader.Close(); } catch (Exception ex) { reader.Close(); CFormat.Print("Erreur lors de la lecture du fichier de configuration. Détails : " + ex.Message, "XmlManager", DateTime.Now, ConsoleColor.Yellow); CreateFile(); // force file creation } }
public static void Debug() { CFormat.Write("Download progress: "); for (int i = 0; i <= 100; i++) { CFormat.DrawProgressBar(i, 100, 10, '■', ConsoleColor.Green, ConsoleColor.DarkGray); System.Threading.Thread.Sleep(10); } }
public static void UnloadFile() { LoadedFiles(); CFormat.JumpLine(); CFormat.WriteLine("Please enter the number ID of the file you want to unload.", ConsoleColor.Gray); int id = CInput.UserPickInt(CommandManager.LoadedFileIDs.Count - 1); if (id == -1) { return; } CommandManager.UnloadFile(id); }
public static string GetIdByName(string name) { string id = ""; foreach (var item in m_StageDefList) { if (CFormat.ToSimplified(item.name) == name) { id = item.id; break; } } return(id); }
public static void SaveXmlConfig() { CFormat.Print("Sauvegarde du fichier de configuration.", "XmlManager", DateTime.Now, ConsoleColor.Yellow); StreamWriter sr = new StreamWriter(Properties.Settings.Default.configFileName, false); XmlWriter writer = XmlWriter.Create(sr, _settings); _Serializer.WriteObject(writer, Config._INSTANCE); writer.Flush(); sr.Flush(); writer.Close(); sr.Close(); }
public List <HeroScore> GetHeroScore(bool sort) { m_HeroScores.Clear(); //读取文件重建m_HeroScores FileStream cwar_last_fs = new FileStream(m_BaseForlder + "\\Login\\cwar\\cwar_last.txt", FileMode.Open, FileAccess.Read); StreamReader cwar_last_rd = new StreamReader(cwar_last_fs, Encoding.GetEncoding(950)); string strLine = ""; strLine = cwar_last_rd.ReadLine(); do { strLine = strLine.Split('/')[0]; if (strLine.Contains("item")) { //ToSimplified HeroScore heroScore = new HeroScore(); strLine = CFormat.ToSimplified(strLine); strLine = strLine.Split(new string[] { " = " }, StringSplitOptions.RemoveEmptyEntries)[1]; var heres = strLine.Split(','); if (heres[0] != "") { heroScore.name = heres[0]; heroScore.level = int.Parse(heres[1]); heroScore.unkown1 = heres[2]; heroScore.unkown2 = heres[3]; heroScore.score = int.Parse(heres[4]); heroScore.num = int.Parse(heres[5]); heroScore.unkwon3 = heres[6]; m_HeroScores.Add(heroScore); } } strLine = ""; strLine = cwar_last_rd.ReadLine(); } while (strLine != null); if (sort) { m_HeroScores.Sort(new Comparison <HeroScore>(AnswerResultCompare)); } cwar_last_rd.Close(); cwar_last_fs.Close(); return(m_HeroScores); }
public static void LoadedFiles() { if (CommandManager.LoadedFileIDs.Count == 0) { CFormat.WriteLine("[CommandManager] There are no external files loaded.", ConsoleColor.Gray); } else { CFormat.WriteLine("[CommandManager] List of loaded files: ", ConsoleColor.Gray); foreach (FileID listLoadedFile in CommandManager.LoadedFileIDs) { CFormat.WriteLine(string.Format("{0}({1}) {2}", CFormat.Indent(2), listLoadedFile.ID, listLoadedFile.Path), ConsoleColor.Gray); } } }
public static string GetNameById(string id) { string name = ""; foreach (var item in m_StageDefList) { if (CFormat.ToSimplified(item.id) == id || CFormat.ToSimplified(item.id) == "0" + id || "0" + CFormat.ToSimplified(item.id) == id) { name = item.name; break; } } return(name); }
public static void RetrieveMoney(IUser user, double amount, ICommandContext _context) { Config._INSTANCE.GuildConfigs[_context.Guild.Id].XUsers[_context.User.Id].Money -= amount; double money = Config._INSTANCE.GuildConfigs[_context.Guild.Id].XUsers[_context.User.Id].Money; _context.Channel.SendMessageAsync("", false, new EmbedBuilder() { Title = "X.A.N.A. - Comptabilité", Color = Color.Red, Description = user.Mention + " a perdu " + amount + " pièce" + CFormat.AddPluralS(amount) + "." + Environment.NewLine + "Nouveau solde : **" + money + "** pièce" + CFormat.AddPluralS(money) }.Build()); XmlManager.SaveXmlConfig(); }
public static bool LoadStageDefInfo() { //文件存在 if (!File.Exists("profile\\STAGE.H")) { return(false); } //读取 m_StageDefList.Clear(); FileStream fs = new FileStream("profile\\STAGE.H", FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(fs, Encoding.GetEncoding(950)); reader.DiscardBufferedData(); reader.BaseStream.Seek(0, SeekOrigin.Begin); reader.BaseStream.Position = 0; string strLine = ""; strLine = reader.ReadLine(); while (strLine != null) { strLine = strLine.Split('/')[0]; if (strLine.Contains("#define")) { StageDef_Str stageDef; string tmp = strLine.Split(new string[] { "city_" }, StringSplitOptions.RemoveEmptyEntries)[1]; string name = tmp.Split(' ')[0].Split('\t')[0]; string id = tmp.Replace(" ", "").Replace("\\t", "").Replace(name, ""); id = CFormat.PureString(id); //去掉前面的0 id = CFormat.RemoveXZeroStr(id); stageDef.id = CFormat.PureString(id); stageDef.name = CFormat.PureString(name); m_StageDefList.Add(stageDef); } strLine = null; strLine = reader.ReadLine(); } reader.Close(); fs.Close(); return(true); }
private static void CreateFile() { try { CFormat.Print("Création d'un nouveau fichier de configuration.", "XmlManager", DateTime.Now, ConsoleColor.Yellow); Config._INSTANCE.ResetDefault(); SaveXmlConfig(); return; } catch (Exception ex) { CFormat.Print("Impossible de créer un fichier de configuration. Détails : " + ex.Message, "XmlManager", DateTime.Now, ConsoleColor.Yellow); CFormat.Write("Appuyez sur une touche pour quitter l'application..."); Console.ReadKey(true); Environment.Exit(0); } }
public static void CreateTemplate(string path = null) { try { if (path == null) { path = "TemplateFile" + Path.GetExtension("*.cs"); } CFormat.WriteLine("Creating template file \"" + path + "\""); if (File.Exists(path)) { CFormat.WriteLine("A file named \"" + path + "\" already exists. Replace it?"); ConsoleAnswer answer = CInput.UserChoice(ConsoleAnswerType.YesNo, true); if (answer == ConsoleAnswer.No) { int num = 1; string withoutExtension = Path.GetFileNameWithoutExtension(path); while (File.Exists(path)) { path = Path.Combine(Path.GetDirectoryName(path), withoutExtension + " (" + num + ")", Path.GetExtension(path)); ++num; } } else if (answer == ConsoleAnswer.Escaped) { return; } } using (StreamWriter streamWriter = new StreamWriter(path, false, Encoding.UTF8)) streamWriter.Write(Properties.Resources.FileTemplate); CFormat.WriteLine("Template file named \"" + path + "\" created!", ConsoleColor.Green); } catch (Exception ex) { CFormat.WriteLine("Could not create template file \"" + path + "\" Details: " + ex.Message, ConsoleColor.Red); } }
/// <summary> /// /!\ WARNING /!\ NEVER USE UNLESS FILE CREATION /// </summary> public void ResetDefault() { CFormat.Print("Mise en place des paramètres par défaut.", "Config", DateTime.Now, ConsoleColor.Yellow); BotToken = (string)CInput.ReadFromConsole("BotToken=", ConsoleInputType.String, false, ConsoleColor.White); XanaId = (ulong)CInput.ReadFromConsole("XanaId=", ConsoleInputType.Ulong, false, ConsoleColor.White, 18); GuildConfigs = new Dictionary <ulong, GuildConfig>(); TresorProbabilities = new Dictionary <int, int>() { { 1, 18 }, { 2, 16 }, { 3, 15 }, { 4, 13 }, { 5, 11 }, { 6, 9 }, { 7, 7 }, { 8, 5 }, { 9, 4 }, { 10, 2 } }; XanaOAuth2URL = ""; CFormat.Print("Paramètres appliqués.", "Config", DateTime.Now, ConsoleColor.Yellow); }
public List <OrganizeRst> GetNoticeStage() { //CPlayerCtrl.LoadPlayerInfos(txt_svrForder.Text + "\\DataBase\\saves\\players.dat", true); List <OrganizeAttr> organizeAttr = COrganizeCtrl.LoadOrganizeInfos(BaseForlder + "\\DataBase\\saves\\organize.dat", true); m_NoticeOrganizeRst.Clear(); foreach (var it in organizeAttr) { int stageId = it.StageId; if (m_NoticeStage.Contains(stageId)) { OrganizeRst organizeRst = new OrganizeRst(); organizeRst.stage = stageId; //get stage name by stage id organizeRst.legion = CFormat.GameStrToSimpleCN(it.OrganizeName); organizeRst.leader = CFormat.GameStrToSimpleCN(it.OrganizeLeaderZh); m_NoticeOrganizeRst.Add(organizeRst); } } return(m_NoticeOrganizeRst); }
private static void _Serializer_UnreferencedObject(object sender, UnreferencedObjectEventArgs e) { CFormat.Print("Erreur lors de la lecture du fichier de configuration : objet non référencé (détails : " + e.UnreferencedObject.ToString() + ".", "XmlManager", DateTime.Now, ConsoleColor.Red); }
public async Task MoneyAsync() { double money = Config._INSTANCE.GuildConfigs[Context.Guild.Id].XUsers[Context.User.Id].Money; await ReplyAsync("Solde de " + Context.User.Mention + " : **" + money + "** pièce" + CFormat.AddPluralS(money)); }
public static void Help(string stringCall = null) { if (stringCall == null) { List(); } else { try { // if the call is a library if (!stringCall.Contains(' ') && !stringCall.Contains('.')) { Type library = CParsedInput.ParseLibrary(stringCall); if (library == null) { CFormat.WriteLine("This library does not exist."); return; } string libraryCallName = CommandManager.ExternalLibraryCallNames.FirstOrDefault(x => x.Value == library).Key; string libraryHelpPrompt = library.GetCustomAttribute <MMasterLibrary>().HelpPrompt; if (!String.IsNullOrEmpty(libraryHelpPrompt)) { libraryHelpPrompt = " (" + libraryHelpPrompt + ")"; } CFormat.WriteLine(libraryCallName + libraryHelpPrompt, ConsoleColor.Yellow); foreach (MethodInfo methodInfo in CommandManager.ExternalLibraries[library].Values) { MMasterCommand mMasterCommand = methodInfo.GetCustomAttribute <MMasterCommand>(); string helpPrompt = mMasterCommand.HelpPrompt; if (!String.IsNullOrEmpty(helpPrompt)) { helpPrompt = " (" + helpPrompt + ")"; } CFormat.WriteLine(CFormat.Indent(3) + "." + methodInfo.Name + helpPrompt); } } else { CParsedInput parsedInput = new CParsedInput(stringCall, true); string helpPrompt = parsedInput.CommandMethodInfo.GetCustomAttribute <MMasterCommand>().HelpPrompt; if (helpPrompt == "") { CFormat.WriteLine(CFormat.GetArgsFormat(parsedInput.FullCallName, parsedInput.CommandMethodInfo.GetParameters())); } else { CFormat.WriteLine(helpPrompt, CFormat.GetArgsFormat(parsedInput.FullCallName, parsedInput.CommandMethodInfo.GetParameters())); } } } catch (WrongCallFormatException) { CFormat.WriteLine("Wrong call format.", "The call should be as it follows: <Library>.<Command> [arg1] [arg2] [etc.]"); } catch (LibraryNotExistingException) { CFormat.WriteLine("This library does not exist."); } catch (CommandNotExistingException) { CFormat.WriteLine("This command does not exist."); } } }
/// <summary>Запись сообщения.</summary> /// <param name="x_sSource">имя источника сообщения.</param>> /// <param name="x_ulType">тип сообщения.</param>> /// <param name="x_ulForm">вид сообщения.</param>> /// <param name="x_sCategory">категория сообщения.</param>> /// <param name="x_sDescription">текст сообщения.</param>> /// <returns>True, если при записи сообщения не возникли ошибки.</returns>> protected override bool WritingMessage( string x_sSource, MessageTypeEnum x_ulType, MessageFormEnum x_ulForm, string x_sCategory, string x_sDescription) { bool c_bSucceeded = true; // Преобразование типа сообщения. string c_sType = "Unknown"; switch (x_ulType) { case MessageTypeEnum.ERROR_MESSAGE: c_sType = "Error"; break; case MessageTypeEnum.WARNING_MESSAGE: c_sType = "Warning"; break; case MessageTypeEnum.INFORMATION_MESSAGE: c_sType = "Information"; break; } try { // Создание файла базы данных, если он не существует. if (!File.Exists(m_sFileName)) { (new SqlCeEngine(String.Format("Data Source='{0}'", m_sFileName))).CreateDatabase(); // Создание таблицы для сообщений. using (SqlCeConnection c_cnSqlceJournal = new SqlCeConnection(String.Format("Data Source='{0}'", m_sFileName))) { c_cnSqlceJournal.Open(); // Формирование и выполнение запроса на создание таблицы. SqlCeCommand c_cmCreate = new SqlCeCommand( String.Format(n_sTemplate_CreateTable, m_sTableName), c_cnSqlceJournal); c_cmCreate.ExecuteNonQuery(); } } using (SqlCeConnection c_cnSqlceJournal = new SqlCeConnection(String.Format("Data Source='{0}'", m_sFileName))){ c_cnSqlceJournal.Open(); // Формирование строки запроса. string c_sBuffer = ""; if (x_ulForm == MessageFormEnum.RELEASE_MESSAGE) { c_sBuffer = String.Format(n_sTemplate_InsertMessage, m_sTableName, x_sSource, c_sType, x_sCategory, x_sDescription.Replace("'", "''"), Environment.UserName, Environment.MachineName); } else { c_sBuffer = String.Format(n_sTemplate_InsertDebug, m_sTableName, x_sSource, c_sType, x_sCategory, x_sDescription.Replace("'", "''"), Environment.UserName, Environment.MachineName, Thread.CurrentThread.ManagedThreadId, CFormat.GetCaller(new StackFrame(2, true))); } // Формирование и выполнение запроса на добавление сообщения. SqlCeCommand c_cmInsert = new SqlCeCommand(c_sBuffer, c_cnSqlceJournal); if (c_cmInsert.ExecuteNonQuery() == 0) { c_bSucceeded = false; } } } catch { c_bSucceeded = false; } return(c_bSucceeded); }
/// <summary>Запись сообщения.</summary> /// <param name="x_sSource">имя источника сообщения.</param>> /// <param name="x_ulType">тип сообщения.</param>> /// <param name="x_ulForm">вид сообщения.</param>> /// <param name="x_sCategory">категория сообщения.</param>> /// <param name="x_sDescription">текст сообщения.</param>> /// <returns>True, если при записи сообщения не возникли ошибки.</returns>> protected override bool WritingMessage( string x_sSource, MessageTypeEnum x_ulType, MessageFormEnum x_ulForm, string x_sCategory, string x_sDescription) { bool c_bSucceeded = true; // Текущие дата и время. DateTime c_dtCurrentTime = DateTime.Now; // Формирование строки с именем папки журнала сообщений. string c_sFolderName = String.Format( n_sTemplate_MessageFolder, m_sFolderName, c_dtCurrentTime.Year, c_dtCurrentTime.Month, CFormat.GetMonth(c_dtCurrentTime.Month), c_dtCurrentTime.Day); // Формирование строки с расширением файла журнала сообщений. string c_sFileExtension = ""; switch (x_ulType) { case MessageTypeEnum.ERROR_MESSAGE: c_sFileExtension = "err"; break; case MessageTypeEnum.WARNING_MESSAGE: c_sFileExtension = "wrn"; break; case MessageTypeEnum.INFORMATION_MESSAGE: c_sFileExtension = "inf"; break; } // Формирование строки с именем файла журнала сообщений. string c_sFileName = String.Format( n_sTemplate_MessageFile, c_sFolderName, x_sSource, c_sFileExtension); try { // Создание папки, если она не существует. if (!Directory.Exists(c_sFolderName)) { Directory.CreateDirectory(c_sFolderName); } using (StreamWriter c_swTextJournal = new StreamWriter(new FileStream(c_sFileName, FileMode.Append, FileAccess.Write, FileShare.Read))) { // Формирование строки сообщения. string c_sBuffer = ""; if (x_ulForm == MessageFormEnum.RELEASE_MESSAGE) { c_sBuffer = String.Format( n_sTemplate_ReleaseLine, c_dtCurrentTime.Hour, c_dtCurrentTime.Minute, c_dtCurrentTime.Second, c_dtCurrentTime.Millisecond, x_sCategory, x_sDescription); } else { c_sBuffer = String.Format( n_sTemplate_DebugLine, c_dtCurrentTime.Hour, c_dtCurrentTime.Minute, c_dtCurrentTime.Second, c_dtCurrentTime.Millisecond, x_sCategory, x_sDescription, Thread.CurrentThread.ManagedThreadId, CFormat.GetCaller(new StackFrame(2, true))); } // Запись в файл сообщения. c_swTextJournal.Write(c_sBuffer); } } catch { c_bSucceeded = false; } return(c_bSucceeded); }
/// <summary>Запись сообщения.</summary> /// <param name="x_sSource">имя источника сообщения.</param>> /// <param name="x_ulType">тип сообщения.</param>> /// <param name="x_ulForm">вид сообщения.</param>> /// <param name="x_sCategory">категория сообщения.</param>> /// <param name="x_sDescription">текст сообщения.</param>> /// <returns>True, если при записи сообщения не возникли ошибки.</returns> protected override bool WritingMessage( string x_sSource, MessageTypeEnum x_ulType, MessageFormEnum x_ulForm, string x_sCategory, string x_sDescription) { bool c_bSucceeded = true; // Текущие дата и время. DateTime c_dtCurrentTime = DateTime.Now; // Преобразование типа сообщения. string c_sType = "Unknown"; switch (x_ulType) { case MessageTypeEnum.ERROR_MESSAGE: c_sType = "Error"; break; case MessageTypeEnum.WARNING_MESSAGE: c_sType = "Warning"; break; case MessageTypeEnum.INFORMATION_MESSAGE: c_sType = "Information"; break; } XmlDocument c_xdXmlJournal = new XmlDocument(); try { // Создание файла, если он не существует. if (!File.Exists(m_sFileName)) { c_xdXmlJournal.LoadXml(n_sTemplate_EmptyJournal); c_xdXmlJournal.Save(m_sFileName); } // Открытие файла. c_xdXmlJournal.Load(m_sFileName); // Добавление нового сообщения в XML документ. if (x_ulForm == MessageFormEnum.RELEASE_MESSAGE) { CXml.AddElement( c_xdXmlJournal.SelectSingleNode(n_sTemplate_JournalNode), "message", ElementTypeEnum.ATTRIBUTE_ELEMENT, "date", String.Format("{0:d2}.{1:d2}.{2:d4}", c_dtCurrentTime.Day, c_dtCurrentTime.Month, c_dtCurrentTime.Year), "time", String.Format("{0:d2}:{1:d2}:{2:d2}.{3:d3}", c_dtCurrentTime.Hour, c_dtCurrentTime.Minute, c_dtCurrentTime.Second, c_dtCurrentTime.Millisecond), "source", x_sSource, "type", c_sType, "category", x_sCategory, "description", x_sDescription, "user", Environment.UserName, "computer", Environment.MachineName); } else { CXml.AddElement( c_xdXmlJournal.SelectSingleNode(n_sTemplate_JournalNode), "message", ElementTypeEnum.ATTRIBUTE_ELEMENT, "date", String.Format("{0:d2}.{1:d2}.{2:d4}", c_dtCurrentTime.Day, c_dtCurrentTime.Month, c_dtCurrentTime.Year), "time", String.Format("{0:d2}:{1:d2}:{2:d2}.{3:d3}", c_dtCurrentTime.Hour, c_dtCurrentTime.Minute, c_dtCurrentTime.Second, c_dtCurrentTime.Millisecond), "source", x_sSource, "type", c_sType, "category", x_sCategory, "description", x_sDescription, "user", Environment.UserName, "computer", Environment.MachineName, "thread", Thread.CurrentThread.ManagedThreadId.ToString(), "writer", CFormat.GetCaller(new StackFrame(2, true))); } // Сохранение файла. c_xdXmlJournal.Save(m_sFileName); } catch { c_bSucceeded = false; } return(c_bSucceeded); }
public async Task SettingsAsync(string settingName = "", [Remainder] string value = null) { settingName.ToLower(); // GENERAL SETTINGS HELP if ((settingName == "help" && String.IsNullOrWhiteSpace(value)) || settingName == "") { EmbedBuilder embedbuilder = new EmbedBuilder() { Title = "X.A.N.A. - Liste des paramètres", Color = Color.Red }; StringBuilder sb = new StringBuilder(); sb.AppendLine("Insérez 'x!settings ' devant chaque commande."); sb.AppendLine(); foreach (KeyValuePair <string, string> property in XPropertiesHelp) { sb.AppendLine("**" + property.Key + "** : " + property.Value); } embedbuilder.Description = sb.ToString(); await ReplyAsync("", false, embedbuilder.Build()); return; } // SPECIFIC HELP SETTING else if (settingName == "help" && !String.IsNullOrWhiteSpace(value)) { if (XPropertiesHelp.Keys.Contains(value)) { EmbedBuilder embedbuilder = new EmbedBuilder() { Title = "X.A.N.A. - Aide sur le paramètre **" + value + "**", Color = Color.Red }; StringBuilder sb = new StringBuilder(); sb.AppendLine("**" + value + "** : " + XPropertiesHelp[value]); sb.AppendLine("Utilisation : " + XPropertiesUsage[value]); embedbuilder.Description = sb.ToString(); await ReplyAsync("", false, embedbuilder.Build()); return; } else { await ReplyAsync("Paramètre inconnu. Tapez **x!settings help** pour obtenir la liste des paramètres disponibles."); return; } } // GET OAUTH 2.0 URL else if (settingName == "oauth") { XmlManager.SaveXmlConfig(); await ReplyAsync("Lien pour ajouter X.A.N.A. à un serveur : " + Config._INSTANCE.XanaOAuth2URL); return; } // SAVE CONFIG else if (settingName == "save") { XmlManager.SaveXmlConfig(); await ReplyAsync("Paramètres sauvegardés."); return; } // SETTING COMMAND else if (XProperties.Keys.Contains(settingName)) // si paramètre existe { Type propertyType = XProperties[settingName].PropertyType; if (String.IsNullOrWhiteSpace(value)) // si valeur nulle { if (propertyType == typeof(bool)) { XProperties[settingName].SetValue(Config._INSTANCE, !(bool)XProperties[settingName].GetValue(Config._INSTANCE)); } else { await ReplyAsync("Veuillez indiquer la nouvelle valeur du paramètre."); await SettingsAsync("help", settingName); return; } } else { try { var parameter = CFormat.CoerceArgument(XProperties[settingName].PropertyType, value); if (CheckPropertyPermission(XProperties[settingName], (SocketGuildUser)Context.User)) { XProperties[settingName].SetValue(Config._INSTANCE.GuildConfigs[Context.Guild.Id], parameter); await ReplyAsync("Paramètre mis à jour."); XmlManager.SaveXmlConfig(); return; } else if (Context.Guild.Roles.Where(x => x.Id == Config._INSTANCE.GuildConfigs[Context.Guild.Id].AdminRoleId).Count() == 0) { await ReplyAsync("Veuillez définir le rôle pouvant modifier les paramètres Administrateurs de X.A.N.A. avec le paramètre AdminRoleId."); await Task.Run(() => SettingsAsync("help", "AdminRoleId")); return; } else { await ReplyAsync("**Accès au paramètre limité** aux utilisateurs possédant au moins le rôle avec l'identifiant définit par le paramètre AdminRoleId."); return; } } catch (Exception ex) { await ReplyAsync("Erreur lors de la mise à jour du paramètre. Détails : " + ex.Message); return; } } } else { await ReplyAsync("Paramètre inconnu. Tapez **x!settings help** pour obtenir la liste des paramètres disponibles."); return; } }
public List <HeroScore> GetHeroScore(bool sort) { m_HeroScores.Clear(); //读取文件重建m_HeroScores FileStream cwar_last_fs = new FileStream(m_BaseForlder + "\\Map\\history\\history_0351.txt", FileMode.Open, FileAccess.Read); StreamReader cwar_last_rd = new StreamReader(cwar_last_fs, Encoding.GetEncoding(950)); string strLine = ""; strLine = cwar_last_rd.ReadLine(); int lastMode = -1; do { strLine = strLine.Split('/')[0]; if (strLine.Contains("last_result")) { lastMode = 1; } else if (strLine.Contains("register_list")) { lastMode = 2; m_HeroScores.Clear(); } if (strLine.Contains("item") && lastMode == 1) { //ToSimplified HeroScore heroScore = new HeroScore(); strLine = CFormat.ToSimplified(strLine); strLine = strLine.Split(new string[] { " = " }, StringSplitOptions.RemoveEmptyEntries)[1]; var heres = strLine.Split(','); if (heres[0] != "") { heroScore.name = heres[0]; heroScore.level = 0; heroScore.unkown1 = ""; heroScore.unkown2 = ""; heroScore.score = int.Parse(heres[3]); heroScore.num = int.Parse(heres[5]); heroScore.unkwon3 = ""; m_HeroScores.Add(heroScore); } } strLine = ""; strLine = cwar_last_rd.ReadLine(); } while (strLine != null); if (m_HeroScores.Count == 0) { SGExHandle SGEx = new SGExHandle(); SGEx.SendWorldWords("赤壁未分胜负,以讨敌数排名,自动发奖!"); //查询数据库 } if (sort) { m_HeroScores.Sort(new Comparison <HeroScore>(AnswerResultCompare)); } cwar_last_rd.Close(); cwar_last_fs.Close(); return(m_HeroScores); }
private static void _Serializer_UnknownAttribute(object sender, XmlAttributeEventArgs e) { CFormat.Print("Erreur lors de la lecture du fichier de configuration : attribut inconnu (nom : " + e.Attr.Name + ".", "XmlManager", DateTime.Now, ConsoleColor.Red); }
public async Task TresorAsync(int number) { if (JoueursTimerTresor.Contains(Context.User.Id)) { await ReplyAsync(Context.User.Mention + ", attends un peu avant d'essayer de trouver un nouveau trésor."); return; } if (number < 1 || number > 10) { await ReplyAsync("Veuillez indiquer un nombre de 1 à 10 pour jouer."); return; } Random rnd = new Random(); int rndNum = rnd.Next(100) + 1; int tresorCode = 1; int previousVal = 0; // Assignation du résultat du tirage au sort for (int i = 1; i <= 10; i++) { if (rndNum <= Config._INSTANCE.TresorProbabilities[i] + previousVal) { tresorCode = i; break; } previousVal += Config._INSTANCE.TresorProbabilities[i]; } // Vérification et résultat if (number == tresorCode) { await ReplyAsync(Context.User.Mention + " a trouvé le code du coffre au trésor (" + tresorCode + ") et a gagné " + tresorCode *3 + " pièce" + CFormat.AddPluralS(tresorCode * 3) + " !"); Money.AddMoney(Context.User, tresorCode * 3, Context); JoueursTimerTresor.Add(Context.User.Id); System.Threading.Timer timer = new System.Threading.Timer((obj) => { JoueursTimerTresor.Remove(Context.User.Id); }, null, (int)(Config._INSTANCE.GuildConfigs[Context.Guild.Id].TimerTresor * 1000), System.Threading.Timeout.Infinite); } else { await ReplyAsync(Context.User.Mention + " n'a pas trouvé le code du coffre au trésor, qui était " + tresorCode + "..."); } }
public static void List() { CFormat.WriteLine("For more information about a command, type 'Help <command>'.", ConsoleColor.Gray); CFormat.JumpLine(); CFormat.WriteLine("[Internal commands]", ConsoleColor.Green); foreach (Type library in CommandManager.InternalLibraryCallNames.Values) { if (CommandManager.InternalLibraries[library].Values.Count != 0) { string libraryCallName = CommandManager.InternalLibraryCallNames.FirstOrDefault(x => x.Value == library).Key; string libraryHelpPrompt = library.GetCustomAttribute <MMasterLibrary>().HelpPrompt; if (!String.IsNullOrEmpty(libraryHelpPrompt)) { libraryHelpPrompt = " (" + libraryHelpPrompt + ")"; } CFormat.WriteLine(libraryCallName + libraryHelpPrompt, ConsoleColor.Yellow); foreach (MethodInfo methodInfo in CommandManager.InternalLibraries[library].Values) { MMasterCommand mMasterCommand = methodInfo.GetCustomAttribute <MMasterCommand>(); string helpPrompt = mMasterCommand.HelpPrompt; if (!String.IsNullOrEmpty(helpPrompt)) { helpPrompt = " (" + helpPrompt + ")"; } CFormat.WriteLine(CFormat.Indent(3) + "." + methodInfo.Name + helpPrompt); } CFormat.JumpLine(); } } if (CommandManager.ExternalLibraryCallNames.Count == 0) { return; } CFormat.WriteLine("[External commands]", ConsoleColor.Green); int num = 1; foreach (Type library in CommandManager.ExternalLibraryCallNames.Values) { string libraryCallName = CommandManager.ExternalLibraryCallNames.FirstOrDefault(x => x.Value == library).Key; string libraryHelpPrompt = library.GetCustomAttribute <MMasterLibrary>().HelpPrompt; if (!String.IsNullOrEmpty(libraryHelpPrompt)) { libraryHelpPrompt = " (" + libraryHelpPrompt + ")"; } CFormat.WriteLine(libraryCallName + libraryHelpPrompt, ConsoleColor.Yellow); foreach (MethodInfo methodInfo in CommandManager.ExternalLibraries[library].Values) { MMasterCommand mMasterCommand = methodInfo.GetCustomAttribute <MMasterCommand>(); string helpPrompt = mMasterCommand.HelpPrompt; if (!String.IsNullOrEmpty(helpPrompt)) { helpPrompt = " (" + helpPrompt + ")"; } CFormat.WriteLine(CFormat.Indent(3) + "." + methodInfo.Name + helpPrompt); } if (num < CommandManager.ExternalLibraryCallNames.Values.Count) { CFormat.JumpLine(); } ++num; } }
public List <OrganizeConstRst> GetNoticeConstStage(int flag) { if (flag == 0) //国战进行中,更新tmp,期间累计 { List <OrganizeAttr> organizeAttr = COrganizeCtrl.LoadOrganizeInfos(BaseForlder + "\\DataBase\\saves\\organize.dat", true); foreach (var it in organizeAttr) { int stageId = it.StageId; if (m_NoticeConstStage.Contains(stageId)) // 关注的城池 { OrganizeConstRst organizeRst = new OrganizeConstRst(); organizeRst.stage = stageId; //get stage name by stage id organizeRst.legion = CFormat.GameStrToSimpleCN(it.OrganizeName); organizeRst.leader = CFormat.GameStrToSimpleCN(it.OrganizeLeaderZh); bool find = false; //检测记录 for (int i = 0; i < m_NoticeTmpConstOrganizeRst.Count; i++) { if (m_NoticeTmpConstOrganizeRst[i].stage == organizeRst.stage)//如果已经找到该城池记录 { find = true; if (m_NoticeTmpConstOrganizeRst[i].legion == organizeRst.legion)//如果是同一个军团,则更新end time { organizeRst = m_NoticeTmpConstOrganizeRst[i]; organizeRst.eTime = DateTime.Now.ToString(); m_NoticeTmpConstOrganizeRst[i] = organizeRst; //判断是否达到条件 if (IsConstStageReward(Convert.ToDateTime(organizeRst.bTime), Convert.ToDateTime(organizeRst.eTime), 2)) //达到 { m_NoticeConstOrganizeRst.Add(m_NoticeTmpConstOrganizeRst[i]); organizeRst.bTime = DateTime.Now.ToString(); organizeRst.eTime = DateTime.Now.ToString(); m_NoticeTmpConstOrganizeRst[i] = organizeRst; } } else //如果不是同一个军团,则先判断上一个军团是否达到奖励条件,然后替换 { if (IsConstStageReward(Convert.ToDateTime(m_NoticeTmpConstOrganizeRst[i].bTime), DateTime.Now, 2)) {//达到 OrganizeConstRst _organizeRst = new OrganizeConstRst(); _organizeRst = m_NoticeTmpConstOrganizeRst[i]; _organizeRst.eTime = DateTime.Now.ToString(); m_NoticeConstOrganizeRst.Add(_organizeRst); organizeRst.bTime = DateTime.Now.ToString(); organizeRst.eTime = DateTime.Now.ToString(); m_NoticeTmpConstOrganizeRst[i] = organizeRst; } else { organizeRst.bTime = DateTime.Now.ToString(); organizeRst.eTime = DateTime.Now.ToString(); m_NoticeTmpConstOrganizeRst[i] = organizeRst; } } } } //否则添加记录 if (!find) { organizeRst.bTime = DateTime.Now.ToString(); organizeRst.eTime = DateTime.Now.ToString(); m_NoticeTmpConstOrganizeRst.Add(organizeRst); } } } } else if (flag == 1)//国战结束,全部计算 { foreach (var it in m_NoticeTmpConstOrganizeRst) { if (IsConstStageReward(Convert.ToDateTime(it.bTime), DateTime.Now, 2))//达到奖励条件 { m_NoticeConstOrganizeRst.Add(it); } } m_NoticeTmpConstOrganizeRst.Clear(); } return(m_NoticeConstOrganizeRst); }
[MMasterCommand("Prints Hello!", "Command")] // ARGS : HelpPrompt, CallName. Both of these args are optional. public static void Command(string message) // Call this command with 'Library.Command' { // Edit code here CFormat.WriteLine("Hello " + message + "!", ConsoleColor.Blue); }