Exemplo n.º 1
0
 /// <summary>
 /// Saves database file
 /// </summary>
 /// <param name="db">Data base object</param>
 /// <param name="path">Path of database(default to current directory and user_database.json</param>
 /// <returns></returns>
 public static bool Save(UserDatabaseType[] db, string path)
 {
     try
     {
         UserDatabaseTypeArray dataAry = new UserDatabaseTypeArray
         {
             db = db
         };
         File.WriteAllText(path, JsonConvert.SerializeObject(dataAry));
     }catch (Exception ex)
     {
         Extra.WriteError(ex.Message);
         return(false);
     }
     return(true);
 }
Exemplo n.º 2
0
 /// <summary>
 /// Loads the database
 /// </summary>
 /// <param name="path">Path of database(default to current directory and user_database.json</param>
 /// <returns></returns>
 public static UserDatabaseType[] Load(string path)
 {
     try
     {
         string savedData = File.ReadAllText(path);
         return(JsonConvert.DeserializeObject <UserDatabaseTypeArray>(savedData).db);
     }
     catch (FileNotFoundException)
     {
         Extra.WriteError("File \"user_database.js\" not found.");
         return(null);
     }
     catch (Exception ex)
     {
         Extra.WriteError(ex.Message);
         return(null);
     }
 }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Usage: dotnet \"Maths Bot.dll\" BOT_TOKEN [-l] [--db Location]");
                Console.WriteLine("Example: dotnet \"Maths Bot.dll\" MY_TOKEN -l --db \"/etc/Bot/myConf.db\"");
                Console.WriteLine("Pass \"-l\" if you are running bot as service.");
                Console.WriteLine("Database location by default is current working directory and the file \"user_database.json\"");
                return;
            }
            Console.WriteLine("Rare Math Calculations Bot By Hirbod Behnam");
            Console.WriteLine("Source at https://github.com/HirbodBehnam/Maths-Bot");
            #region Parse Token and setup bot
            try
            {
                _bot = new TelegramBotClient(args[0]);
            }
            catch (ArgumentException e)
            {
                Extra.WriteError(e.Message);
                return;
            }
            #endregion
            #region Parse Arguments
            bool UseLoop = false;
            for (int i = 1; i < args.Length; i++)
            {
                if (args[i] == "-l")
                {
                    UseLoop = true;
                }
                else if (args[i] == "--db")
                {
                    _dbPath = args[++i];
                }
                else
                {
                    Extra.WriteWarning("Unrecognized argument \"" + args[i] + "\"");
                }
            }
            #endregion
            #region Load database
            if (!System.IO.File.Exists(_dbPath))
            {
                _userDb = new UserDatabaseType[0];
            }
            else
            {
                _userDb = UserDatabaseActions.Load(_dbPath);
                if (_userDb == null)
                {
                    return;
                }
            }
            #endregion
            //Setup bot
            var me = _bot.GetMeAsync().Result;
            Console.Title   = me.Username;
            _bot.OnMessage += BotOnMessageReceived;
            _bot.StartReceiving();
            Console.WriteLine($"[ {DateTime.Now:dd MMMM yyyy HH:mm:ss} ]: Starting @{me.Username} bot.");
            //Run user db manager; It deletes each user that have not accessed database for more than 30 days
            new Task(() =>
            {
                Console.WriteLine($"[ { DateTime.Now:dd MMMM yyyy HH:mm:ss} ]: Started database cleaner daemon.");
                const int oneDay = 1000 * 60 * 60 * 24;
                DateTime now;
                List <UserDatabaseType> users;
                List <int> removedId;
                while (true)
                {
                    now       = DateTime.Now;
                    users     = new List <UserDatabaseType>(_userDb);
                    removedId = new List <int>();
                    for (int i = 0; i < users.Count; i++)
                    {
                        if ((now - _userDb[i].LastUse).TotalDays >= 30)
                        {
                            removedId.Add(users[i].UserId);
                            users.RemoveAt(i);
                        }
                    }
                    if (removedId.Count != 0)
                    {
                        _userDb = users.ToArray();
                        foreach (int i in removedId)
                        {
                            Console.WriteLine($"[ { DateTime.Now:dd MMMM yyyy HH:mm:ss} ]: A user has been removed from database. ID: " + i);
                        }
                    }
                    Thread.Sleep(oneDay);
                }
            }).Start();
            //Save database every 15 mins
            new Task(() =>
            {
                Console.WriteLine($"[ { DateTime.Now:dd MMMM yyyy HH:mm:ss} ]: Started database saver daemon.");
                const int fiftyMin = 1000 * 60 * 15;
                while (true)
                {
                    Thread.Sleep(fiftyMin);
                    if (UserDatabaseActions.Save(_userDb, _dbPath))
                    {
                        Console.WriteLine($"[ { DateTime.Now:dd MMMM yyyy HH:mm:ss} ]: Saved database at " + _dbPath);
                    }
                }
            }).Start();

            /*
             * If you are going to make a service out of this application you may have to pass -l to application
             */
            if (UseLoop)
            {
                Console.WriteLine("Press Ctrl+C to stop application");
                while (true)
                {
                    Thread.Sleep(int.MaxValue);//Stop main thread and wait for Ctrl+C
                }
            }
            else
            {
                Console.WriteLine("Press enter to stop bot.");
                Console.ReadLine();//Wait until user presses enter
            }
            _bot.StopReceiving();
        }