Esempio n. 1
0
        public AppCommon.APPErrors Start()
        {
            m_frameNumber = 1;
            m_running     = true;

            m_fgControl = new FrameGrabberControl();

            while (m_running)
            {
                SLog.Instance().Write(AppCommon.MODULES.MANAGER_MODULE, "Start frame: " + m_frameNumber);
                if (m_fgControl.Start(m_config.num1, m_config.num2, m_fgEvent) == AppCommon.APPErrors.STATUS_FG_PENDING)
                {
                    bool b;
                    if ((b = m_fgEvent.WaitOne(m_config.FrameGrabberMaxTimeout)) == false)
                    {
                        if (m_running == false)
                        {
                            return(AppCommon.APPErrors.STATUS_OK);
                        }
                        return(AppCommon.APPErrors.STATUS_FG_TIMEOUT);
                    }
                    if (m_running == false)
                    {
                        return(AppCommon.APPErrors.STATUS_OK);
                    }
                    m_fgBuffer = m_fgControl.RowData;
                    SLog.Instance().Write(AppCommon.MODULES.FG_MODULE, "Got row data to pass to IP size of: " + m_fgControl.BufferLength);
                }


                m_frameNumber++;
            }

            return(AppCommon.APPErrors.STATUS_OK);
        }
        private IEnumerator CheckForUpdates()
        {
            //PLog.Info("Checking for plugin updates...");
            int updates = 0;

            foreach (Plugin plugin in Loader.plugins.Values)
            {
                try
                {
                    bool has_update = plugin.check_for_updates();
                    if (has_update)
                    {
                        updates++;
                    }
                    //PLog.Info("Plugin[{0}] has_update = {1}", plugin.data.NAME, (has_update ? "TRUE" : "FALSE"));
                }
                catch (Exception ex)
                {
                    SLog.Error(ex);
                }
            }

            if (updates <= 0)
            {
                this.Hide();
            }
            else
            {
                this.Show();
            }

            yield break;
        }
        private void process_downloads()
        {
            if (download_queue.Count > 0)
            {
                Plugin             plugin = download_queue.First();
                Plugin_Update_Item itm    = list.Get_Children().First(o => ((Plugin_Update_Item)o).plugin_hash == plugin.Hash) as Plugin_Update_Item;
                if (itm == null)
                {
                    SLog.Info("Unable to find plugin_update_item for plugin {0}({1})", plugin.data.NAME, plugin.Hash);
                    return;
                }
                else
                {
                    SLog.Info("Found plugin_update_item for plugin {0}({1})", plugin.data.NAME, plugin.Hash);
                }

                uiProgressBar prog = null;
                if (itm != null)
                {
                    prog = itm.progress_bar;
                }

                StartCoroutine(plugin.force_download(prog, (string file) =>
                {
                    download_queue.RemoveAt(0);
                    process_downloads();
                }));
            }
            else
            {
                this.Hide();
                Loader.Restart_App();
            }
        }
Esempio n. 4
0
        void LoadSettings()
        {
            try
            {
                if (File.Exists(ConfigFileName) == false)
                {
                    return;
                }

                using (StreamReader file = File.OpenText(ConfigFileName))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    m_appConfig = (AppConfig)serializer.Deserialize(file, typeof(AppConfig));
                }

                txtIpAddress.Text = m_appConfig.IpAddress;
                txtNum1.Text      = m_appConfig.num1.ToString();
                txtNum2.Text      = m_appConfig.num2.ToString();
                txtPort.Text      = m_appConfig.port.ToString();
                m_appConfig.FrameGrabberMaxTimeout = 10000;
                chkOnFile.Checked   = m_appConfig.logOnFile;
                chkOnScreen.Checked = m_appConfig.logOnScreen;

                SLog.Instance().EnableLog(m_appConfig.logOnFile);
            }
            catch (Exception err)
            {
                throw (new SystemException(err.Message));
            }
        }
        /// <summary>
        /// Find texture by name, if the path is unknown. Warning: It is a slow process and uses a lot of memory.
        /// </summary>
        public static Texture FindTexture(string name)
        {
            Texture result;

            if (loadedTextures.TryGetValue(name, out result))
            {
                return(result); //Already loaded the texture
            }
            else
            {
                //Search in all the textures that been loaded by unity
                Texture[] allTextures = Resources.FindObjectsOfTypeAll <Texture>();
                foreach (Texture tex in allTextures)
                {
                    if (tex.name == name)
                    {
                        loadedTextures.Add(name, tex); //Store the found texture
                        return(tex);
                    }
                }

                loadedTextures.Add(name, null);
                SLog.Error("Could not find texture: " + name);
                return(null);
            }
        }
