Exemple #1
0
        public void DrawWinner()
        {
            // Create a random instance with timebased seed
            Random rnd = new Random((int)DateTime.Now.Ticks);

            // Create a copy of the current entry list to work with
            // This also prevents people to enter when rolling is happening
            List <string> workList = new List <string>(entries);

            // Manupilate workList to add subscriber luck

            /*
             *      // Not really needed as the forloop will limit this but to increase performance
             *      // it won't load subscriber list if subluck is set to 1 (off)
             *      if (SubscriberLuck > 1)
             *      {
             *          List<string> subList = new List<string>();
             *
             *          // TODO: Fetch complete subscriber list from Twitch API and add to subList
             *
             *          // Create another list with Intersect restult as it is going to enumerate
             *          // over this while editing workList to prevent modified execeptions.
             *          List<string> crossCheck = new List<string>(workList.Intersect(subList));
             *          foreach (string subEntry in crossCheck)
             *          {
             *              for (int i = 1; i < subscriberLuck; i++)
             *              {
             *                  workList.Insert(rnd.Next(0, workList.Count), subEntry);
             *              }
             *          }
             *      }
             */

            // Roll initial winner and get the Viewer object
            // No need to verify if user exist as it SHOULD exist
            int    index        = rnd.Next(0, workList.Count);
            Viewer rolledViewer = MainWindow.colDatabase.FirstOrDefault(x =>
                                                                        x.UserName == workList[index]);

            // Verify if the winner is eligable, if not remove from
            // the workList and reroll a winner without user interaction
            while (!MeetsRequirements(rolledViewer) || rolledViewer == null)
            {
                try
                {
                    // Remove failed winner from workList
                    workList.RemoveAll(x => x == rolledViewer.UserName);

                    // Reroll winner
                    index        = rnd.Next(0, workList.Count);
                    rolledViewer = MainWindow.colDatabase.FirstOrDefault(x =>
                                                                         x.UserName == workList[index]);
                }
                catch (Exception)
                {
                }
            }

            // We finally have a winner!
            winners.Add(rolledViewer.UserName);
            winner = rolledViewer;

            WinnerChosenEventArgs args = new WinnerChosenEventArgs(rolledViewer, this);

            OnWinnerChosen(args);
        }
        private bool DatabaseFilter(object item)
        {
            Viewer viewer = item as Viewer;

            return(viewer.UserName.Contains(tbFilterOnName.Text));
        }
Exemple #3
0
        public void ExecuteCommand(IrcMessage message)
        {
            // Get command user's Viewer object
            Viewer viewer = MainWindow.colDatabase.FirstOrDefault(x => x.UserName == message.Author);

            if (viewer == null)
            {
                return;
            }

            if (CanExecute(viewer))
            {
                Match  targetMatch = Regex.Match(message.Message, @"@(?<name>[a-zA-Z0-9_]{4,25})");
                string target      = targetMatch.Groups["name"].Value;

                // Parse response line here
                // @user@ -> Display name of the user of the command

                // @followdate@ -> Command user's follow date
                // @followdatetime@ -> Command user's follow date and time

                // @game@ -> Channels current game
                // @title@ -> Channels current title

                string parsedResponse = Regex.Replace(response, @"@(?<item>\w+)@", m =>
                {
                    string[] split = Regex.Split(message.Message, @"\s+");

                    switch (m.Groups["item"].Value.ToLower())
                    {
                    case "user":
                        return(viewer.UserName);

                    case "followdate":
                        return(viewer.GetFollowDateTime("yyyy-MM-dd"));

                    case "followdatetime":
                        return(viewer.GetFollowDateTime("yyyy-MM-dd HH:mm"));

                    case "game":
                        return(Utils.GetClient().GetMyChannel().Game);

                    case "title":
                        return(Utils.GetClient().GetMyChannel().Status);

                    case "var1":
                        if (split.Count() == 2)
                        {
                            var1 = split[1];
                            return(var1);
                        }
                        return("");

                    default:
                        return("");
                    }
                });

                // Set timestamps
                lastUsed = DateTime.UtcNow;
                dictLastUsed[message.Author] = DateTime.UtcNow;

                // Notify the UI of the new last used date
                NotifyPropertyChanged("LastUsed");

                // Send the response
                if (sendAsStreamer)
                {
                    // Send message to IRC, no need to add to collection as this will be received by bot account
                    MainWindow.instance.streamerChatConnection.SendChatMessage(parsedResponse.Trim());
                }
                else
                {
                    // Send message to IRC
                    MainWindow.instance.botChatConnection.SendChatMessage(parsedResponse.Trim());

                    // Add message to collection
                    App.Current.Dispatcher.BeginInvoke(new Action(delegate
                    {
                        MainWindow.colChatMessages.Add(new IrcMessage(
                                                           MainWindow.instance.accountBot.UserName, parsedResponse.Trim()));
                    }));
                }
            }
        }
