Esempio n. 1
0
        internal static string GetAbout(Update update, string[] args)
        {
            var       language = GetLanguage(update.Message.From.Id);
            var       files    = Directory.GetFiles(Bot.LanguageDirectory);
            XDocument doc;
            var       file = files.First(x => Path.GetFileNameWithoutExtension(x) == language);
            {
                doc = LanguageConverter.Load(file);
            }
            var strings = doc.Descendants("string")
                          .FirstOrDefault(x => x.Attribute("key").Value.ToLower() == args[0].ToLower());

            if (strings == null)
            {
                var efile = LanguageConverter.Load(Path.Combine(Bot.LanguageDirectory, "English.yaml"));
                strings =
                    efile.Descendants("string")
                    .FirstOrDefault(x => x.Attribute("key").Value.ToLower() == args[0].ToLower());
            }

            if (strings == null)
            {
                return(null);
            }

            var values   = strings.Descendants("value");
            var choice   = Bot.R.Next(values.Count());
            var selected = values.ElementAt(choice);

            return(string.Format(selected.Value.FormatHTML(), args).Replace("\\n", Environment.NewLine));
        }
Esempio n. 2
0
        private static void Main(string[] args)
        {
            //set up exception logging.  It appears nodes are crashing and I'm not getting any output
            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
            {
                var ex = eventArgs.ExceptionObject as Exception;
                using (var sw = new StreamWriter(Path.Combine(RootDirectory, "../Logs/NodeFatalError.log"), true))
                {
                    sw.WriteLine($"{DateTime.Now} - {Version} - {ex.Message}");
                    sw.WriteLine(ex.StackTrace);
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                        sw.WriteLine($"{ex.Message}");
                        sw.WriteLine(ex.StackTrace);
                    }

                    sw.WriteLine("--------------------------------------------------------");
                }
            };
            English  = LanguageConverter.Load(Path.Combine(LanguageDirectory, "English.yaml"));
            APIToken = Environment.GetEnvironmentVariable("TELEGRAM_TOKEN");

            Bot      = new TelegramBotClient(APIToken);
            Me       = Bot.GetMeAsync().Result;
            ClientId = Guid.NewGuid();
            new Thread(KeepAlive).Start();
            Console.Title = $"{ClientId} - {Version.FileVersion}";
            Thread.Sleep(-1);
        }
Esempio n. 3
0
 private static string GetLocaleString(string key, string language, params object[] args)
 {
     try
     {
         var       files = Directory.GetFiles(Bot.LanguageDirectory);
         XDocument doc;
         var       file = files.First(x => Path.GetFileNameWithoutExtension(x) == language);
         {
             doc = LanguageConverter.Load(file);
         }
         var strings = doc.Descendants("string").FirstOrDefault(x => x.Attribute("key").Value == key) ??
                       Bot.English.Descendants("string").FirstOrDefault(x => x.Attribute("key").Value == key);
         var values   = strings.Descendants("value");
         var choice   = Bot.R.Next(values.Count());
         var selected = values.ElementAt(choice);
         return(string.Format(selected.Value.FormatHTML(), args).Replace("\\n", Environment.NewLine));
     }
     catch (Exception)
     {
         var strings  = Bot.English.Descendants("string").FirstOrDefault(x => x.Attribute("key").Value == key);
         var values   = strings.Descendants("value");
         var choice   = Bot.R.Next(values.Count());
         var selected = values.ElementAt(choice);
         return(string.Format(selected.Value.FormatHTML(), args).Replace("\\n", Environment.NewLine));
     }
 }
Esempio n. 4
0
 public LangFile(string path)
 {
     Doc          = LanguageConverter.Load(path);
     Name         = Doc.Descendants("language").First().Attribute("name")?.Value;
     Base         = Doc.Descendants("language").First().Attribute("base")?.Value;
     Variant      = Doc.Descendants("language").First().Attribute("variant")?.Value;
     FilePath     = path;
     FileName     = Path.GetFileNameWithoutExtension(path);
     LatestUpdate = File.GetLastWriteTimeUtc(path);
 }