Esempio n. 6
0
        private static Sisco_Return onPostGameLoaded(ref object sender, ref object[] args, ref object return_value)
        {
            string gameName        = (string)args[0];
            string plyUpgradesFile = String.Concat(gameName, ".pug");

            // LOAD PLAYER UPGRADES
            if (File.Exists(plyUpgradesFile))
            {
                string   str  = File.ReadAllText(plyUpgradesFile);
                string[] list = str.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                if (list.Length <= 0)
                {
                    return(null);
                }

                foreach (string ID in list)
                {
                    string        id      = ID.ToLower();
                    PlayerUpgrade upgrade = Get_Upgrade(Upgrade_Type.PLAYER_UPGRADE, id) as PlayerUpgrade;
                    if (upgrade == null)
                    {
                        Player_Upgrades_Missing.Add(id);
                        SLog.Info("[Upgrades] Unable to find Upgrade, ID: {0}", id);
                    }
                    else
                    {
                        Player.GiveUpgrade(upgrade);
                    }
                }
            }
            return(null);
        }
        public static void Find_Common_Classes_For_Idents(HashSet <Identifiable.Id> ID_LIST)
        {
            Dictionary <string, int> TALLY = new Dictionary <string, int>();

            //Lookup the prefab for each id and grab a list of all classes it has on it

            foreach (Identifiable.Id id in ID_LIST)
            {
                var        pref = Directors.lookupDirector.GetPrefab(id);
                GameObject inst = (GameObject)GameObject.Instantiate(pref, Vector3.zero, Quaternion.identity);

                MonoBehaviour[] class_list = inst.GetComponentsInChildren <MonoBehaviour>(true);
                foreach (var cInst in class_list.DistinctBy(o => o.name))
                {
                    if (!TALLY.ContainsKey(cInst.name))
                    {
                        TALLY.Add(cInst.name, 0);
                    }
                    TALLY[cInst.name]++;
                }

                GameObject.Destroy(inst);
            }

            SLog.Info("==== Results ====");
            foreach (KeyValuePair <string, int> kvp in TALLY.OrderByDescending(o => o.Value))
            {
                float pct = ((float)kvp.Value / ID_LIST.Count);
                SLog.Info("{0}: {1:P1}", kvp.Key, pct);
            }
            SLog.Info("=================");
        }
        /// <summary>
        /// Creates a new network by using a JSON configuration string. This is used to configure the server connection for the signaling channel
        /// and to define webrtc specific configurations such as stun server used to connect through firewalls.
        ///
        ///
        /// </summary>
        /// <param name="config"></param>
        public BrowserWebRtcNetwork(string websocketUrl, IceServer[] lIceServers)
        {
            string conf = ConstructorParamToJson(websocketUrl, lIceServers);

            SLog.L("Creating BrowserWebRtcNetwork config: " + conf, this.GetType().Name);
            mReference = UnityWebRtcNetworkCreate(conf);
        }
Esempio n. 9
0
        public static void Save_Config()
        {
            if (IN_LOADING_PHASE == true)
            {
                return;
            }

            try
            {
                if (plugins == null)
                {
                    SLog.Warn("CRITICAL ERROR: Active plugins list is null!");
                    return;
                }

                // Select the keynames of all non-null, enabled plugins from our dictionary.
                List <string> list = Loader.plugins.Where(kv => (kv.Value != null && kv.Value.Enabled)).Select(kv => kv.Key).ToList();

                Config.Set_Array <string>("ENABLED_PLUGINS", list);
                Config.Save();
            }
            catch (Exception ex)
            {
                SLog.Error(ex);
            }
        }