Exemple #4
0
        public void ExecuteCommandDiscord(Message message)
        {
            Viewer viewer;

            try
            {
                viewer = MainWindow.colDatabase.FirstOrDefault(x => x.DiscordID == message.User.Id.ToString());
                MainWindow.popMsgBox(viewer.UserName);
            }
            catch (Exception)
            {
                viewer = new Viewer(message.User.Name);
            }
            if (viewer == null)
            {
                return;
            }

            if (CanExecute(viewer))
            {
                Match  targetMatch = Regex.Match(message.Text, @"@(?<name>[a-zA-Z0-9_]{4,25})");
                string target      = targetMatch.Groups["name"].Value;

                // Parse response line here
                // @user@ -> Display name of the user of the command

                // @followdate@ -> Command user's follow date
                // @followdatetime@ -> Command user's follow date and time

                // @game@ -> Channels current game
                // @title@ -> Channels current title

                string parsedResponse = Regex.Replace(response, @"@(?<item>\w+)@", m =>
                {
                    string[] split = Regex.Split(message.Text, @"\s+");

                    switch (m.Groups["item"].Value.ToLower())
                    {
                    case "user":
                        return(viewer.UserName);

                    case "followdate":
                        return(viewer.GetFollowDateTime("yyyy-MM-dd"));

                    case "followdatetime":
                        return(viewer.GetFollowDateTime("yyyy-MM-dd HH:mm"));

                    case "game":
                        return(Utils.GetClient().GetMyChannel().Game);

                    case "title":
                        return(Utils.GetClient().GetMyChannel().Status);

                    case "var1":
                        if (split.Count() == 2)
                        {
                            var1 = split[1];
                            return(var1);
                        }
                        return("");

                    default:
                        return("");
                    }
                });

                MainWindow.discord.GetServer(message.Server.Id).GetChannel(message.Channel.Id).SendMessage(parsedResponse.Trim());
            }
        }
        /// <summary>
        /// Import the currency database file created by Ankhbot.
        /// </summary>
        /// <returns>True on success, false otherwise.</returns>
        private bool ImportFromAnkhbot()
        {
            // Create OpenFileDialog and set default file extention and filters
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt       = ".sqlite";
            dlg.Filter           = "AnkhBot CurrencyDB|CurrencyDB.sqlite";
            dlg.InitialDirectory = Environment.GetFolderPath(
                Environment.SpecialFolder.ApplicationData) + "\\AnkhHeart\\AnkhBotR2\\Twitch\\Databases";

            // Show file dialog
            if (dlg.ShowDialog() == true)
            {
                int cntRecords = 0;

                // Set status
                lblStatusText.Content = "Reading Ankhbot Data and Writing to file. This window will close automatically when finished.";

                try
                {
                    // Create and open a new SQLite DB connection from the user selected file
                    SQLiteConnection dbConnection = new SQLiteConnection(string.Format("DataSource={0}; Version=3; Read Only=True;", dlg.FileName));
                    dbConnection.Open();

                    // Execute SQL command
                    SQLiteCommand    sqlCmd     = new SQLiteCommand("SELECT * FROM CurrencyUser", dbConnection);
                    SQLiteDataReader dataReader = sqlCmd.ExecuteReader();

                    // TODO close active chat connections
                    try
                    {
                        MainWindow.instance.DisconnectBot();
                        MainWindow.instance.DisconnectStreamer();
                    }
                    catch (Exception)
                    {
                    }

                    MainWindow.colViewers.Clear();
                    MainWindow.colDatabase.Clear();

                    // Itterate over found rows and insert a new Viewer in colDatabase
                    while (dataReader.Read())
                    {
                        Viewer viewer = new Viewer((string)dataReader["Name"]);

                        viewer.Title  = (string)dataReader["Rank"];
                        viewer.Points = (long)dataReader["Points"];
                        viewer.Raids  = (long)dataReader["Raids"];

                        // .ToUniversalTime() is required to set DateTimeKind to universal and the result
                        // will else be converted to the local machine time which is what we don't want.
                        viewer.LastSeen = DateTime.Parse((string)dataReader["LastSeen"],
                                                         CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime();

                        // AnkhBot's time format is the following [d.]HH:MM:SS
                        // This is the value for timespan.toString(), .Parse() and .TryParse()
                        viewer.Watched = TimeSpan.Parse((string)dataReader["Hours"]);

                        // Add new Viewer to colDatabase
                        MainWindow.colDatabase.Add(viewer);

                        // Counter for parsed records
                        cntRecords++;
                    }

                    dbConnection.Close();
                    dbConnection.Dispose();

                    /*
                     *
                     *                  // Open DBfile
                     *                  dbConnection = new SQLiteConnection(string.Format("Data Source={0}; Version=3", ViewerDB.filename));
                     *                  dbConnection.Open();
                     *
                     *                  // Set status
                     *                  lblStatusText.Content = "Clearing existing database...";
                     *
                     *                  // Purge DBfile
                     *                  sqlCmd = new SQLiteCommand("DELETE FROM `Viewers`", dbConnection);
                     *                  sqlCmd.ExecuteNonQuery();
                     *
                     *                  int cntWriteViewer = 0;
                     *
                     *                  // Insert new Viewer in `Viewers`
                     *                  foreach (Viewer viewer in MainWindow.colDatabase)
                     *                  {
                     *                      // Set status
                     *                      //http://stackoverflow.com/questions/32680826/wpf-mvvm-thread-keep-running-and-show-progress-in-wpf-windows
                     *                      //http://stackoverflow.com/questions/1952201/display-progress-bar-while-doing-some-work-in-c
                     *                      lblStatusText.Content = string.Format("Writing viewer {0} of {1} to file...", cntWriteViewer, cntRecords);
                     *                      pbStatus.Value = cntWriteViewer / cntRecords * 100;
                     *                      cntWriteViewer++;
                     *
                     *                      sqlCmd = new SQLiteCommand(
                     *                          string.Format("INSERT INTO `Viewers` VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}')",
                     *                              viewer.UserName,
                     *                              viewer.Points,
                     *                              viewer.Spent,
                     *                              viewer.Watched.ToString(),
                     *                              viewer.LastSeen.ToString("o"),
                     *                              viewer.Raids,
                     *                              viewer.Title,
                     *                              viewer.regular.ToString(),
                     *                              viewer.IGN),
                     *                          dbConnection);
                     *                      sqlCmd.ExecuteNonQuery();
                     *                  }
                     *
                     *                  // Close DBfile
                     *                  dbConnection.Close();
                     *
                     */

                    // Return success
                    return(true);
                }
                catch (SQLiteException ex)
                {
                    MessageBox.Show(string.Format("Could not open or read the selected sqlite database file.\n\n{0}", ex.ToString()),
                                    "AnkhBot User Data Import", MessageBoxButton.OK, MessageBoxImage.Error);

                    lblStatusText.Content = "Error reading file.";

                    return(false);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("The following program error has occured:\n\n{0}", ex.ToString()),
                                    "AnkhBot User Data Import", MessageBoxButton.OK, MessageBoxImage.Error);

                    lblStatusText.Content = "Unknown error occured.";

                    return(false);
                }
            }

            // User canceled the file selection
            return(false);
        }