Esempio n. 5
0
        public static void Initialize(string updateid = null)
        {
            //get api token from registry
            var key =
                RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
                .OpenSubKey("SOFTWARE\\Werewolf");

            TelegramApiKey = key.GetValue("ProductionAPI").ToString();

            Api = new Client(TelegramApiKey, LogDirectory);

            English = LanguageConverter.Load(Path.Combine(LanguageDirectory, "English.yaml"));

            //load the commands list
            foreach (var m in typeof(Commands).GetMethods())
            {
                var c = new Command();
                foreach (var a in m.GetCustomAttributes(true))
                {
                    if (!(a is Attributes.Command ca))
                    {
                        continue;
                    }

                    c.Blockable       = ca.Blockable;
                    c.DevOnly         = ca.DevOnly;
                    c.GlobalAdminOnly = ca.GlobalAdminOnly;
                    c.GroupAdminOnly  = ca.GroupAdminOnly;
                    c.Trigger         = ca.Trigger;
                    c.Method          = (ChatCommandMethod)Delegate.CreateDelegate(typeof(ChatCommandMethod), m);
                    c.InGroupOnly     = ca.InGroupOnly;
                    Commands.Add(c);
                }
            }

            Api.InlineQueryReceived   += UpdateHandler.InlineQueryReceived;
            Api.UpdateReceived        += UpdateHandler.UpdateReceived;
            Api.CallbackQueryReceived += UpdateHandler.CallbackReceived;
            Api.ReceiveError          += ApiOnReceiveError;
            //Api.OnReceiveGeneralError += ApiOnOnReceiveGeneralError;
            Api.StatusChanged += ApiOnStatusChanged;
            //Api.UpdatesReceived += ApiOnUpdatesReceived;
            Me = Api.GetMeAsync().Result;
            //Api.OnMessage += ApiOnOnMessage;
            Console.Title += " " + Me.Username;
            if (!string.IsNullOrEmpty(updateid))
            {
                Api.SendTextMessageAsync(updateid, "Control updated\n" + Program.GetVersion());
            }

            StartTime = DateTime.UtcNow;

            //now we can start receiving
            Api.StartReceiving();
        }
Esempio n. 6
0
        public static string GetLanguageName(string baseName)
        {
            var       files = Directory.GetFiles(Bot.LanguageDirectory);
            XDocument doc;
            var       file = files.First(x => Path.GetFileNameWithoutExtension(x) == baseName);
            {
                doc = LanguageConverter.Load(file);
            }
            var langNode = doc.Descendants("language").First();

            return($"{langNode.Attribute("base").Value}"); // - {langNode.Attribute("variant").Value}
        }
Esempio n. 7
0
        private static void Main(string[] args)
        {
            //set up exception logging.  It appears nodes are crashing and I'm not getting any output
            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
            {
                var ex = eventArgs.ExceptionObject as Exception;
                using (var sw = new StreamWriter(Path.Combine(RootDirectory, "../Logs/NodeFatalError.log"), true))
                {
                    sw.WriteLine($"{DateTime.Now} - {Version} - {ex.Message}");
                    sw.WriteLine(ex.StackTrace);
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                        sw.WriteLine($"{ex.Message}");
                        sw.WriteLine(ex.StackTrace);
                    }

                    sw.WriteLine("--------------------------------------------------------");
                }
            };
            English = LanguageConverter.Load(Path.Combine(LanguageDirectory, "English.yaml"));


            //get api token from registry
            var key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
                      .OpenSubKey("SOFTWARE\\Werewolf");

            APIToken = key.GetValue("ProductionAPI").ToString();

            Bot      = new TelegramBotClient(APIToken);
            Me       = Bot.GetMeAsync().Result;
            ClientId = Guid.NewGuid();
            new Thread(KeepAlive).Start();
            Console.Title = $"{ClientId} - {Version.FileVersion}";
            Thread.Sleep(-1);
        }