Esempio n. 10
0
        protected override void OnStart(string[] args)
        {
            SLog.WriteLog("====================================================");

            try
            {
                #region 根据消息发送类型配置启动时钟

                tmMail.Enabled = false;

                if (MsgSentTypes.Contains(type_Mail))
                {
                    tmMail.Enabled = true;
                    tmMail.Start();
                }

                #endregion
            }
            catch (Exception ex)
            {
                SLog.WriteLogWithDefaultTime(string.Format("服务启动失败,详细:{0}", ex.Message));
            }

            SLog.WriteLogWithDefaultTime("服务正常启动。");
        }
Esempio n. 11
0
        public async Task SayMessAsync([Remainder] string mess)
        {
            if (!(await Access("say")))
            {
                return;
            }

            SLog logger = new SLog("Say", Context);

            try
            {
                EmbedBuilder builder = new EmbedBuilder();

                builder.WithAuthor(Context.User.Username, Context.User.GetAvatarUrl())
                .WithFooter(Context.Guild.Name, Context.Guild.IconUrl)
                .WithDescription(mess)
                .WithColor(ConstVariables.UserColor);

                await Context.Channel.SendMessageAsync("", embed : builder.Build());

                logger._addcondition = $" is message '{mess}'";
            }
            catch (Exception e)
            {
                await ReplyAsync("Ошибка во время выполнения! Обратитесь к админестратору!");

                logger._exception = e;
            }

            logger.PrintLog();
        }
Esempio n. 12
0
        protected override void Display()
        {
            Display_BG();// Draw BG
            //GUI.BeginGroup(title_bar_abs_area);
            GUI.BeginGroup(draw_area);
            GUI.BeginGroup(titlebar_area);
            style_title.Draw(title_area, content, false, false, false, false);        // Draw the titlebar text.
            GUI.DrawTextureWithTexCoords(title_stipple_area, title_bar_texture, title_stipple_coords, true);
            GUI.EndGroup();
            GUI.EndGroup();

            //GUI.BeginClip(_inner_area);
            GUI.BeginGroup(_inner_area);

            for (int i = 0; i < children.Count; i++)
            {
                if (CONFIRM_DRAW)
                {
                    SLog.Info("  - Drawing child: {0}", children[i]);
                }
                children[i].TryDisplay();
            }

            GUI.EndGroup();
            //GUI.EndClip();
        }
Esempio n. 13
0
        public async Task PingAsync()
        {
            if (!(await Access("ping")))
            {
                return;
            }

            SLog logger = new SLog("RoleInfo 1", Context);

            try
            {
                var sw  = Stopwatch.StartNew();
                var msg = await Context.Channel.SendMessageAsync("😝").ConfigureAwait(false);

                sw.Stop();

                await msg.DeleteAsync();

                await Context.Channel.SendMessageAsync($"{Context.User.Mention}, пинг составляет: {(int)sw.Elapsed.TotalMilliseconds}ms").ConfigureAwait(false);
            }
            catch (Exception e)
            {
                await ReplyAsync("Ошибка во время выполнения! Обратитесь к админестратору!");

                logger._exception = e;
            }

            logger.PrintLog();
        }
Esempio n. 14
0
        private void Setup_Dict(List <string[]> names_list, out Dictionary <string, GameObject> dict)
        {
            dict = new Dictionary <string, GameObject>();
            foreach (string[] strs in names_list)
            {
                string fullName = strs[0];
                string name     = strs[1];

                var child = base.gameObject.transform.Find(fullName);
                if (child == null)
                {
                    SLog.Info("Unable to find child named: \"{0}\"", fullName);
                    continue;
                }
                GameObject gObj = child.gameObject;

                if (!dict.ContainsKey(name))
                {
                    dict.Add(name, gObj);
                }
                else
                {
                    SLog.Info("Duplicate entry for child named: \"{0}\"", name);
                }
            }
            //PLog.Info("Dictionary<> {0} entrys. {1}", dict.Keys.Count, String.Join(", ", dict.Keys.ToArray()));
        }
