@@ -15,6 +15,8 @@ public partial class ReplaceTagsFunctions : IReplaceTagsFunctions
1515 private readonly IPluginGlobals _pluginGlobals ;
1616 private readonly PluginContext _pluginContext ;
1717 private readonly ILogger < CustomCommands > _logger ;
18+
19+ private static readonly Random _random = new Random ( ) ;
1820
1921 public ReplaceTagsFunctions ( IPluginGlobals PluginGlobals , IPluginContext PluginContext ,
2022 ILogger < CustomCommands > Logger )
@@ -79,38 +81,49 @@ public string ReplaceRandomTags(string message)
7981 // Replace all occurrences of the RNDNO tag in the message
8082 var match = ReplaceRandomTagsRegex ( ) . Match ( message ) ;
8183
84+ // Check if the match is successful
85+ if ( ! match . Success )
86+ {
87+ return message ; // Return original message if no match is found
88+ }
89+
8290 // Extract min and max from the regex match groups
8391 string minStr = match . Groups [ 1 ] . Value ;
8492 string maxStr = match . Groups [ 2 ] . Value ;
8593
94+ // Check for empty strings
95+ if ( string . IsNullOrWhiteSpace ( minStr ) || string . IsNullOrWhiteSpace ( maxStr ) )
96+ {
97+ return message ; // Return original message if min or max is empty
98+ }
99+
86100 // Determine if the min and max are integers or floats
87101 bool isMinFloat = float . TryParse ( minStr , out float minFloat ) ;
88102 bool isMaxFloat = float . TryParse ( maxStr , out float maxFloat ) ;
89103
90- var random = new Random ( ) ;
91-
92- if ( isMinFloat || isMaxFloat )
104+ if ( isMinFloat && isMaxFloat )
93105 {
94106 // Generate a random float between min and max (inclusive)
95- float randomFloat = ( float ) ( random . NextDouble ( ) * ( maxFloat - minFloat ) + minFloat ) ;
107+ float randomFloat = ( float ) ( _random . NextDouble ( ) * ( maxFloat - minFloat ) + minFloat ) ;
96108
97109 // Determine the maximum precision from the min and max values
98110 int maxDecimalPlaces = Math . Max ( GetDecimalPlaces ( minStr ) , GetDecimalPlaces ( maxStr ) ) ;
99111
100112 // Use the determined precision to format the float
101113 message = message . Replace ( match . Value , randomFloat . ToString ( $ "F{ maxDecimalPlaces } ") ) ;
102114 }
103- else
115+ else if ( int . TryParse ( minStr , out int min ) && int . TryParse ( maxStr , out int max ) )
104116 {
105- // Parse as integers
106- int min = int . Parse ( minStr ) ;
107- int max = int . Parse ( maxStr ) ;
108-
109- // Generate a random integer between min and max (inclusive)
110- int randomValue = random . Next ( min , max + 1 ) ; // max is exclusive, so add 1
117+ /// Generate a random integer between min and max (inclusive)
118+ int randomValue = _random . Next ( min , max + 1 ) ; // max is exclusive, so add 1
111119 message = message . Replace ( match . Value , randomValue . ToString ( ) ) ;
112120 }
113-
121+ else
122+ {
123+ // If neither min nor max is valid, return the original message
124+ return message ;
125+ }
126+
114127 return message ;
115128 }
116129
0 commit comments