Esempio n. 8
0
        public static void ValidateFiles(long id, int msgId, string choice = null)
        {
            var errors = new List <LanguageError>();

            //first, let's load up the English file, which is our master file
            var master = LanguageConverter.Load(Path.Combine(Bot.LanguageDirectory, "English.yaml"));

            foreach (var langfile in Directory.GetFiles(Bot.LanguageDirectory).Where(x => !x.EndsWith("English.yaml"))
                     .Select(x => new LangFile(x)))
            {
                if (langfile.Base == choice || choice == null)
                {
                    //first check the language node
                    CheckLanguageNode(langfile, errors);

                    //test the length
                    TestLength(langfile, errors);

                    //get the file errors
                    GetFileErrors(langfile, errors, master);
                }
            }

            //now pack up the errors and send
            var result = "";

            foreach (var file in errors.Select(x => x.File).Distinct().ToList())
            {
                var langfile = new LangFile(Path.Combine(Bot.LanguageDirectory, $"{file}.yaml"));
                result += $"*{langfile.FileName}.yaml* (Last updated: {langfile.LatestUpdate.ToString("MMM dd")})\n";
                if (errors.Any(x => x.Level == ErrorLevel.Ads))
                {
                    result += "*Ads detected:";
                    result  = errors.Where(x => x.File == langfile.FileName && x.Level == ErrorLevel.Ads)
                              .Aggregate(result, (current, fileError) => current + fileError.Key + ", ")
                              .TrimEnd(',', ' ') + "\n";
                    continue;
                }

                if (errors.Any(x => x.Level == ErrorLevel.DuplicatedString))
                {
                    result += "_Duplicated Strings: _";
                    result  = errors.Where(x => x.File == langfile.FileName && x.Level == ErrorLevel.DuplicatedString)
                              .Aggregate(result, (current, fileError) => current + fileError.Key + ", ")
                              .TrimEnd(',', ' ') + "\n";
                }

                if (errors.Any(x => x.Level == ErrorLevel.JoinLink))
                {
                    result += "_Join commands: _";
                    result  = errors.Where(x => x.File == langfile.FileName && x.Level == ErrorLevel.JoinLink)
                              .Aggregate(result, (current, fileError) => current + fileError.Key + ", ")
                              .TrimEnd(',', ' ') + "\n";
                }

                result +=
                    $"_Missing strings:_ {errors.Count(x => x.Level == ErrorLevel.MissingString && x.File == langfile.FileName)}\n";
                if (errors.Any(x => x.File == langfile.FileName && x.Level == ErrorLevel.Error))
                {
                    result = errors.Where(x => x.File == langfile.FileName && x.Level == ErrorLevel.Error)
                             .Aggregate(result,
                                        (current, fileError) =>
                                        current + $"_{fileError.Level} - {fileError.Key}_\n{fileError.Message}\n");
                }

                result += "\n";
            }

            Bot.Api.SendTextMessageAsync(id, result, parseMode: ParseMode.Markdown);
            var sortedfiles = Directory.GetFiles(Bot.LanguageDirectory).Select(x => new LangFile(x))
                              .Where(x => x.Base == (choice ?? x.Base)).OrderBy(x => x.LatestUpdate);

            result =
                $"*Validation complete*\nErrors: {errors.Count(x => x.Level == ErrorLevel.Error)}\nMissing strings: {errors.Count(x => x.Level == ErrorLevel.MissingString)}";
            result +=
                $"\nMost recently updated file: {sortedfiles.Last().FileName}.yaml ({sortedfiles.Last().LatestUpdate.ToString("MMM dd")})\nLeast recently updated file: {sortedfiles.First().FileName}.yaml ({sortedfiles.First().LatestUpdate.ToString("MMM dd")})";

            Bot.Api.EditMessageTextAsync(id, msgId, result, ParseMode.Markdown);
        }