Esempio n. 15
0
        public async Task ReportAsync(string command, [Remainder] string text)
        {
            if (!(await Access("report")))
            {
                return;
            }

            SLog logger = new SLog("Report", Context);

            try
            {
                string UMention = Context.User.Username + "#" + Context.User.Discriminator;
                string report   = $"Пользователь: {UMention}\r\nКоманда: {command}\r\nСообщение: {text}";

                await ConstVariables.CServer[Context.Guild.Id].GetGuild().GetUser(ConstVariables.DateBase.OwnerID).SendMessageAsync(report);

                await ReplyAsync($"{Context.User.Mention}, спасибо за ваш отчет! Ваше сообщение очень важно для нас))");
            }
            catch (Exception e)
            {
                await ReplyAsync("Ошибка во время выполнения! Обратитесь к админестратору!");

                logger._exception = e;
            }

            logger.PrintLog();
        }
Esempio n. 16
0
        private void Dev_Spawn_Item(Identifiable.Id ID)
        {
            if (Game.atMainMenu)
            {
                Sound.Play(SoundId.ERROR);
                SLog.Info("Failed to spawn item: {0}, We are at the main menu.", ID);
                return;
            }

            RaycastHit?ray = Player.Raycast();

            if (!ray.HasValue)
            {
                Sound.Play(SoundId.ERROR);
                SLog.Info("Failed to spawn item: {0}, Unable to perform raycast from player's view. Perhaps the ray distance is too far.", ID);
            }

            if (Util.TrySpawn(ID, ray.Value) == null)
            {
                Sound.Play(SoundId.ERROR);
                SLog.Info("Failed to spawn item: {0}, An unknown error occured", ID);
            }
            else
            {
                Sound.Play(SoundId.BTN_CLICK);
            }
        }
Esempio n. 17
0
        //called from native code
        public override StringVector GetVideoDevices()
        {
            StringVector vector = new StringVector();

            try
            {
                foreach (var v in WebCamTexture.devices)
                {
                    if (v.isFrontFacing)
                    {
                        string deviceName = sDevicePrefix + v.name;
                        vector.Add(deviceName);
                    }
                }
                foreach (var v in WebCamTexture.devices)
                {
                    if (v.isFrontFacing == false)
                    {
                        string deviceName = sDevicePrefix + v.name;
                        vector.Add(deviceName);
                    }
                }
                if (sTestDeviceActive)
                {
                    vector.Add(sTestDeviceName);
                }
            }
            catch (Exception e)
            {
                SLog.LogException(e, LOGTAG);
            }
            return(vector);
        }
Esempio n. 18
0
        public BrowserMediaNetwork(NetworkConfig lNetConfig)
        {
            if (lNetConfig.AllowRenegotiation)
            {
                SLog.LW("NetworkConfig.AllowRenegotiation is set to true. This is not supported in the browser version yet! Flag ignored.", this.GetType().Name);
            }
            string signalingUrl = lNetConfig.SignalingUrl;

            IceServer[] iceServers = null;
            if (lNetConfig.IceServers != null)
            {
                iceServers = lNetConfig.IceServers.ToArray();
            }


            //TODO: change this to avoid the use of json

            StringBuilder iceServersJson = new StringBuilder();

            BrowserWebRtcNetwork.IceServersToJson(iceServers, iceServersJson);

            /*
             * Example:
             * {"{IceServers":[{"urls":["turn:because-why-not.com:12779"],"username":"******","credential":"testpassword"},{"urls":["stun:stun.l.google.com:19302"],"username":"","credential":""}], "SignalingUrl":"ws://because-why-not.com:12776/callapp", "IsConference":"False"}
             */

            string conf = "{\"IceServers\":" + iceServersJson.ToString() + ", \"SignalingUrl\":\"" + signalingUrl + "\", \"IsConference\":\"" + false + "\"}";

            SLog.L("Creating BrowserMediaNetwork config: " + conf, this.GetType().Name);
            mReference = UnityMediaNetwork_Create(conf);
        }