Esempio n. 9
0
        public static void UseNewLanguageFile(string fileName, long id, int msgId)
        {
            var msg = "Moving file to production..\n";

            msg += "Checking paths for duplicate language file...\n";
            Bot.Api.EditMessageTextAsync(id, msgId, msg);
            fileName += ".yaml";
            var tempPath    = Bot.TempLanguageDirectory;
            var langPath    = Bot.LanguageDirectory;
            var newFilePath = Path.Combine(tempPath, fileName);
            var copyToPath  = Path.Combine(langPath, fileName);

            //get the new files language
            var doc = LanguageConverter.Load(newFilePath);

            var newFileLang = new
            {
                Name    = doc.Descendants("language").First().Attribute("name").Value,
                Base    = doc.Descendants("language").First().Attribute("base").Value,
                Variant = doc.Descendants("language").First().Attribute("variant").Value
            };


            //check for existing file
            var langs = Directory.GetFiles(langPath).Select(x => new LangFile(x)).ToList();
            var lang  = langs.FirstOrDefault(x => x.Name == newFileLang.Name && x.FilePath != copyToPath);

            if (lang != null)
            {
                msg +=
                    $"Found duplicate language (name attribute) with filename {Path.GetFileNameWithoutExtension(lang.FilePath)}\n";
                copyToPath = lang.FilePath;
            }
            else
            {
                lang = langs.FirstOrDefault(x =>
                                            x.Base == newFileLang.Base && x.Variant == newFileLang.Variant && x.Name != newFileLang.Name);
                if (lang != null)
                {
                    msg +=
                        $"Found duplicate language (matching base and variant) with filename {Path.GetFileNameWithoutExtension(lang.FilePath)}\n";
                    msg += "Aborting!";
                    Bot.Api.EditMessageTextAsync(id, msgId, msg);
                    return;
                }
            }


            File.Copy(newFilePath, copyToPath, true);
            msg += "File copied to bot\n";
//#if RELEASE
//            msg += $"File copied to bot 1\n";
//#elif RELEASE2
//            msg += $"File copied to bot 2\n";
//#endif
            //Bot.Api.EditMessageTextAsync(id, msgId, msg);
//#if RELEASE
//            copyToPath = copyToPath.Replace("Werewolf 3.0", "Werewolf 3.0 Clone");
//            System.IO.File.Copy(newFilePath, copyToPath, true);
//            msg += $"File copied to bot 2\n";
//            Bot.Api.EditMessageTextAsync(id, msgId, msg);
//#endif
            var gitPath = Path.Combine(@"C:\Werewolf Source\Werewolf\Werewolf for Telegram\Languages",
                                       Path.GetFileName(copyToPath));

            File.Copy(newFilePath, gitPath, true);
            File.Delete(newFilePath);
            msg += $"File copied to git directory\n";
            if (newFilePath.EndsWith("English.yaml"))
            {
                var p = new Process
                {
                    StartInfo =
                    {
                        FileName               = @"C:\Werewolf Source\Werewolf\Werewolf for Telegram\Languages\commit.bat",
                        Arguments              = $"\"Syncing langfiles from Telegram (English.yaml update)\"",
                        WorkingDirectory       = @"C:\Werewolf Source\Werewolf\Werewolf for Telegram\Languages",
                        UseShellExecute        = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                        CreateNoWindow         = true
                    }
                };

                p.Start();
                msg += "Started the committing process. Reading output from git...";
                Bot.Edit(id, msgId, msg);

                var output = "";
                while (!p.StandardOutput.EndOfStream)
                {
                    output += p.StandardOutput.ReadLine() + Environment.NewLine;
                }

                while (!p.StandardError.EndOfStream)
                {
                    output += p.StandardError.ReadLine() + Environment.NewLine;
                }

                msg += "\nValidating the output...";
                Bot.Edit(id, msgId, msg);

                //validate the output
                if (output.Contains("failed"))
                {
                    msg += "\n<b>Failed</b> to commit files. See control output for information";
                    Console.WriteLine(output);
                }
                else if (output.Contains("nothing to commit"))
                {
                    msg += "\nNothing to commit.";
                }
                else
                {
                    //try to grab the commit
                    var regex  = new Regex("(\\[master .*])");
                    var match  = regex.Match(output);
                    var commit = "";
                    if (match.Success)
                    {
                        commit = match.Value.Replace("[master ", "").Replace("]", "");
                    }

                    msg +=
                        $"\n<b>Files committed successfully.</b> {(string.IsNullOrEmpty(commit) ? "" : $"<a href=\"https://github.com/GreyWolfDev/Werewolf/commit/" + commit + $"\">{commit}</a>")}";
                }
            }

            msg += "\n<b>Operation complete.</b>";

            Bot.Api.EditMessageTextAsync(id, msgId, msg, ParseMode.Html);
        }