Esempio n. 19
0
        public async Task TimeAsync()
        {
            if (!(await Access("time")))
            {
                return;
            }

            SLog logger = new SLog("Time", Context);

            try
            {
                TimeSpan     current_time = DateTime.Now.TimeOfDay;
                EmbedBuilder builder      = new EmbedBuilder();

                builder.WithTitle("Time").WithDescription($"Время на сервере: {current_time.Hours}:{current_time.Minutes}:{current_time.Seconds}")
                .WithAuthor(Context.User.Username, Context.User.GetAvatarUrl())
                .WithThumbnailUrl("https://media.discordapp.net/attachments/462236317926031370/464149984934100992/time.png?width=473&height=473")
                .WithFooter(Context.Guild.Name, Context.Guild.IconUrl)
                .WithColor(ConstVariables.InfoColor);

                await Context.Channel.SendMessageAsync("", embed : builder.Build());
            }
            catch (Exception e)
            {
                await ReplyAsync("Ошибка во время выполнения! Обратитесь к админестратору!");

                logger._exception = e;
            }

            logger.PrintLog();
        }
Esempio n. 20
0
        /// <summary>
        /// Child controls can use this function to query what kind of size constraints the parent will impose on them.
        /// </summary>
        internal virtual Vector2 Constrain_Child_Size(uiControl c, Vector2 requested_size)
        {
            Vector2 max = available_area;// This is the maximum size available to this control

            // We want to determine if the calling control's maximum extents would go outside the maximum possible extents of this control.
            // And if so, scale back the requested size so it fits within our limits.
            if (isSizeConstrained)
            {
                max.x = Get_Content_Area().width;
            }

            if (CONFIRM_SIZE)
            {
                SLog.Info("{0}  Confirm Child Size Constraint  |  Available Area: {1}  |  Requested Size: {2}  ", this, max, requested_size);
            }

            if ((requested_size.x + c.Pos.x) > max.x)
            {
                requested_size.x = (max.x - c.Pos.x);
            }
            if ((requested_size.y + c.Pos.y) > max.y)
            {
                requested_size.y = (max.y - c.Pos.y);
            }

            return(requested_size);
        }
Esempio n. 21
0
        public void Update_Plugins_List()
        {
            set_layout_dirty();
            list.Clear_Children();

            float dY = 3f;

            foreach (KeyValuePair <string, Plugin> kv in Loader.plugins)
            {
                try
                {
                    var sel = Create <Plugin_Manager_List_Item>();
                    sel.Set_Plugin(kv.Value);
                    sel.onClicked += Sel_onClicked;
                    list.Add(kv.Value.Hash, sel);
                }
                catch (Exception ex)
                {
                    SLog.Error(ex);
                }
            }

            if (list.isEmpty)
            {
                tab_need_plugins.Select();              // tabPanel.Set_Tab(NEED_PLUGINS_TAB_NAME);
            }
            else
            {
                tab_ins.Select(); // tabPanel.Set_Tab(INSTRUCTION_TAB_NAME);
            }
            // Set the very first plugin in our list as the active one
            //if (Loader.plugins.Count > 0) { this.Select_Plugin(Loader.plugins.First().Value); }
        }
Esempio n. 22
0
        public static byte[] Load_Resource(string name, string namespace_str = "SR_PluginLoader")
        {
            try
            {
                using (var stream = Get_Resource_Stream(name, namespace_str))
                {
                    if (stream == null)
                    {
                        return(null);
                    }

                    var buf  = new byte[stream.Length];
                    var read = stream.Read(buf, 0, (int)stream.Length);
                    if (read >= (int)stream.Length)
                    {
                        return(buf);
                    }
                    var remain = ((int)stream.Length - read);
                    var r      = 0;
                    while (r < remain && remain > 0)
                    {
                        r       = stream.Read(buf, read, remain);
                        read   += r;
                        remain -= r;
                    }

                    return(buf);
                }
            }
            catch (Exception ex)
            {
                SLog.Error(ex);
                return(null);
            }
        }
        internal static void Setup()
        {
            SLog.Info("[SiscosHooks] Initialized...");
            int max = HOOK_ID.Count;

            // foreach(var hook in HOOKS.HooksList) { max = Math.Max(max, hook.id); }

            EventCounter = new int[max];
            for (int i = 0; i < EventCounter.Length; i++)
            {
                EventCounter[i] = 0;
            }

            #region Setup Event Extension Proxys
            register(HOOK_ID.Ext_Game_Saved, HookProxys.Ext_Game_Saved);
            register(HOOK_ID.Ext_Pre_Game_Loaded, HookProxys.Ext_Pre_Game_Loaded);
            register(HOOK_ID.Ext_Post_Game_Loaded, HookProxys.Ext_Post_Game_Loaded);
            register(HOOK_ID.Ext_Demolish_Plot, HookProxys.Ext_Demolish_Plot_Upgrade);
            register(HOOK_ID.Ext_Spawn_Plot_Upgrades_UI, HookProxys.Ext_Spawn_Plot_Upgrades_UI);
            register(HOOK_ID.Ext_Identifiable_Spawn, HookProxys.Ext_Identifiable_Spawn);
            register(HOOK_ID.Ext_Player_Death, HookProxys.Ext_Player_Death);
            register(HOOK_ID.Ext_LockOnDeath_Start, HookProxys.Ext_LockOnDeath_Start);
            register(HOOK_ID.Ext_LockOnDeath_End, HookProxys.Ext_LockOnDeath_End);
            #endregion

            #region Hook Prefab Instantiation Events
            Util.Inject_Into_Prefabs <Entity_Pref_Hook>(Ident.ALL_IDENTS);
            Util.Inject_Into_Prefabs <Plot_Pref_Hook>(Ident.ALL_PLOTS);
            Util.Inject_Into_Prefabs <Resource_Pref_Hook>(Ident.ALL_GARDEN_PATCHES);
            #endregion
        }
        private static JSONArray Cache_Git_Repo(string repo_url)
        {
            //EXAMPLE:  https://api.github.com/repos/dsisco11/SR_Plugin_Loader/git/trees/master?recursive=1
            string url     = String.Format("{0}/git/trees/master?recursive=1", repo_url.TrimEnd(new char[] { '\\', '/' }));
            string jsonStr = null;

            if (!remote_file_cache.ContainsKey(url))
            {
                // Fetch repo information
                //jsonStr = webClient.DownloadString(url);
                jsonStr = GetString(url);
                if (jsonStr == null || jsonStr.Length <= 0)
                {
                    return(null);
                }

                remote_file_cache.Add(url, ENCODING.GetBytes(jsonStr));
                SLog.Debug("Cached repository: {0}", url);
            }
            else
            {
                jsonStr = ENCODING.GetString(remote_file_cache[url]);
            }

            // Parse the json response from GitHub
            var git  = SimpleJSON.JSON.Parse(jsonStr);
            var tree = git["tree"].AsArray;

            return(tree);
        }
Esempio n. 25
0
        public Dev_SpawnMenu()
        {
            Autosize        = true;
            Autosize_Method = AutosizeMethod.FILL;
            onLayout       += Layout;

            // This list will contain different categories of spawnable items
            cList = uiControl.Create <uiListView>(this);
            cList.Set_Margin(0, 4, 0, 0);
            cList.Set_Width(130f);

            catPanel = uiControl.Create <uiTabPanel>(this);

            foreach (SpawnCategory cty in Enum.GetValues(typeof(SpawnCategory)))
            {
                if (cty == SpawnCategory.NONE)
                {
                    continue;
                }
                string catStr = Enum.GetName(typeof(SpawnCategory), cty);
                var    catBtn = uiControl.Create <uiListItem>(String.Concat("category_", catStr.ToLower()), cList);
                catBtn.Title       = catStr.ToLower().CapitalizeFirst();
                catBtn.Description = null;

                uiTab cTab = null;
                switch (cty)
                {
                case SpawnCategory.SLIMES:
                    cTab = Create_Spawn_Category_Menu(catPanel, cty, Ident.ALL_SLIMES);
                    break;

                case SpawnCategory.PLORTS:
                    cTab = Create_Spawn_Category_Menu(catPanel, cty, Identifiable.PLORT_CLASS);
                    break;

                case SpawnCategory.ANIMALS:
                    cTab = Create_Spawn_Category_Menu(catPanel, cty, Ident.ALL_ANIMALS);
                    break;

                case SpawnCategory.FRUITS:
                    cTab = Create_Spawn_Category_Menu(catPanel, cty, Identifiable.FRUIT_CLASS);
                    break;

                case SpawnCategory.VEGETABLES:
                    cTab = Create_Spawn_Category_Menu(catPanel, cty, Identifiable.VEGGIE_CLASS);
                    break;

                default:
                    SLog.Info("Unhandled Spawn menu category: {0}", catStr);
                    break;
                }

                catBtn.onSelected += (uiControl c) =>
                {
                    Sound.Play(SoundId.BTN_CLICK);
                    cTab.Select();
                };
            }
        }