Esempio n. 10
0
        internal static void UploadFile(string fileid, long id, string newFileCorrectName, int msgID)
        {
            var file = Bot.Api.GetFileAsync(fileid).Result;
            var path = Directory.CreateDirectory(Bot.TempLanguageDirectory);
            //var fileName = file.FilePath.Substring(file.FilePath.LastIndexOf("/") + 1);
            var uri         = $"https://api.telegram.org/file/bot{Bot.TelegramApiKey}/{file.FilePath}";
            var newFilePath = Path.Combine(path.FullName, newFileCorrectName);

            using (var client = new WebClient())
            {
                client.DownloadFile(new Uri(uri), newFilePath);
            }


            //ok, we have the file.  Now we need to determine the language, scan it and the original file.
            var newFileErrors = new List <LanguageError>();
            //first, let's load up the English file, which is our master file
            var langs   = Directory.GetFiles(Bot.LanguageDirectory, "*.yaml").Select(x => new LangFile(x));
            var master  = LanguageConverter.Load(Path.Combine(Bot.LanguageDirectory, "English.yaml"));
            var newFile = new LangFile(newFilePath);

            //make sure it has a complete langnode
            CheckLanguageNode(newFile, newFileErrors);

            //test the length
            TestLength(newFile, newFileErrors);

            //check uniqueness
            var error = langs.FirstOrDefault(x =>
                                             x.FileName.ToLower() == newFile.FileName.ToLower() &&
                                             x.Name != newFile.Name || //check for matching filename and mismatching name
                                             x.Name == newFile.Name &&
                                             (x.Base != newFile.Base ||
                                              x.Variant != newFile.Variant) || //check for same name and mismatching base-variant
                                             x.Base == newFile.Base && x.Variant == newFile.Variant &&
                                             x.FileName != newFile.FileName //check for same base-variant and mismatching filename
                                                                            //if we want to have the possibility to rename the file, change previous line with FileName -> Name
                                             );

            if (error != null)
            {
                //problem....
                newFileErrors.Add(new LanguageError(newFile.FileName, "*Language Node*",
                                                    $"ERROR: The following file partially matches the same language node. Please check the file name, and the language name, base and variant. Aborting.\n\n*{error.FileName}.yaml*\n_Name:_{error.Name}\n_Base:_{error.Base}\n_Variant:_{error.Variant}",
                                                    ErrorLevel.FatalError));
            }

            //get the errors in it
            GetFileErrors(newFile, newFileErrors, master);

            //need to get the current file
            var curFile       = langs.FirstOrDefault(x => x.Name == newFile.Name);
            var curFileErrors = new List <LanguageError>();

            if (curFile != null)
            {
                //test the length
                TestLength(curFile, curFileErrors);

                ////validate current file name / base / variants match
                //if (newFile.Base != lang.Base)
                //{
                //    newFileErrors.Add(new LanguageError(curFileName, "Language Node", $"Mismatched Base! {newFile.Base} - {lang.Base}", ErrorLevel.Error));
                //}
                //if (newFile.Variant != lang.Variant)
                //{
                //    newFileErrors.Add(new LanguageError(curFileName, "Language Node", $"Mismatched Variant! {newFile.Variant} - {lang.Variant}", ErrorLevel.Error));
                //}

                //get the errors in it
                GetFileErrors(curFile, curFileErrors, master);
            }

            //send the validation result
            Bot.Api.SendTextMessageAsync(id, OutputResult(newFile, newFileErrors, curFile, curFileErrors),
                                         parseMode: ParseMode.Markdown);
            Thread.Sleep(500);


            if (newFileErrors.All(x => x.Level != ErrorLevel.FatalError && x.Level != ErrorLevel.Ads))
            {
                //load up each file and get the names
                var buttons = new[]
                {
                    new InlineKeyboardCallbackButton($"New", $"upload|{id}|{newFile.FileName}"),
                    new InlineKeyboardCallbackButton($"Old", $"upload|{id}|current")
                };
                var menu = new InlineKeyboardMarkup(buttons.ToArray());
                Bot.Api.SendTextMessageAsync(id, "Which file do you want to keep?", replyToMessageId: msgID,
                                             replyMarkup: menu);
            }
            else
            {
                Bot.Api.SendTextMessageAsync(id, "Fatal errors present, cannot upload.", replyToMessageId: msgID);
            }
        }
Esempio n. 11
0
        public static void ValidateLanguageFile(long id, string filePath, int msgId)
        {
            var errors   = new List <LanguageError>();
            var langfile = new LangFile(filePath);

            //first, let's load up the English file, which is our master file
            var master = LanguageConverter.Load(Path.Combine(Bot.LanguageDirectory, "English.yaml"));

            //first check the language node
            CheckLanguageNode(langfile, errors);

            //now test the length
            TestLength(langfile, errors);

            //get the errors
            GetFileErrors(langfile, errors, master);

            //send the result
            var result = $"*{langfile.FileName}.yaml* (Last updated: {langfile.LatestUpdate:MMM dd})" +
                         Environment.NewLine;

            if (errors.Any(x => x.Level == ErrorLevel.Ads))
            {
                result += "*ADS DETECTED*\n";
                result  = errors.Where(x => x.Level == ErrorLevel.Error)
                          .Aggregate(result, (current, fileError) => current + $"{fileError.Key}\n");
            }
            else
            {
                if (errors.Any(x => x.Level == ErrorLevel.Error))
                {
                    result += "_Errors:_\n";
                    result  = errors.Where(x => x.Level == ErrorLevel.Error).Aggregate(result,
                                                                                       (current, fileError) => current + $"{fileError.Key}\n{fileError.Message}\n\n");
                }

                if (errors.Any(x => x.Level == ErrorLevel.MissingString))
                {
                    result += "_Missing Values:_\n";
                    result  = errors.Where(x => x.Level == ErrorLevel.MissingString)
                              .Aggregate(result, (current, fileError) => current + $"{fileError.Key}\n");
                }

                if (errors.Any(x => x.Level == ErrorLevel.DuplicatedString))
                {
                    result += "\n_Duplicated Strings:_\n";
                    result  = errors.Where(x => x.Level == ErrorLevel.DuplicatedString)
                              .Aggregate(result, (current, fileError) => current + fileError.Key + ", ")
                              .TrimEnd(',', ' ') + "\n";
                }

                if (errors.Any(x => x.Level == ErrorLevel.JoinLink))
                {
                    result += "\n_Join commands:_\n";
                    result  = errors.Where(x => x.Level == ErrorLevel.JoinLink)
                              .Aggregate(result, (current, fileError) => current + fileError.Key + ", ")
                              .TrimEnd(',', ' ') + "\n";
                }

                if (errors.Any(x => x.Level == ErrorLevel.FatalError))
                {
                    result += "\n*Fatal errors:*\n";
                    result  = errors.Where(x => x.Level == ErrorLevel.FatalError).Aggregate(result,
                                                                                            (current, fileError) => current + $"{fileError.Key}\n{fileError.Message}\n");
                }
            }

            result += "\n";
            //Program.Send(result, id);
            Thread.Sleep(500);
            result +=
                $"*Validation complete*.\nErrors: {errors.Count(x => x.Level == ErrorLevel.Error)}\nMissing strings: {errors.Count(x => x.Level == ErrorLevel.MissingString)}";
            Bot.Api.EditMessageTextAsync(id, msgId, result, ParseMode.Markdown);
        }