Esempio n. 26
0
        protected override void Initialize()
        {
            ModeChanged += OnModeChanged;

            SLog.SetLogger(OnLog);

            base.Initialize();
        }
Esempio n. 27
0
        private void Add_Error(Exception ex)
        {
            string str = Logging.Logger.Format_Exception(ex);

            Errors.Add(str);
            SLog.Error("[ <b>{0}</b> ] {1}", dll_name, str);
            onError?.Invoke();
        }
Esempio n. 28
0
        private void Add_Error(string format, params object[] args)
        {
            string str = DebugHud.Format_Log(format, 1, args);

            Errors.Add(str);
            SLog.Info("[ <b>{0}</b> ] {1}", this.dll_name, str);
            onError?.Invoke();
        }
Esempio n. 29
0
        public async Task HelloAsyng(SocketUser user = null)
        {
            if (!(await Access("hello")))
            {
                return;
            }

            SLog logger = new SLog("Hello", Context);

            try
            {
                TimeSpan current_time = DateTime.Now.TimeOfDay;

                int h = current_time.Hours;

                string good = "";

                if (user != null)
                {
                    good = $"{user.Mention}, ";
                }
                else
                {
                    good = $"{Context.Message.Author.Mention}, ";
                }

                if (h < 6)
                {
                    good += "Доброй ночи!";
                }
                else if (h < 12)
                {
                    good += "Доброе утро!";
                }
                else if (h < 18)
                {
                    good += "Добрый день!";
                }
                else if (h < 20)
                {
                    good += "Добрый вечер!";
                }
                else if (h < 24)
                {
                    good += "Доброй ночи!";
                }

                await Context.Channel.SendMessageAsync(good);
            }
            catch (Exception e)
            {
                await ReplyAsync("Ошибка во время выполнения! Обратитесь к админестратору!");

                logger._exception = e;
            }

            logger.PrintLog();
        }
Esempio n. 30
0
        public async Task UserInfoAsync(IGuildUser user = null)
        {
            if (!(await Access("userinfo")))
            {
                return;
            }

            SLog logger = new SLog("UserInfo", Context);

            try
            {
                IGuildUser User = user ?? Context.User as IGuildUser;

                EmbedBuilder builder = new EmbedBuilder();

                builder.AddField("Имя пользователя", User.Username + "#" + User.Discriminator, true);

                if (User.Activity != null)
                {
                    builder.AddField("Activity", User.Activity.Name, true);
                }

                builder.AddField("Дата создания", $"{User.CreatedAt:dd.MM.yyyy HH:mm}", true)
                .AddField("Дата присоединения", User.JoinedAt?.ToString("dd.MM.yyyy HH:mm"), true)
                .AddField("Кол-во ролей", User.RoleIds.Count - 1, true)
                .WithColor(ConstVariables.InfoColor);

                string avatar = User.GetAvatarUrl();

                if (Uri.IsWellFormedUriString(avatar, UriKind.Absolute))
                {
                    builder.WithThumbnailUrl(avatar);
                }

                string role = "";
                int    i    = 1;

                foreach (var key in User.RoleIds)
                {
                    if (!Context.Guild.GetRole(key).IsEveryone)
                    {
                        role += $"{i++}: **{Context.Guild.GetRole(key).Name}** ({Context.Guild.GetRole(key).CreatedAt:dd.MM.yyyy HH:mm})\r\n";
                    }
                }

                builder.AddField("Роли", role);

                await Context.Channel.SendMessageAsync("", embed : builder.Build());
            }
            catch (Exception e)
            {
                await ReplyAsync("Ошибка во время выполнения! Обратитесь к админестратору!");

                logger._exception = e;
            }

            logger.PrintLog();
        }