fix: reformat using C# rules

This commit is contained in:
ZavaruKitsu 2022-10-08 19:26:34 +03:00
parent a731e2a8d0
commit 5ab15621a0
180 changed files with 13136 additions and 13081 deletions

View File

@ -10,11 +10,13 @@
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0"/> <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="Microsoft.VisualBasic.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="Microsoft.VisualBasic.Core" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-10.0.6.0" newVersion="10.0.6.0"/> <bindingRedirect oldVersion="0.0.0.0-10.0.6.0" newVersion="10.0.6.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="Microsoft.Win32.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="Microsoft.Win32.Primitives" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -30,19 +32,23 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Collections.Concurrent" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Collections.Concurrent" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Collections.NonGeneric" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Collections.NonGeneric" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Collections.Specialized" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Collections.Specialized" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -50,19 +56,23 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.ComponentModel.EventBasedAsync" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.ComponentModel.EventBasedAsync" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.ComponentModel.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.ComponentModel.Primitives" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.ComponentModel.TypeConverter" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.ComponentModel.TypeConverter" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -74,7 +84,8 @@
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Diagnostics.Contracts" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Diagnostics.Contracts" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -82,31 +93,38 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" /> <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Diagnostics.FileVersionInfo" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Diagnostics.FileVersionInfo" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Diagnostics.Process" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Diagnostics.Process" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Diagnostics.StackTrace" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Diagnostics.StackTrace" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.4.0" newVersion="4.0.4.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.4.0" newVersion="4.0.4.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Diagnostics.TextWriterTraceListener" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Diagnostics.TextWriterTraceListener" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Diagnostics.TraceSource" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Diagnostics.TraceSource" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Diagnostics.Tracing" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Diagnostics.Tracing" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -118,7 +136,8 @@
<bindingRedirect oldVersion="0.0.0.0-4.1.3.0" newVersion="4.1.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.3.0" newVersion="4.1.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.IO.Compression.ZipFile" publicKeyToken="b77a5c561934e089" culture="neutral" /> <assemblyIdentity name="System.IO.Compression.ZipFile" publicKeyToken="b77a5c561934e089"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -126,11 +145,13 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.IO.FileSystem.DriveInfo" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.IO.FileSystem.DriveInfo" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.IO.FileSystem.Watcher" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.IO.FileSystem.Watcher" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -138,7 +159,8 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.IO.MemoryMappedFiles" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.IO.MemoryMappedFiles" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -174,7 +196,8 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Net.NetworkInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Net.NetworkInformation" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -202,7 +225,8 @@
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Net.WebHeaderCollection" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Net.WebHeaderCollection" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -210,7 +234,8 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Net.WebSockets.Client" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Net.WebSockets.Client" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -222,15 +247,18 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Reflection.Emit.ILGeneration" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Reflection.Emit.ILGeneration" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Reflection.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Reflection.Primitives" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Resources.ResourceManager" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Resources.ResourceManager" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -242,7 +270,8 @@
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.VisualC" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Runtime.CompilerServices.VisualC" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -250,11 +279,13 @@
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Runtime.InteropServices" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Runtime.InteropServices" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation"
publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -262,23 +293,28 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Runtime.Serialization.Formatters" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Runtime.Serialization.Formatters" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Runtime.Serialization.Json" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Runtime.Serialization.Json" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Runtime.Serialization.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Runtime.Serialization.Primitives" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.3.0" newVersion="4.1.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.3.0" newVersion="4.1.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Runtime.Serialization.Xml" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Runtime.Serialization.Xml" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.3.0" newVersion="4.1.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.3.0" newVersion="4.1.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Security.AccessControl" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Security.AccessControl" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/> <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -286,23 +322,28 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Security.Cryptography.Algorithms" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Security.Cryptography.Algorithms" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.2.2.0" newVersion="4.2.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.2.2.0" newVersion="4.2.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Security.Cryptography.Csp" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Security.Cryptography.Csp" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Security.Cryptography.Encoding" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Security.Cryptography.Encoding" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Security.Cryptography.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Security.Cryptography.Primitives" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Security.Cryptography.X509Certificates" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Security.Cryptography.X509Certificates" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -310,11 +351,13 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Security.Principal.Windows" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Security.Principal.Windows" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/> <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Text.Encoding.Extensions" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Text.Encoding.Extensions" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -326,7 +369,8 @@
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Text.RegularExpressions" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Text.RegularExpressions" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.1.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.1.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -334,11 +378,13 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.11.0" newVersion="4.0.11.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Threading.Overlapped" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Threading.Overlapped" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Parallel" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Threading.Tasks.Parallel" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -346,7 +392,8 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Threading.ThreadPool" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Threading.ThreadPool" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.12.0" newVersion="4.0.12.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.12.0" newVersion="4.0.12.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
@ -370,7 +417,8 @@
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly> </dependentAssembly>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity name="System.Xml.XPath.XDocument" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Xml.XPath.XDocument" publicKeyToken="b03f5f7f11d50a3a"
culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/> <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"/>
</dependentAssembly> </dependentAssembly>
</assemblyBinding> </assemblyBinding>

View File

@ -33,17 +33,17 @@ namespace AsyncFormUpdates
private static async void Timer_Elapsed(object sender, ElapsedEventArgs e) private static async void Timer_Elapsed(object sender, ElapsedEventArgs e)
{ {
foreach (var s in __bot.Sessions.SessionList) foreach (var s in __bot.Sessions.SessionList)
{ {
//Only for AsyncUpdateForm //Only for AsyncUpdateForm
if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) && s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit)) if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) &&
s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit))
{
continue; continue;
}
await __bot.InvokeMessageLoop(s.Key); await __bot.InvokeMessageLoop(s.Key);
} }
} }
} }
} }

View File

@ -46,8 +46,6 @@ namespace AsyncFormUpdates.forms
var m = await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); var m = await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true);
_messageId = m.MessageId; _messageId = m.MessageId;
} }
}
}
} }
} }

View File

@ -38,7 +38,5 @@ namespace AsyncFormUpdates.forms
await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true);
} }
} }
} }

View File

@ -6,8 +6,6 @@ namespace AsyncFormUpdates.forms
{ {
public class Start : AutoCleanForm public class Start : AutoCleanForm
{ {
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
await message.ConfirmAction(); await message.ConfirmAction();
@ -30,7 +28,6 @@ namespace AsyncFormUpdates.forms
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
@ -43,6 +40,5 @@ namespace AsyncFormUpdates.forms
await Device.Send("Choose your option", bf); await Device.Send("Choose your option", bf);
} }
} }
} }

View File

@ -10,7 +10,8 @@ var serviceCollection = new ServiceCollection()
var serviceProvider = serviceCollection.BuildServiceProvider(); var serviceProvider = serviceCollection.BuildServiceProvider();
var bot = BotBaseBuilder.Create() var bot = BotBaseBuilder.Create()
.WithAPIKey(Environment.GetEnvironmentVariable("API_KEY") ?? throw new Exception("API_KEY is not set")) .WithAPIKey(Environment.GetEnvironmentVariable("API_KEY") ??
throw new Exception("API_KEY is not set"))
.DefaultMessageLoop() .DefaultMessageLoop()
.WithServiceProvider<StartForm>(serviceProvider) .WithServiceProvider<StartForm>(serviceProvider)
.NoProxy() .NoProxy()

View File

@ -2,13 +2,12 @@
using JoinHiderBot.forms; using JoinHiderBot.forms;
using TelegramBotBase.Builder; using TelegramBotBase.Builder;
namespace JoinHiderBot namespace JoinHiderBot;
{
internal class Program internal class Program
{ {
private static void Main(string[] args) private static void Main(string[] args)
{ {
var apiKey = ""; var apiKey = "";
var bot = BotBaseBuilder.Create() var bot = BotBaseBuilder.Create()
@ -20,4 +19,3 @@ namespace JoinHiderBot
Console.ReadLine(); Console.ReadLine();
} }
} }
}

View File

@ -3,21 +3,20 @@ using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace JoinHiderBot.forms namespace JoinHiderBot.forms;
{
public class GroupManageForm : GroupForm public class GroupManageForm : GroupForm
{ {
public override async Task OnMemberChanges(MemberChangeEventArgs e) public override async Task OnMemberChanges(MemberChangeEventArgs e)
{ {
if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft) if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft)
{
return; return;
}
var m = e.Result.Message; var m = e.Result.Message;
await Device.DeleteMessage(m); await Device.DeleteMessage(m);
} }
}
} }

View File

@ -2,8 +2,8 @@
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace JoinHiderBot.forms namespace JoinHiderBot.forms;
{
public class Start : SplitterForm public class Start : SplitterForm
{ {
public override async Task<bool> Open(MessageResult e) public override async Task<bool> Open(MessageResult e)
@ -21,6 +21,4 @@ namespace JoinHiderBot.forms
return true; return true;
} }
}
} }

View File

@ -3,8 +3,8 @@ using SystemCommandsBot.config;
using SystemCommandsBot.forms; using SystemCommandsBot.forms;
using TelegramBotBase.Builder; using TelegramBotBase.Builder;
namespace SystemCommandsBot namespace SystemCommandsBot;
{
internal class Program internal class Program
{ {
public static Config BotConfig { get; set; } public static Config BotConfig { get; set; }
@ -12,7 +12,6 @@ namespace SystemCommandsBot
private static void Main(string[] args) private static void Main(string[] args)
{ {
BotConfig = Config.Load(); BotConfig = Config.Load();
if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "") if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "")
@ -34,8 +33,5 @@ namespace SystemCommandsBot
bot.Stop(); bot.Stop();
}
} }
} }

View File

@ -1,5 +1,5 @@
namespace SystemCommandsBot.commands namespace SystemCommandsBot.commands;
{
public class Commando public class Commando
{ {
public int Id { get; set; } public int Id { get; set; }
@ -17,9 +17,5 @@
public int? MaxInstances { get; set; } public int? MaxInstances { get; set; }
public string ProcName public string ProcName { get; set; }
{
get;set;
}
}
} }

View File

@ -4,26 +4,28 @@ using System.IO;
using Newtonsoft.Json; using Newtonsoft.Json;
using SystemCommandsBot.commands; using SystemCommandsBot.commands;
namespace SystemCommandsBot.config namespace SystemCommandsBot.config;
{
public class Config public class Config
{ {
public Config()
{
Commandos = new List<Commando>();
}
public string Password { get; set; } public string Password { get; set; }
public string ApiKey { get; set; } public string ApiKey { get; set; }
public List<Commando> Commandos { get; set; } public List<Commando> Commandos { get; set; }
public Config()
{
Commandos = new List<Commando>();
}
public void LoadDefaultValues() public void LoadDefaultValues()
{ {
ApiKey = ""; ApiKey = "";
Commandos.Add(new Commando { Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 }); Commandos.Add(new Commando
{
Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2
});
} }
@ -32,13 +34,12 @@ namespace SystemCommandsBot.config
try try
{ {
return Load(AppContext.BaseDirectory + "config\\default.cfg"); return Load(AppContext.BaseDirectory + "config\\default.cfg");
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex.Message); Console.WriteLine(ex.Message);
} }
return null; return null;
} }
@ -75,6 +76,7 @@ namespace SystemCommandsBot.config
{ {
Console.WriteLine(ex.Message); Console.WriteLine(ex.Message);
} }
return null; return null;
} }
@ -86,8 +88,6 @@ namespace SystemCommandsBot.config
} }
catch catch
{ {
}
} }
} }
} }

View File

@ -6,8 +6,8 @@ using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace SystemCommandsBot.forms namespace SystemCommandsBot.forms;
{
public class CmdForm : AutoCleanForm public class CmdForm : AutoCleanForm
{ {
public DateTime ExpiresAt { get; set; } public DateTime ExpiresAt { get; set; }
@ -27,7 +27,6 @@ namespace SystemCommandsBot.forms
if (!int.TryParse(btn, out id)) if (!int.TryParse(btn, out id))
{ {
return; return;
} }
@ -48,7 +47,6 @@ namespace SystemCommandsBot.forms
if (cmd.MaxInstances != null && cmd.MaxInstances >= 0) if (cmd.MaxInstances != null && cmd.MaxInstances >= 0)
{ {
if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances) if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances)
{ {
await Device.Send("Anwendung läuft bereits."); await Device.Send("Anwendung läuft bereits.");
@ -56,7 +54,6 @@ namespace SystemCommandsBot.forms
return; return;
} }
} }
var psi = new ProcessStartInfo var psi = new ProcessStartInfo
@ -90,7 +87,6 @@ namespace SystemCommandsBot.forms
} }
catch catch
{ {
} }
} }
@ -116,7 +112,6 @@ namespace SystemCommandsBot.forms
} }
catch catch
{ {
} }
} }
@ -143,30 +138,19 @@ namespace SystemCommandsBot.forms
await message.ConfirmAction(); await message.ConfirmAction();
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (MessageId == null) if (MessageId == null)
{ {
var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled).Select(a => new ButtonBase(a.Title, a.Id.ToString())); var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled)
.Select(a => new ButtonBase(a.Title, a.Id.ToString()));
var bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddSplitted(buttons, 1); bf.AddSplitted(buttons, 1);
await Device.Send("Deine Optionen", bf); await Device.Send("Deine Optionen", bf);
} }
}
} }
} }

View File

@ -3,8 +3,8 @@ using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace SystemCommandsBot.forms namespace SystemCommandsBot.forms;
{
public class StartForm : FormBase public class StartForm : FormBase
{ {
public string Password { get; set; } public string Password { get; set; }
@ -34,8 +34,5 @@ namespace SystemCommandsBot.forms
cmd.ExpiresAt = DateTime.Now.AddDays(14); cmd.ExpiresAt = DateTime.Now.AddDays(14);
await NavigateTo(cmd); await NavigateTo(cmd);
}
} }
} }

View File

@ -28,13 +28,15 @@ namespace TelegramBotBase.Extensions.Images
/// <param name="replyTo"></param> /// <param name="replyTo"></param>
/// <param name="disableNotification"></param> /// <param name="disableNotification"></param>
/// <returns></returns> /// <returns></returns>
public static async Task<Message> SendPhoto(this DeviceSession session, Image image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) public static async Task<Message> SendPhoto(this DeviceSession session, Image image, string name,
string caption, ButtonForm buttons = null, int replyTo = 0,
bool disableNotification = false)
{ {
using (var fileStream = ToStream(image, ImageFormat.Png)) using (var fileStream = ToStream(image, ImageFormat.Png))
{ {
var fts = new InputOnlineFile(fileStream, name); var fts = new InputOnlineFile(fileStream, name);
return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification); return await session.SendPhoto(fts, caption, buttons, replyTo, disableNotification);
} }
} }
@ -47,13 +49,15 @@ namespace TelegramBotBase.Extensions.Images
/// <param name="replyTo"></param> /// <param name="replyTo"></param>
/// <param name="disableNotification"></param> /// <param name="disableNotification"></param>
/// <returns></returns> /// <returns></returns>
public static async Task<Message> SendPhoto(this DeviceSession session, Bitmap image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) public static async Task<Message> SendPhoto(this DeviceSession session, Bitmap image, string name,
string caption, ButtonForm buttons = null, int replyTo = 0,
bool disableNotification = false)
{ {
using (var fileStream = ToStream(image, ImageFormat.Png)) using (var fileStream = ToStream(image, ImageFormat.Png))
{ {
var fts = new InputOnlineFile(fileStream, name); var fts = new InputOnlineFile(fileStream, name);
return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification); return await session.SendPhoto(fts, caption, buttons, replyTo, disableNotification);
} }
} }
} }

View File

@ -3,6 +3,5 @@
[![NuGet version (TelegramBotBase)](https://img.shields.io/nuget/v/TelegramBotBase.Extensions.Images.svg?style=flat-square)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images/) [![NuGet version (TelegramBotBase)](https://img.shields.io/nuget/v/TelegramBotBase.Extensions.Images.svg?style=flat-square)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images/)
[![Telegram chat](https://img.shields.io/badge/Support_Chat-Telegram-blue.svg?style=flat-square)](https://www.t.me/tgbotbase) [![Telegram chat](https://img.shields.io/badge/Support_Chat-Telegram-blue.svg?style=flat-square)](https://www.t.me/tgbotbase)
[![License](https://img.shields.io/github/license/MajMcCloud/telegrambotframework.svg?style=flat-square&maxAge=2592000&label=License)](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md) [![License](https://img.shields.io/github/license/MajMcCloud/telegrambotframework.svg?style=flat-square&maxAge=2592000&label=License)](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md)
[![Package Downloads](https://img.shields.io/nuget/dt/TelegramBotBase.Extensions.Images.svg?style=flat-square&label=Package%20Downloads)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images) [![Package Downloads](https://img.shields.io/nuget/dt/TelegramBotBase.Extensions.Images.svg?style=flat-square&label=Package%20Downloads)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images)

View File

@ -6,7 +6,6 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
{ {
public static class BotBaseBuilderExtensions public static class BotBaseBuilderExtensions
{ {
/// <summary> /// <summary>
/// Uses an Microsoft SQL Server Database to save and restore sessions. /// Uses an Microsoft SQL Server Database to save and restore sessions.
/// </summary> /// </summary>
@ -15,7 +14,9 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
/// <param name="tablePrefix"></param> /// <param name="tablePrefix"></param>
/// <param name="fallbackForm"></param> /// <param name="fallbackForm"></param>
/// <returns></returns> /// <returns></returns>
public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string connectionString, Type fallbackForm = null, string tablePrefix = "tgb_") public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder,
string connectionString, Type fallbackForm = null,
string tablePrefix = "tgb_")
{ {
var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm);
@ -36,9 +37,12 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
/// <param name="tablePrefix"></param> /// <param name="tablePrefix"></param>
/// <param name="fallbackForm"></param> /// <param name="fallbackForm"></param>
/// <returns></returns> /// <returns></returns>
public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, string userId, string password, Type fallbackForm = null, string tablePrefix = "tgb_") public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP,
string databaseName, string userId, string password,
Type fallbackForm = null, string tablePrefix = "tgb_")
{ {
var connectionString = $"Server={hostOrIP}; Database={databaseName}; User Id={userId}; Password={password}; TrustServerCertificate=true;"; var connectionString =
$"Server={hostOrIP}; Database={databaseName}; User Id={userId}; Password={password}; TrustServerCertificate=true;";
var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm);
@ -56,12 +60,17 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
/// <param name="tablePrefix"></param> /// <param name="tablePrefix"></param>
/// <param name="fallbackForm"></param> /// <param name="fallbackForm"></param>
/// <returns></returns> /// <returns></returns>
public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, bool integratedSecurity = true, Type fallbackForm = null, string tablePrefix = "tgb_") public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP,
string databaseName, bool integratedSecurity = true,
Type fallbackForm = null, string tablePrefix = "tgb_")
{ {
if (!integratedSecurity) if (!integratedSecurity)
{
throw new ArgumentOutOfRangeException(); throw new ArgumentOutOfRangeException();
}
var connectionString = $"Server={hostOrIP}; Database={databaseName}; Integrated Security=true; TrustServerCertificate=true;"; var connectionString =
$"Server={hostOrIP}; Database={databaseName}; Integrated Security=true; TrustServerCertificate=true;";
var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm);

View File

@ -11,19 +11,19 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
{ {
public class MssqlSerializer : IStateMachine public class MssqlSerializer : IStateMachine
{ {
public Type FallbackStateForm { get; set; }
public string ConnectionString { get; }
public string TablePrefix { get; set; }
/// <summary> /// <summary>
/// Will initialize the state machine. /// Will initialize the state machine.
/// </summary> /// </summary>
/// <param name="file">Path of the file and name where to save the session details.</param> /// <param name="file">Path of the file and name where to save the session details.</param>
/// <param name="fallbackStateForm">Type of Form which will be saved instead of Form which has <seealso cref="Attributes.IgnoreState"/> attribute declared. Needs to be subclass of <seealso cref="Form.FormBase"/>.</param> /// <param name="fallbackStateForm">
/// Type of Form which will be saved instead of Form which has
/// <seealso cref="Attributes.IgnoreState" /> attribute declared. Needs to be subclass of
/// <seealso cref="Form.FormBase" />.
/// </param>
/// <param name="overwrite">Declares of the file could be overwritten.</param> /// <param name="overwrite">Declares of the file could be overwritten.</param>
public MssqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null) public MssqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null)
{ {
this.ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
TablePrefix = tablePrefix; TablePrefix = tablePrefix;
@ -35,6 +35,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
} }
} }
public string ConnectionString { get; }
public string TablePrefix { get; set; }
public Type FallbackStateForm { get; set; }
public StateContainer LoadFormStates() public StateContainer LoadFormStates()
{ {
var sc = new StateContainer(); var sc = new StateContainer();
@ -44,7 +48,8 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
connection.Open(); connection.Open();
var command = connection.CreateCommand(); var command = connection.CreateCommand();
command.CommandText = "SELECT deviceId, deviceTitle, FormUri, QualifiedName FROM " + TablePrefix + "devices_sessions"; command.CommandText = "SELECT deviceId, deviceTitle, FormUri, QualifiedName FROM " + TablePrefix +
"devices_sessions";
var dataTable = new DataTable(); var dataTable = new DataTable();
using (var dataAdapter = new SqlDataAdapter(command)) using (var dataAdapter = new SqlDataAdapter(command))
@ -73,7 +78,8 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
} }
var command2 = connection.CreateCommand(); var command2 = connection.CreateCommand();
command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId"; command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix +
"devices_sessions_data WHERE deviceId = @deviceId";
command2.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"])); command2.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"]));
var dataTable2 = new DataTable(); var dataTable2 = new DataTable();
@ -91,13 +97,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
se.Values.Add(key, value); se.Values.Add(key, value);
} }
} }
} }
} }
connection.Close(); connection.Close();
} }
@ -127,13 +130,15 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
var sessionCommand = connection.CreateCommand(); var sessionCommand = connection.CreateCommand();
var dataCommand = connection.CreateCommand(); var dataCommand = connection.CreateCommand();
sessionCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)"; sessionCommand.CommandText = "INSERT INTO " + TablePrefix +
"devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)";
sessionCommand.Parameters.Add(new SqlParameter("@deviceId", "")); sessionCommand.Parameters.Add(new SqlParameter("@deviceId", ""));
sessionCommand.Parameters.Add(new SqlParameter("@deviceTitle", "")); sessionCommand.Parameters.Add(new SqlParameter("@deviceTitle", ""));
sessionCommand.Parameters.Add(new SqlParameter("@FormUri", "")); sessionCommand.Parameters.Add(new SqlParameter("@FormUri", ""));
sessionCommand.Parameters.Add(new SqlParameter("@QualifiedName", "")); sessionCommand.Parameters.Add(new SqlParameter("@QualifiedName", ""));
dataCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)"; dataCommand.CommandText = "INSERT INTO " + TablePrefix +
"devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)";
dataCommand.Parameters.Add(new SqlParameter("@deviceId", "")); dataCommand.Parameters.Add(new SqlParameter("@deviceId", ""));
dataCommand.Parameters.Add(new SqlParameter("@key", "")); dataCommand.Parameters.Add(new SqlParameter("@key", ""));
dataCommand.Parameters.Add(new SqlParameter("@value", "")); dataCommand.Parameters.Add(new SqlParameter("@value", ""));
@ -169,13 +174,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
dataCommand.ExecuteNonQuery(); dataCommand.ExecuteNonQuery();
} }
} }
connection.Close(); connection.Close();
} }
} }
} }
} }

View File

@ -3,7 +3,6 @@
[![NuGet version (TelegramBotBase)](https://img.shields.io/nuget/v/TelegramBotBase.Extensions.Serializer.Database.MSSQL.svg?style=flat-square)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL/) [![NuGet version (TelegramBotBase)](https://img.shields.io/nuget/v/TelegramBotBase.Extensions.Serializer.Database.MSSQL.svg?style=flat-square)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL/)
[![Telegram chat](https://img.shields.io/badge/Support_Chat-Telegram-blue.svg?style=flat-square)](https://www.t.me/tgbotbase) [![Telegram chat](https://img.shields.io/badge/Support_Chat-Telegram-blue.svg?style=flat-square)](https://www.t.me/tgbotbase)
[![License](https://img.shields.io/github/license/MajMcCloud/telegrambotframework.svg?style=flat-square&maxAge=2592000&label=License)](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md) [![License](https://img.shields.io/github/license/MajMcCloud/telegrambotframework.svg?style=flat-square&maxAge=2592000&label=License)](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md)
[![Package Downloads](https://img.shields.io/nuget/dt/TelegramBotBase.Extensions.Serializer.Database.MSSQL.svg?style=flat-square&label=Package%20Downloads)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL) [![Package Downloads](https://img.shields.io/nuget/dt/TelegramBotBase.Extensions.Serializer.Database.MSSQL.svg?style=flat-square&label=Package%20Downloads)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL)

View File

@ -1,37 +1,81 @@
USE [telegram_bot] USE
[telegram_bot]
GO GO
/****** Object: Table [dbo].[tgb_devices_sessions] Script Date: 30.06.2022 16:22:09 ******/ /****** Object: Table [dbo].[tgb_devices_sessions] Script Date: 30.06.2022 16:22:09 ******/
SET ANSI_NULLS ON SET ANSI_NULLS ON
GO GO
SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER ON
GO GO
CREATE TABLE [dbo].[tgb_devices_sessions]( CREATE TABLE [dbo].[tgb_devices_sessions]
[deviceId] [bigint] NOT NULL, (
[deviceTitle] [nvarchar](512) NOT NULL, [
[FormUri] [nvarchar](512) NOT NULL, deviceId] [
[QualifiedName] [nvarchar](512) NOT NULL, bigint]
NOT
NULL, [
deviceTitle] [
nvarchar]
(
512
) NOT NULL,
[FormUri] [nvarchar]
(
512
) NOT NULL,
[QualifiedName] [nvarchar]
(
512
) NOT NULL,
CONSTRAINT [PK_tgb_devices_sessions_1] PRIMARY KEY CLUSTERED CONSTRAINT [PK_tgb_devices_sessions_1] PRIMARY KEY CLUSTERED
( (
[deviceId] ASC [
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] deviceId] ASC
) ON [PRIMARY] )
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF)
ON [PRIMARY]
)
ON [PRIMARY]
GO GO
/****** Object: Table [dbo].[tgb_devices_sessions_data] Script Date: 30.06.2022 16:22:09 ******/ /****** Object: Table [dbo].[tgb_devices_sessions_data] Script Date: 30.06.2022 16:22:09 ******/
SET ANSI_NULLS ON SET ANSI_NULLS
ON
GO GO
SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER
ON
GO GO
CREATE TABLE [dbo].[tgb_devices_sessions_data]( CREATE TABLE [dbo].[tgb_devices_sessions_data]
[Id] [uniqueidentifier] NOT NULL, (
[deviceId] [bigint] NOT NULL, [
[key] [nvarchar](512) NOT NULL, Id] [
[value] [nvarchar](max) NOT NULL, uniqueidentifier]
[type] [nvarchar](512) NOT NULL, NOT
NULL, [
deviceId] [
bigint]
NOT
NULL, [
key] [
nvarchar]
(
512
) NOT NULL,
[value] [nvarchar]
(
max
) NOT NULL,
[type] [nvarchar]
(
512
) NOT NULL,
CONSTRAINT [PK_tgb_devices_session_data] PRIMARY KEY CLUSTERED CONSTRAINT [PK_tgb_devices_session_data] PRIMARY KEY CLUSTERED
( (
[Id] ASC [
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] Id] ASC
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] )
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF)
ON [PRIMARY]
)
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO GO
ALTER TABLE [dbo].[tgb_devices_sessions_data] ADD CONSTRAINT [DF_tgb_devices_session_data_Id] DEFAULT (newid()) FOR [Id] ALTER TABLE [dbo].[tgb_devices_sessions_data] ADD CONSTRAINT [DF_tgb_devices_session_data_Id] DEFAULT (newid()) FOR [Id]
GO GO

View File

@ -7,13 +7,12 @@ using TelegramBotBase.Commands;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBaseTest.Tests; using TelegramBotBaseTest.Tests;
namespace TelegramBotBaseTest namespace TelegramBotBaseTest;
{
internal class Program internal class Program
{ {
private static void Main(string[] args) private static void Main(string[] args)
{ {
var apiKey = ""; var apiKey = "";
var bb = BotBaseBuilder var bb = BotBaseBuilder
@ -59,7 +58,6 @@ namespace TelegramBotBaseTest
Console.ReadLine(); Console.ReadLine();
bb.Stop(); bb.Stop();
} }
private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en) private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en)
@ -112,4 +110,3 @@ namespace TelegramBotBaseTest
} }
} }
} }
}

View File

@ -3,6 +3,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp3.1;net5;net6</TargetFrameworks> <TargetFrameworks>netcoreapp3.1;net5;net6</TargetFrameworks>
<LangVersion>10</LangVersion>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo> <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<Configurations>Debug;Release</Configurations> <Configurations>Debug;Release</Configurations>
</PropertyGroup> </PropertyGroup>

View File

@ -3,11 +3,10 @@ using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests;
{
public class ButtonTestForm : AutoCleanForm public class ButtonTestForm : AutoCleanForm
{ {
public ButtonTestForm() public ButtonTestForm()
{ {
Opened += ButtonTestForm_Opened; Opened += ButtonTestForm_Opened;
@ -20,14 +19,15 @@ namespace TelegramBotBaseTest.Tests
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
var call = message.GetData<CallbackData>(); var call = message.GetData<CallbackData>();
await message.ConfirmAction(); await message.ConfirmAction();
if (call == null) if (call == null)
{
return; return;
}
message.Handled = true; message.Handled = true;
@ -71,29 +71,24 @@ namespace TelegramBotBaseTest.Tests
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
var btn = new ButtonForm(); var btn = new ButtonForm();
btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()), new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize())); btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()),
new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize()));
btn.AddButtonRow(new ButtonBase("Button 3", new CallbackData("a", "button3").Serialize()), new ButtonBase("Button 4", new CallbackData("a", "button4").Serialize())); btn.AddButtonRow(new ButtonBase("Button 3", new CallbackData("a", "button3").Serialize()),
new ButtonBase("Button 4", new CallbackData("a", "button4").Serialize()));
btn.AddButtonRow(new ButtonBase("Google.com", "google", "https://www.google.com"), new ButtonBase("Telegram", "telegram", "https://telegram.org/")); btn.AddButtonRow(new ButtonBase("Google.com", "google", "https://www.google.com"),
new ButtonBase("Telegram", "telegram", "https://telegram.org/"));
btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize()));
await Device.Send("Click a button", btn); await Device.Send("Click a button", btn);
} }
} }
}

View File

@ -4,8 +4,8 @@ using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls;
{
public class ButtonGridForm : AutoCleanForm public class ButtonGridForm : AutoCleanForm
{ {
private ButtonGrid _mButtons; private ButtonGrid _mButtons;
@ -43,7 +43,9 @@ namespace TelegramBotBaseTest.Tests.Controls
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
{ {
if (e.Button == null) if (e.Button == null)
{
return; return;
}
if (e.Button.Value == "back") if (e.Button.Value == "back")
{ {
@ -61,11 +63,7 @@ namespace TelegramBotBaseTest.Tests.Controls
} }
else else
{ {
await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
} }
}
} }
} }

View File

@ -6,8 +6,8 @@ using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls;
{
public class ButtonGridPagingForm : AutoCleanForm public class ButtonGridPagingForm : AutoCleanForm
{ {
private ButtonGrid _mButtons; private ButtonGrid _mButtons;
@ -26,7 +26,7 @@ namespace TelegramBotBaseTest.Tests.Controls
KeyboardType = EKeyboardType.ReplyKeyboard, KeyboardType = EKeyboardType.ReplyKeyboard,
EnablePaging = true, EnablePaging = true,
EnableSearch = true, EnableSearch = true,
HeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase("Back", "back") } HeadLayoutButtonRow = new List<ButtonBase> { new("Back", "back") }
}; };
var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
@ -49,7 +49,9 @@ namespace TelegramBotBaseTest.Tests.Controls
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
{ {
if (e.Button == null) if (e.Button == null)
{
return; return;
}
if (e.Button.Value == "back") if (e.Button.Value == "back")
{ {
@ -58,11 +60,7 @@ namespace TelegramBotBaseTest.Tests.Controls
} }
else else
{ {
await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
} }
}
} }
} }

View File

@ -8,8 +8,8 @@ using TelegramBotBase.DataSources;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls;
{
public class ButtonGridTagForm : AutoCleanForm public class ButtonGridTagForm : AutoCleanForm
{ {
private TaggedButtonGrid _mButtons; private TaggedButtonGrid _mButtons;
@ -27,7 +27,7 @@ namespace TelegramBotBaseTest.Tests.Controls
{ {
KeyboardType = EKeyboardType.ReplyKeyboard, KeyboardType = EKeyboardType.ReplyKeyboard,
EnablePaging = true, EnablePaging = true,
HeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase("Back", "back") } HeadLayoutButtonRow = new List<ButtonBase> { new("Back", "back") }
}; };
@ -56,20 +56,19 @@ namespace TelegramBotBaseTest.Tests.Controls
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
{ {
if (e.Button == null) if (e.Button == null)
{
return; return;
}
switch (e.Button.Value) switch (e.Button.Value)
{ {
case "back": case "back":
var start = new Menu(); var start = new Menu();
await NavigateTo(start); await NavigateTo(start);
return; return;
} }
await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
} }
} }
}

View File

@ -5,21 +5,20 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls;
{
public class CalendarPickerForm : AutoCleanForm public class CalendarPickerForm : AutoCleanForm
{ {
public CalendarPicker Picker { get; set; }
private int? SelectedDateMessage { get; set; }
public CalendarPickerForm() public CalendarPickerForm()
{ {
DeleteMode = EDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
Init += CalendarPickerForm_Init; Init += CalendarPickerForm_Init;
} }
public CalendarPicker Picker { get; set; }
private int? SelectedDateMessage { get; set; }
private Task CalendarPickerForm_Init(object sender, InitEventArgs e) private Task CalendarPickerForm_Init(object sender, InitEventArgs e)
{ {
Picker = new CalendarPicker Picker = new CalendarPicker
@ -34,7 +33,6 @@ namespace TelegramBotBaseTest.Tests.Controls
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
switch (message.RawData) switch (message.RawData)
{ {
case "back": case "back":
@ -45,7 +43,6 @@ namespace TelegramBotBaseTest.Tests.Controls
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
@ -68,12 +65,5 @@ namespace TelegramBotBaseTest.Tests.Controls
var m = await Device.Send(s, bf); var m = await Device.Send(s, bf);
SelectedDateMessage = m.MessageId; SelectedDateMessage = m.MessageId;
} }
}
} }
} }

View File

@ -6,8 +6,8 @@ using TelegramBotBase.DataSources;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls;
{
public class CheckedButtonListForm : AutoCleanForm public class CheckedButtonListForm : AutoCleanForm
{ {
private CheckedButtonList _mButtons; private CheckedButtonList _mButtons;
@ -25,8 +25,8 @@ namespace TelegramBotBaseTest.Tests.Controls
{ {
KeyboardType = EKeyboardType.InlineKeyBoard, KeyboardType = EKeyboardType.InlineKeyBoard,
EnablePaging = true, EnablePaging = true,
HeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch") }, HeadLayoutButtonRow = new List<ButtonBase> { new("Back", "back"), new("Switch Keyboard", "switch") },
SubHeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase("No checked items", "$") } SubHeadLayoutButtonRow = new List<ButtonBase> { new("No checked items", "$") }
}; };
var bf = new ButtonForm(); var bf = new ButtonForm();
@ -47,14 +47,17 @@ namespace TelegramBotBaseTest.Tests.Controls
private Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e) private Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e)
{ {
_mButtons.SubHeadLayoutButtonRow = new List<ButtonBase> { new ButtonBase($"{_mButtons.CheckedItems.Count} checked items", "$") }; _mButtons.SubHeadLayoutButtonRow = new List<ButtonBase>
{ new($"{_mButtons.CheckedItems.Count} checked items", "$") };
return Task.CompletedTask; return Task.CompletedTask;
} }
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
{ {
if (e.Button == null) if (e.Button == null)
{
return; return;
}
switch (e.Button.Value) switch (e.Button.Value)
{ {
@ -79,8 +82,5 @@ namespace TelegramBotBaseTest.Tests.Controls
await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
break; break;
} }
}
} }
} }

View File

@ -5,21 +5,20 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls;
{
public class MonthPickerForm : AutoCleanForm public class MonthPickerForm : AutoCleanForm
{ {
public MonthPicker Picker { get; set; }
private int? SelectedDateMessage { get; set; }
public MonthPickerForm() public MonthPickerForm()
{ {
DeleteMode = EDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
Init += MonthPickerForm_Init; Init += MonthPickerForm_Init;
} }
public MonthPicker Picker { get; set; }
private int? SelectedDateMessage { get; set; }
private Task MonthPickerForm_Init(object sender, InitEventArgs e) private Task MonthPickerForm_Init(object sender, InitEventArgs e)
{ {
Picker = new MonthPicker Picker = new MonthPicker
@ -33,7 +32,6 @@ namespace TelegramBotBaseTest.Tests.Controls
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
switch (message.RawData) switch (message.RawData)
{ {
case "back": case "back":
@ -44,7 +42,6 @@ namespace TelegramBotBaseTest.Tests.Controls
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
@ -66,12 +63,5 @@ namespace TelegramBotBaseTest.Tests.Controls
var m = await Device.Send(s, bf); var m = await Device.Send(s, bf);
SelectedDateMessage = m.MessageId; SelectedDateMessage = m.MessageId;
} }
}
} }
} }

View File

@ -7,8 +7,8 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls;
{
public class MultiToggleButtons : AutoCleanForm public class MultiToggleButtons : AutoCleanForm
{ {
public MultiToggleButtons() public MultiToggleButtons()
@ -20,10 +20,9 @@ namespace TelegramBotBaseTest.Tests.Controls
private Task ToggleButtons_Init(object sender, InitEventArgs e) private Task ToggleButtons_Init(object sender, InitEventArgs e)
{ {
var mtb = new MultiToggleButton var mtb = new MultiToggleButton
{ {
Options = new List<ButtonBase> { new ButtonBase("Option 1", "1"), new ButtonBase("Option 2", "2"), new ButtonBase("Option 3", "3") } Options = new List<ButtonBase> { new("Option 1", "1"), new("Option 2", "2"), new("Option 3", "3") }
}; };
mtb.SelectedOption = mtb.Options.FirstOrDefault(); mtb.SelectedOption = mtb.Options.FirstOrDefault();
@ -32,7 +31,7 @@ namespace TelegramBotBaseTest.Tests.Controls
mtb = new MultiToggleButton mtb = new MultiToggleButton
{ {
Options = new List<ButtonBase> { new ButtonBase("Option 4", "4"), new ButtonBase("Option 5", "5"), new ButtonBase("Option 6", "6") } Options = new List<ButtonBase> { new("Option 4", "4"), new("Option 5", "5"), new("Option 6", "6") }
}; };
mtb.SelectedOption = mtb.Options.FirstOrDefault(); mtb.SelectedOption = mtb.Options.FirstOrDefault();
@ -54,4 +53,3 @@ namespace TelegramBotBaseTest.Tests.Controls
Console.WriteLine("Selection for " + tb.Id + " has been removed."); Console.WriteLine("Selection for " + tb.Id + " has been removed.");
} }
} }
}

View File

@ -5,13 +5,12 @@ using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Controls.Subclass; using TelegramBotBaseTest.Tests.Controls.Subclass;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls;
{
public class MultiViewForm : AutoCleanForm public class MultiViewForm : AutoCleanForm
{ {
private MultiViewTest _mvt;
private ButtonGrid _bg; private ButtonGrid _bg;
private MultiViewTest _mvt;
public MultiViewForm() public MultiViewForm()
{ {
@ -48,7 +47,4 @@ namespace TelegramBotBaseTest.Tests.Controls
break; break;
} }
} }
}
} }

View File

@ -4,12 +4,10 @@ using TelegramBotBase.Base;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls.Subclass namespace TelegramBotBaseTest.Tests.Controls.Subclass;
{
public class MultiViewTest : MultiView public class MultiViewTest : MultiView
{ {
public override Task Action(MessageResult result, string value = null) public override Task Action(MessageResult result, string value = null)
{ {
switch (result.RawData) switch (result.RawData)
@ -31,7 +29,6 @@ namespace TelegramBotBaseTest.Tests.Controls.Subclass
public override async Task RenderView(RenderViewEventArgs e) public override async Task RenderView(RenderViewEventArgs e)
{ {
var bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next")); bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next"));
@ -50,13 +47,6 @@ namespace TelegramBotBaseTest.Tests.Controls.Subclass
await Device.Send("Unknown Page", bf); await Device.Send("Unknown Page", bf);
break; break;
}
}
}
} }
} }

View File

@ -5,8 +5,8 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls;
{
public class ToggleButtons : AutoCleanForm public class ToggleButtons : AutoCleanForm
{ {
public ToggleButtons() public ToggleButtons()
@ -18,7 +18,6 @@ namespace TelegramBotBaseTest.Tests.Controls
private Task ToggleButtons_Init(object sender, InitEventArgs e) private Task ToggleButtons_Init(object sender, InitEventArgs e)
{ {
var tb = new ToggleButton var tb = new ToggleButton
{ {
Checked = true Checked = true
@ -51,4 +50,3 @@ namespace TelegramBotBaseTest.Tests.Controls
Console.WriteLine(tb.Id + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked")); Console.WriteLine(tb.Id + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked"));
} }
} }
}

View File

@ -5,27 +5,30 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls namespace TelegramBotBaseTest.Tests.Controls;
{
public class TreeViewForms : AutoCleanForm public class TreeViewForms : AutoCleanForm
{ {
public TreeView View { get; set; }
private int? MessageId { get; set; }
public TreeViewForms() public TreeViewForms()
{ {
DeleteMode = EDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
Init += TreeViewForms_Init; Init += TreeViewForms_Init;
} }
public TreeView View { get; set; }
private int? MessageId { get; set; }
private Task TreeViewForms_Init(object sender, InitEventArgs e) private Task TreeViewForms_Init(object sender, InitEventArgs e)
{ {
View = new TreeView(); View = new TreeView();
var tvn = new TreeViewNode("Cars", "cars"); var tvn = new TreeViewNode("Cars", "cars");
tvn.AddNode(new TreeViewNode("Porsche", "porsche", new TreeViewNode("Website", "web", "https://www.porsche.com/germany/"), new TreeViewNode("911", "911"), new TreeViewNode("918 Spyder", "918"))); tvn.AddNode(new TreeViewNode("Porsche", "porsche",
new TreeViewNode("Website", "web", "https://www.porsche.com/germany/"),
new TreeViewNode("911", "911"),
new TreeViewNode("918 Spyder", "918")));
tvn.AddNode(new TreeViewNode("BMW", "bmw")); tvn.AddNode(new TreeViewNode("BMW", "bmw"));
tvn.AddNode(new TreeViewNode("Audi", "audi")); tvn.AddNode(new TreeViewNode("Audi", "audi"));
tvn.AddNode(new TreeViewNode("VW", "vw")); tvn.AddNode(new TreeViewNode("VW", "vw"));
@ -50,7 +53,9 @@ namespace TelegramBotBaseTest.Tests.Controls
await message.ConfirmAction(); await message.ConfirmAction();
if (message.Handled) if (message.Handled)
{
return; return;
}
switch (message.RawData) switch (message.RawData)
{ {
@ -63,9 +68,7 @@ namespace TelegramBotBaseTest.Tests.Controls
await NavigateTo(start); await NavigateTo(start);
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
@ -92,6 +95,4 @@ namespace TelegramBotBaseTest.Tests.Controls
MessageId = m.MessageId; MessageId = m.MessageId;
} }
} }
}
} }

View File

@ -7,12 +7,10 @@ using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests;
{
public class DataForm : AutoCleanForm public class DataForm : AutoCleanForm
{ {
public override async Task SentData(DataResult data) public override async Task SentData(DataResult data)
{ {
var tmp = ""; var tmp = "";
@ -80,7 +78,6 @@ namespace TelegramBotBaseTest.Tests
break; break;
} }
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
@ -88,7 +85,9 @@ namespace TelegramBotBaseTest.Tests
await message.ConfirmAction(); await message.ConfirmAction();
if (message.Handled) if (message.Handled)
{
return; return;
}
switch (message.RawData) switch (message.RawData)
{ {
@ -114,8 +113,6 @@ namespace TelegramBotBaseTest.Tests
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
@ -131,10 +128,5 @@ namespace TelegramBotBaseTest.Tests
InlineKeyboardMarkup ikv = bf; InlineKeyboardMarkup ikv = bf;
await Device.Send("Please upload a contact, photo, video, audio, document or location.", bf); await Device.Send("Please upload a contact, photo, video, audio, document or location.", bf);
}
} }
} }

View File

@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.DataSources;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.DataSources;
public class CustomDataSource : ButtonFormDataSource
{
public List<string> Countries = new() { "Country 1", "Country 2", "Country 3" };
public CustomDataSource()
{
LoadData();
}
public override int Count => Countries.Count;
public override int ColumnCount => 1;
public override int RowCount => Count;
/// <summary>
/// This method has the example purpose of creating and loading some example data.
/// When using a database you do not need this kind of method.
/// </summary>
private void LoadData()
{
//Exists data source? Read it
if (File.Exists(AppContext.BaseDirectory + "countries.json"))
{
try
{
var list = JsonConvert.DeserializeObject<List<string>>(File.ReadAllText("countries.json"));
Countries = list;
}
catch
{
}
return;
}
//If not, create it
try
{
var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(a => a.DisplayName).ToList();
Countries = countries;
var tmp = JsonConvert.SerializeObject(countries);
File.WriteAllText(AppContext.BaseDirectory + "countries.json", tmp);
}
catch
{
}
}
public override ButtonRow ItemAt(int index)
{
var item = Countries.ElementAt(index);
if (item == null)
{
return new ButtonRow();
}
return Render(item);
}
public override List<ButtonRow> ItemRange(int start, int count)
{
var items = Countries.Skip(start).Take(count);
var lst = new List<ButtonRow>();
foreach (var c in items)
{
lst.Add(Render(c));
}
return lst;
}
public override List<ButtonRow> AllItems()
{
var lst = new List<ButtonRow>();
foreach (var c in Countries)
{
lst.Add(Render(c));
}
return lst;
}
public override ButtonForm PickItems(int start, int count, string filter = null)
{
var rows = ItemRange(start, count);
var lst = new ButtonForm();
foreach (var c in rows)
{
lst.AddButtonRow(c);
}
return lst;
}
public override ButtonForm PickAllItems(string filter = null)
{
var rows = AllItems();
var bf = new ButtonForm();
bf.AddButtonRows(rows);
return bf;
}
public override int CalculateMax(string filter = null)
{
if (filter == null)
{
return Countries.Count;
}
return Countries.Where(a => a.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) != -1).Count();
}
public override ButtonRow Render(object data)
{
if (!(data is string s))
{
return new ButtonRow(new ButtonBase("Empty", "zero"));
}
return new ButtonRow(new ButtonBase(s, s));
}
}

View File

@ -0,0 +1,51 @@
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.DataSources;
public class List : FormBase
{
private ButtonGrid _buttons;
public List()
{
Init += List_Init;
}
private Task List_Init(object sender, InitEventArgs e)
{
_buttons = new ButtonGrid
{
EnablePaging = true,
EnableSearch = false
};
_buttons.ButtonClicked += __buttons_ButtonClicked;
_buttons.KeyboardType = EKeyboardType.ReplyKeyboard;
_buttons.DeleteReplyMessage = true;
_buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back"));
var cds = new CustomDataSource();
_buttons.DataSource = cds;
AddControl(_buttons);
return Task.CompletedTask;
}
private async Task __buttons_ButtonClicked(object sender, ButtonClickedEventArgs e)
{
switch (e.Button.Value)
{
case "back":
var mn = new Menu();
await NavigateTo(mn);
break;
}
}
}

View File

@ -1,143 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.DataSources;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Datasources
{
public class CustomDataSource : ButtonFormDataSource
{
public List<string> Countries = new List<string> { "Country 1", "Country 2", "Country 3" };
public CustomDataSource()
{
LoadData();
}
/// <summary>
/// This method has the example purpose of creating and loading some example data.
/// When using a database you do not need this kind of method.
/// </summary>
private void LoadData()
{
//Exists data source? Read it
if (File.Exists(AppContext.BaseDirectory + "countries.json"))
{
try
{
var list = JsonConvert.DeserializeObject<List<string>>(File.ReadAllText("countries.json"));
Countries = list;
}
catch
{
}
return;
}
//If not, create it
try
{
var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(a => a.DisplayName).ToList();
Countries = countries;
var tmp = JsonConvert.SerializeObject(countries);
File.WriteAllText( AppContext.BaseDirectory + "countries.json", tmp);
}
catch
{
}
}
public override ButtonRow ItemAt(int index)
{
var item = Countries.ElementAt(index);
if (item == null)
return new ButtonRow();
return Render(item);
}
public override List<ButtonRow> ItemRange(int start, int count)
{
var items = Countries.Skip(start).Take(count);
var lst = new List<ButtonRow>();
foreach (var c in items)
{
lst.Add(Render(c));
}
return lst;
}
public override List<ButtonRow> AllItems()
{
var lst = new List<ButtonRow>();
foreach (var c in Countries)
{
lst.Add(Render(c));
}
return lst;
}
public override ButtonForm PickItems(int start, int count, string filter = null)
{
var rows = ItemRange(start, count);
var lst = new ButtonForm();
foreach (var c in rows)
{
lst.AddButtonRow(c);
}
return lst;
}
public override ButtonForm PickAllItems(string filter = null)
{
var rows = AllItems();
var bf = new ButtonForm();
bf.AddButtonRows(rows);
return bf;
}
public override int CalculateMax(string filter = null)
{
if (filter == null)
return Countries.Count;
return Countries.Where(a => a.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) != -1).Count();
}
public override ButtonRow Render(object data)
{
if (!(data is string s))
return new ButtonRow(new ButtonBase("Empty", "zero"));
return new ButtonRow(new ButtonBase(s, s));
}
public override int Count => Countries.Count;
public override int ColumnCount => 1;
public override int RowCount => Count;
}
}

View File

@ -1,55 +0,0 @@
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Datasources
{
public class List : FormBase
{
private ButtonGrid _buttons;
public List()
{
Init += List_Init;
}
private Task List_Init(object sender, InitEventArgs e)
{
_buttons = new ButtonGrid
{
EnablePaging = true,
EnableSearch = false
};
_buttons.ButtonClicked += __buttons_ButtonClicked;
_buttons.KeyboardType = EKeyboardType.ReplyKeyboard;
_buttons.DeleteReplyMessage = true;
_buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back"));
var cds = new CustomDataSource();
_buttons.DataSource = cds;
AddControl(_buttons);
return Task.CompletedTask;
}
private async Task __buttons_ButtonClicked(object sender, ButtonClickedEventArgs e)
{
switch(e.Button.Value)
{
case "back":
var mn = new Menu();
await NavigateTo(mn);
break;
}
}
}
}

View File

@ -4,8 +4,8 @@ using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Groups namespace TelegramBotBaseTest.Tests.Groups;
{
public class GroupChange : GroupForm public class GroupChange : GroupForm
{ {
public GroupChange() public GroupChange()
@ -16,7 +16,6 @@ namespace TelegramBotBaseTest.Tests.Groups
private async Task GroupChange_Opened(object sender, EventArgs e) private async Task GroupChange_Opened(object sender, EventArgs e)
{ {
var bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
@ -24,13 +23,14 @@ namespace TelegramBotBaseTest.Tests.Groups
bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
await Device.Send("GroupChange started, click to switch", bf); await Device.Send("GroupChange started, click to switch", bf);
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
{
return; return;
}
var bn = message.RawData; var bn = message.RawData;
@ -62,13 +62,11 @@ namespace TelegramBotBaseTest.Tests.Groups
break; break;
} }
} }
public override async Task OnGroupChanged(GroupChangedEventArgs e) public override async Task OnGroupChanged(GroupChangedEventArgs e)
{ {
await Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " + e.OriginalMessage.Message.From.LastName); await Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " +
} e.OriginalMessage.Message.From.LastName);
} }
} }

View File

@ -7,12 +7,10 @@ using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Groups namespace TelegramBotBaseTest.Tests.Groups;
{
public class LinkReplaceTest : GroupForm public class LinkReplaceTest : GroupForm
{ {
private Dictionary<long, int> Counter { get; set; } = new Dictionary<long, int>();
private const int Maximum = 3; private const int Maximum = 3;
@ -21,9 +19,10 @@ namespace TelegramBotBaseTest.Tests.Groups
Opened += LinkReplaceTest_Opened; Opened += LinkReplaceTest_Opened;
} }
private Dictionary<long, int> Counter { get; } = new();
private async Task LinkReplaceTest_Opened(object sender, EventArgs e) private async Task LinkReplaceTest_Opened(object sender, EventArgs e)
{ {
var bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
@ -31,13 +30,14 @@ namespace TelegramBotBaseTest.Tests.Groups
bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
await Device.Send("LinkReplaceTest started, click to switch", bf); await Device.Send("LinkReplaceTest started, click to switch", bf);
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
{
return; return;
}
var bn = message.RawData; var bn = message.RawData;
@ -68,7 +68,6 @@ namespace TelegramBotBaseTest.Tests.Groups
break; break;
} }
} }
public override async Task OnMessage(MessageResult e) public override async Task OnMessage(MessageResult e)
@ -76,16 +75,20 @@ namespace TelegramBotBaseTest.Tests.Groups
var from = e.Message.From.Id; var from = e.Message.From.Id;
if (e.Message.From.IsBot) if (e.Message.From.IsBot)
{
return; return;
}
//Are urls inside his message ? //Are urls inside his message ?
if (!HasLinks(e.MessageText)) if (!HasLinks(e.MessageText))
{
return; return;
}
var u = await Device.GetChatUser(from); var u = await Device.GetChatUser(from);
//Don't kick Admins or Creators //Don't kick Admins or Creators
if (u.Status == ChatMemberStatus.Administrator | u.Status == ChatMemberStatus.Creator) if ((u.Status == ChatMemberStatus.Administrator) | (u.Status == ChatMemberStatus.Creator))
{ {
await Device.Send("You won't get kicked,...not this time."); await Device.Send("You won't get kicked,...not this time.");
return; return;
@ -120,17 +123,16 @@ namespace TelegramBotBaseTest.Tests.Groups
{ {
await e.Device.KickUser(from); await e.Device.KickUser(from);
await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been removed from the group"); await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName +
" has been removed from the group");
} }
else else
{ {
await e.Device.RestrictUser(from, cp, DateTime.UtcNow.AddSeconds(30)); await e.Device.RestrictUser(from, cp, DateTime.UtcNow.AddSeconds(30));
await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been blocked for 30 seconds"); await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName +
" has been blocked for 30 seconds");
} }
} }
/// <summary> /// <summary>
@ -152,14 +154,12 @@ namespace TelegramBotBaseTest.Tests.Groups
{ {
var tmp = str; var tmp = str;
var pattern = @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$"; var pattern =
@"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$";
var r = new Regex(pattern); var r = new Regex(pattern);
var matches = r.Matches(tmp); var matches = r.Matches(tmp);
return (matches.Count > 0); return matches.Count > 0;
}
} }
} }

View File

@ -6,11 +6,10 @@ using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Groups namespace TelegramBotBaseTest.Tests.Groups;
{
public class WelcomeUser : GroupForm public class WelcomeUser : GroupForm
{ {
public WelcomeUser() public WelcomeUser()
{ {
Opened += WelcomeUser_Opened; Opened += WelcomeUser_Opened;
@ -19,7 +18,6 @@ namespace TelegramBotBaseTest.Tests.Groups
private async Task WelcomeUser_Opened(object sender, EventArgs e) private async Task WelcomeUser_Opened(object sender, EventArgs e)
{ {
var bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
@ -27,13 +25,14 @@ namespace TelegramBotBaseTest.Tests.Groups
bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
await Device.Send("WelcomeUser started, click to switch", bf); await Device.Send("WelcomeUser started, click to switch", bf);
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
{
return; return;
}
var bn = message.RawData; var bn = message.RawData;
@ -64,28 +63,20 @@ namespace TelegramBotBaseTest.Tests.Groups
break; break;
} }
} }
public override async Task OnMemberChanges(MemberChangeEventArgs e) public override async Task OnMemberChanges(MemberChangeEventArgs e)
{ {
if (e.Type == MessageType.ChatMembersAdded) if (e.Type == MessageType.ChatMembersAdded)
{ {
await Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName)
await Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + "\r\n" + b)); .Aggregate((a, b) => a + "\r\n" + b));
} }
else if (e.Type == MessageType.ChatMemberLeft) else if (e.Type == MessageType.ChatMemberLeft)
{ {
await Device.Send(e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) + " has left the group"); await Device.Send(
e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) +
} " has left the group");
}
}
} }
} }

View File

@ -4,11 +4,11 @@ using TelegramBotBase.Base;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Controls; using TelegramBotBaseTest.Tests.Controls;
using TelegramBotBaseTest.Tests.Datasources; using TelegramBotBaseTest.Tests.DataSources;
using TelegramBotBaseTest.Tests.Groups; using TelegramBotBaseTest.Tests.Groups;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests;
{
public class Menu : AutoCleanForm public class Menu : AutoCleanForm
{ {
public Menu() public Menu()
@ -18,9 +18,7 @@ namespace TelegramBotBaseTest.Tests
public override async Task Load(MessageResult message) public override async Task Load(MessageResult message)
{ {
if ((message.Message.Chat.Type == ChatType.Group) | (message.Message.Chat.Type == ChatType.Supergroup))
if (message.Message.Chat.Type == ChatType.Group | message.Message.Chat.Type == ChatType.Supergroup)
{ {
var sf = new WelcomeUser(); var sf = new WelcomeUser();
@ -39,7 +37,9 @@ namespace TelegramBotBaseTest.Tests
if (call == null) if (call == null)
{
return; return;
}
message.Handled = true; message.Handled = true;
@ -213,16 +213,14 @@ namespace TelegramBotBaseTest.Tests
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
var btn = new ButtonForm(); var btn = new ButtonForm();
btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()), new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize())); btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()),
new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize()));
btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize())); btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize()));
btn.AddButtonRow(new ButtonBase("#4 Registration Example", new CallbackData("a", "registration").Serialize())); btn.AddButtonRow(new ButtonBase("#4 Registration Example", new CallbackData("a", "registration").Serialize()));
@ -238,27 +236,30 @@ namespace TelegramBotBaseTest.Tests
btn.AddButtonRow(new ButtonBase("#11 ToggleButtons", new CallbackData("a", "togglebuttons").Serialize())); btn.AddButtonRow(new ButtonBase("#11 ToggleButtons", new CallbackData("a", "togglebuttons").Serialize()));
btn.AddButtonRow(new ButtonBase("#11.2 MultiToggleButtons", new CallbackData("a", "multitogglebuttons").Serialize())); btn.AddButtonRow(new ButtonBase("#11.2 MultiToggleButtons",
new CallbackData("a", "multitogglebuttons").Serialize()));
btn.AddButtonRow(new ButtonBase("#12 ButtonGrid", new CallbackData("a", "buttongrid").Serialize())); btn.AddButtonRow(new ButtonBase("#12 ButtonGrid", new CallbackData("a", "buttongrid").Serialize()));
btn.AddButtonRow(new ButtonBase("#13 ButtonGrid Paging & Filter", new CallbackData("a", "buttongridfilter").Serialize())); btn.AddButtonRow(new ButtonBase("#13 ButtonGrid Paging & Filter",
new CallbackData("a", "buttongridfilter").Serialize()));
btn.AddButtonRow(new ButtonBase("#14 ButtonGrid Tags (Filter)", new CallbackData("a", "buttongridtags").Serialize())); btn.AddButtonRow(new ButtonBase("#14 ButtonGrid Tags (Filter)",
new CallbackData("a", "buttongridtags").Serialize()));
btn.AddButtonRow(new ButtonBase("#15 MultiView", new CallbackData("a", "multiview").Serialize())); btn.AddButtonRow(new ButtonBase("#15 MultiView", new CallbackData("a", "multiview").Serialize()));
btn.AddButtonRow(new ButtonBase("#16 CheckedButtonList", new CallbackData("a", "checkedbuttonlist").Serialize())); btn.AddButtonRow(
new ButtonBase("#16 CheckedButtonList", new CallbackData("a", "checkedbuttonlist").Serialize()));
btn.AddButtonRow(new ButtonBase("#17 NavigationController (Push/Pop)", new CallbackData("a", "navigationcontroller").Serialize())); btn.AddButtonRow(new ButtonBase("#17 NavigationController (Push/Pop)",
new CallbackData("a", "navigationcontroller").Serialize()));
btn.AddButtonRow(new ButtonBase("#18 Dynamic ButtonGrid (DataSources)", new CallbackData("a", "dynamicbuttongrid").Serialize())); btn.AddButtonRow(new ButtonBase("#18 Dynamic ButtonGrid (DataSources)",
new CallbackData("a", "dynamicbuttongrid").Serialize()));
btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize())); btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize()));
await Device.Send("Choose your test:", btn); await Device.Send("Choose your test:", btn);
} }
}
} }

View File

@ -3,13 +3,12 @@ using System.Threading.Tasks;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Form.Navigation; using TelegramBotBase.Form.Navigation;
namespace TelegramBotBaseTest.Tests.Navigation namespace TelegramBotBaseTest.Tests.Navigation;
{
internal class CustomController : NavigationController internal class CustomController : NavigationController
{ {
public CustomController(FormBase form) : base(form) public CustomController(FormBase form) : base(form)
{ {
} }
@ -37,6 +36,4 @@ namespace TelegramBotBaseTest.Tests.Navigation
return base.PopToRootAsync(); return base.PopToRootAsync();
} }
}
} }

View File

@ -4,8 +4,8 @@ using Telegram.Bot.Types;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Navigation namespace TelegramBotBaseTest.Tests.Navigation;
{
public class Form1 : FormBase public class Form1 : FormBase
{ {
private Message _msg; private Message _msg;
@ -18,7 +18,9 @@ namespace TelegramBotBaseTest.Tests.Navigation
private async Task Form1_Closed(object sender, EventArgs e) private async Task Form1_Closed(object sender, EventArgs e)
{ {
if (_msg == null) if (_msg == null)
{
return; return;
}
await Device.DeleteMessage(_msg); await Device.DeleteMessage(_msg);
} }
@ -26,7 +28,9 @@ namespace TelegramBotBaseTest.Tests.Navigation
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
{
return; return;
}
await message.ConfirmAction(); await message.ConfirmAction();
@ -59,18 +63,15 @@ namespace TelegramBotBaseTest.Tests.Navigation
await NavigationController.PopToRootAsync(); await NavigationController.PopToRootAsync();
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (_msg != null) if (_msg != null)
{
return; return;
}
var bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow("Next page", "next"); bf.AddButtonRow("Next page", "next");
@ -78,9 +79,5 @@ namespace TelegramBotBaseTest.Tests.Navigation
bf.AddButtonRow("Back to root", "root"); bf.AddButtonRow("Back to root", "root");
_msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf); _msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf);
}
} }
} }

View File

@ -3,8 +3,8 @@ using Telegram.Bot.Types;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Navigation namespace TelegramBotBaseTest.Tests.Navigation;
{
public class Start : FormBase public class Start : FormBase
{ {
private Message _msg; private Message _msg;
@ -18,7 +18,9 @@ namespace TelegramBotBaseTest.Tests.Navigation
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
{
return; return;
}
await message.ConfirmAction(); await message.ConfirmAction();
@ -39,7 +41,9 @@ namespace TelegramBotBaseTest.Tests.Navigation
await NavigateTo(nc); await NavigateTo(nc);
if (_msg == null) if (_msg == null)
{
return; return;
}
await Device.DeleteMessage(_msg); await Device.DeleteMessage(_msg);
@ -54,13 +58,14 @@ namespace TelegramBotBaseTest.Tests.Navigation
await NavigateTo(mn); await NavigateTo(mn);
if (_msg == null) if (_msg == null)
{
return; return;
}
await Device.DeleteMessage(_msg); await Device.DeleteMessage(_msg);
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
@ -71,9 +76,5 @@ namespace TelegramBotBaseTest.Tests.Navigation
bf.AddButtonRow("No", "no"); bf.AddButtonRow("No", "no");
_msg = await Device.Send("Open controller?", bf); _msg = await Device.Send("Open controller?", bf);
}
} }
} }

View File

@ -3,8 +3,8 @@ using TelegramBotBase.Base;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Notifications namespace TelegramBotBaseTest.Tests.Notifications;
{
public class Start : AutoCleanForm public class Start : AutoCleanForm
{ {
private bool _sent; private bool _sent;
@ -17,7 +17,9 @@ namespace TelegramBotBaseTest.Tests.Notifications
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
{
return; return;
}
switch (message.RawData) switch (message.RawData)
{ {
@ -37,15 +39,15 @@ namespace TelegramBotBaseTest.Tests.Notifications
await message.ConfirmAction("This is feedback"); await message.ConfirmAction("This is feedback");
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
if (_sent) if (_sent)
{
return; return;
}
var bf = new ButtonForm(); var bf = new ButtonForm();
bf.AddButtonRow("Normal feeback", "normal"); bf.AddButtonRow("Normal feeback", "normal");
@ -56,6 +58,4 @@ namespace TelegramBotBaseTest.Tests.Notifications
_sent = true; _sent = true;
} }
}
} }

View File

@ -6,11 +6,10 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests;
{
public class ProgressTest : AutoCleanForm public class ProgressTest : AutoCleanForm
{ {
public ProgressTest() public ProgressTest()
{ {
DeleteMode = EDeleteMode.OnLeavingForm; DeleteMode = EDeleteMode.OnLeavingForm;
@ -32,7 +31,9 @@ namespace TelegramBotBaseTest.Tests
if (call == null) if (call == null)
{
return; return;
}
ProgressBar bar = null; ProgressBar bar = null;
@ -94,7 +95,6 @@ namespace TelegramBotBaseTest.Tests
default: default:
return; return;
} }
@ -110,17 +110,17 @@ namespace TelegramBotBaseTest.Tests
Thread.Sleep(250); Thread.Sleep(250);
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
var btn = new ButtonForm(); var btn = new ButtonForm();
btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()), new ButtonBase("Squares", new CallbackData("a", "squares").Serialize())); btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()),
new ButtonBase("Squares", new CallbackData("a", "squares").Serialize()));
btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()), new ButtonBase("Lines", new CallbackData("a", "lines").Serialize())); btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()),
new ButtonBase("Lines", new CallbackData("a", "lines").Serialize()));
btn.AddButtonRow(new ButtonBase("Squared Line", new CallbackData("a", "squaredlines").Serialize())); btn.AddButtonRow(new ButtonBase("Squared Line", new CallbackData("a", "squaredlines").Serialize()));
@ -133,6 +133,4 @@ namespace TelegramBotBaseTest.Tests
{ {
await Device.Send("Ciao from ProgressTest"); await Device.Send("Ciao from ProgressTest");
} }
}
} }

View File

@ -2,8 +2,8 @@
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Register namespace TelegramBotBaseTest.Tests.Register;
{
public class PerForm : AutoCleanForm public class PerForm : AutoCleanForm
{ {
public string EMail { get; set; } public string EMail { get; set; }
@ -15,7 +15,9 @@ namespace TelegramBotBaseTest.Tests.Register
public override Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
if (message.MessageText.Trim() == "") if (message.MessageText.Trim() == "")
{
return Task.CompletedTask; return Task.CompletedTask;
}
if (Firstname == null) if (Firstname == null)
{ {
@ -45,7 +47,9 @@ namespace TelegramBotBaseTest.Tests.Register
await message.ConfirmAction(); await message.ConfirmAction();
if (call == null) if (call == null)
{
return; return;
}
switch (call.Value) switch (call.Value)
{ {
@ -56,10 +60,7 @@ namespace TelegramBotBaseTest.Tests.Register
await NavigateTo(start); await NavigateTo(start);
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
@ -94,7 +95,4 @@ namespace TelegramBotBaseTest.Tests.Register
await Device.Send("Your details:\r\n" + s, bf); await Device.Send("Your details:\r\n" + s, bf);
} }
}
} }

View File

@ -3,11 +3,10 @@ using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Register.Steps; using TelegramBotBaseTest.Tests.Register.Steps;
namespace TelegramBotBaseTest.Tests.Register namespace TelegramBotBaseTest.Tests.Register;
{
public class PerStep : AutoCleanForm public class PerStep : AutoCleanForm
{ {
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
await message.ConfirmAction(); await message.ConfirmAction();
@ -28,7 +27,6 @@ namespace TelegramBotBaseTest.Tests.Register
await NavigateTo(start); await NavigateTo(start);
break; break;
} }
} }
@ -41,4 +39,3 @@ namespace TelegramBotBaseTest.Tests.Register
await Device.Send("Register Steps", bf); await Device.Send("Register Steps", bf);
} }
} }
}

View File

@ -2,8 +2,8 @@
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Register namespace TelegramBotBaseTest.Tests.Register;
{
public class Start : AutoCleanForm public class Start : AutoCleanForm
{ {
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
@ -14,7 +14,9 @@ namespace TelegramBotBaseTest.Tests.Register
if (call == null) if (call == null)
{
return; return;
}
switch (call.Value) switch (call.Value)
{ {
@ -40,13 +42,10 @@ namespace TelegramBotBaseTest.Tests.Register
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
var btn = new ButtonForm(); var btn = new ButtonForm();
btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize())); btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize()));
@ -54,10 +53,5 @@ namespace TelegramBotBaseTest.Tests.Register
btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize())); btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize()));
await Device.Send("Choose your test:", btn); await Device.Send("Choose your test:", btn);
}
} }
} }

View File

@ -1,5 +1,5 @@
namespace TelegramBotBaseTest.Tests.Register.Steps namespace TelegramBotBaseTest.Tests.Register.Steps;
{
public class Data public class Data
{ {
public string EMail { get; set; } public string EMail { get; set; }
@ -7,6 +7,4 @@
public string Firstname { get; set; } public string Firstname { get; set; }
public string Lastname { get; set; } public string Lastname { get; set; }
}
} }

View File

@ -3,17 +3,17 @@ using TelegramBotBase.Args;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Register.Steps namespace TelegramBotBaseTest.Tests.Register.Steps;
{
public class Step1 : AutoCleanForm public class Step1 : AutoCleanForm
{ {
public Data UserData { get; set; }
public Step1() public Step1()
{ {
Init += Step1_Init; Init += Step1_Init;
} }
public Data UserData { get; set; }
private Task Step1_Init(object sender, InitEventArgs e) private Task Step1_Init(object sender, InitEventArgs e)
{ {
UserData = new Data(); UserData = new Data();
@ -24,10 +24,14 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
public override Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
{
return Task.CompletedTask; return Task.CompletedTask;
}
if (message.MessageText.Trim() == "") if (message.MessageText.Trim() == "")
{
return Task.CompletedTask; return Task.CompletedTask;
}
if (UserData.Firstname == null) if (UserData.Firstname == null)
{ {
@ -54,6 +58,4 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
await NavigateTo(step2); await NavigateTo(step2);
} }
}
} }

View File

@ -2,8 +2,8 @@
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Register.Steps namespace TelegramBotBaseTest.Tests.Register.Steps;
{
public class Step2 : AutoCleanForm public class Step2 : AutoCleanForm
{ {
public Data UserData { get; set; } public Data UserData { get; set; }
@ -12,10 +12,14 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
public override Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
{
return Task.CompletedTask; return Task.CompletedTask;
}
if (message.MessageText.Trim() == "") if (message.MessageText.Trim() == "")
{
return Task.CompletedTask; return Task.CompletedTask;
}
if (UserData.Lastname == null) if (UserData.Lastname == null)
{ {
@ -43,6 +47,4 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
await NavigateTo(step3); await NavigateTo(step3);
} }
}
} }

View File

@ -2,8 +2,8 @@
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Register.Steps namespace TelegramBotBaseTest.Tests.Register.Steps;
{
public class Step3 : AutoCleanForm public class Step3 : AutoCleanForm
{ {
public Data UserData { get; set; } public Data UserData { get; set; }
@ -11,10 +11,14 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
public override Task Load(MessageResult message) public override Task Load(MessageResult message)
{ {
if (message.Handled) if (message.Handled)
{
return Task.CompletedTask; return Task.CompletedTask;
}
if (message.MessageText.Trim() == "") if (message.MessageText.Trim() == "")
{
return Task.CompletedTask; return Task.CompletedTask;
}
if (UserData.EMail == null) if (UserData.EMail == null)
{ {
@ -38,9 +42,7 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
await NavigateTo(start); await NavigateTo(start);
break; break;
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
@ -64,6 +66,4 @@ namespace TelegramBotBaseTest.Tests.Register.Steps
await Device.Send("Your details:\r\n" + s, bf); await Device.Send("Your details:\r\n" + s, bf);
} }
}
} }

View File

@ -4,11 +4,10 @@ using TelegramBotBase.Base;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests;
{
public class SimpleForm : AutoCleanForm public class SimpleForm : AutoCleanForm
{ {
public SimpleForm() public SimpleForm()
{ {
DeleteSide = EDeleteSide.Both; DeleteSide = EDeleteSide.Both;
@ -60,7 +59,4 @@ namespace TelegramBotBaseTest.Tests
break; break;
} }
} }
}
} }

View File

@ -3,8 +3,8 @@ using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Groups; using TelegramBotBaseTest.Tests.Groups;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests;
{
public class Start : SplitterForm public class Start : SplitterForm
{ {
public override async Task<bool> Open(MessageResult e) public override async Task<bool> Open(MessageResult e)
@ -33,6 +33,4 @@ namespace TelegramBotBaseTest.Tests
{ {
return base.OpenSupergroup(e); return base.OpenSupergroup(e);
} }
}
} }

View File

@ -3,18 +3,18 @@ using System.Threading.Tasks;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests;
{
public class TestForm : FormBase public class TestForm : FormBase
{ {
private string LastMessage { get; set; }
public TestForm() public TestForm()
{ {
Opened += TestForm_Opened; Opened += TestForm_Opened;
Closed += TestForm_Closed; Closed += TestForm_Closed;
} }
private string LastMessage { get; set; }
private async Task TestForm_Opened(object sender, EventArgs e) private async Task TestForm_Opened(object sender, EventArgs e)
{ {
await Device.Send("Welcome to Form 1"); await Device.Send("Welcome to Form 1");
@ -46,14 +46,14 @@ namespace TelegramBotBaseTest.Tests
default: default:
if (message.UpdateData == null) if (message.UpdateData == null)
{
return; return;
}
LastMessage = message.Message.Text; LastMessage = message.Message.Text;
break; break;
} }
} }
@ -61,12 +61,7 @@ namespace TelegramBotBaseTest.Tests
{ {
if (message.Command == "reply") if (message.Command == "reply")
{ {
await Device.Send("Last message: " + LastMessage); await Device.Send("Last message: " + LastMessage);
}
}
}
} }
} }

View File

@ -6,12 +6,10 @@ using TelegramBotBase.Base;
using TelegramBotBase.Extensions.Images; using TelegramBotBase.Extensions.Images;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests namespace TelegramBotBaseTest.Tests;
{
public class TestForm2 : FormBase public class TestForm2 : FormBase
{ {
public TestForm2() public TestForm2()
{ {
Opened += TestForm2_Opened; Opened += TestForm2_Opened;
@ -29,8 +27,6 @@ namespace TelegramBotBaseTest.Tests
} }
public override async Task Action(MessageResult message) public override async Task Action(MessageResult message)
{ {
var call = message.GetData<CallbackData>(); var call = message.GetData<CallbackData>();
@ -43,7 +39,6 @@ namespace TelegramBotBaseTest.Tests
if (call.Value == "testform1") if (call.Value == "testform1")
{ {
var tf = new TestForm(); var tf = new TestForm();
await NavigateTo(tf); await NavigateTo(tf);
@ -62,7 +57,8 @@ namespace TelegramBotBaseTest.Tests
} }
else if (call.Value == "confirm") else if (call.Value == "confirm")
{ {
var pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"), new ButtonBase("Cancel", "cancel")); var pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"),
new ButtonBase("Cancel", "cancel"));
pd.ButtonClicked += async (s, en) => pd.ButtonClicked += async (s, en) =>
{ {
@ -77,28 +73,21 @@ namespace TelegramBotBaseTest.Tests
{ {
var pd = new PromptDialog("Please tell me your name ?"); var pd = new PromptDialog("Please tell me your name ?");
pd.Completed += async (s, en) => pd.Completed += async (s, en) => { await Device.Send("Hello " + pd.Value); };
{
await Device.Send("Hello " + pd.Value);
};
await OpenModal(pd); await OpenModal(pd);
} }
} }
public override async Task Render(MessageResult message) public override async Task Render(MessageResult message)
{ {
var bmp = new Bitmap(800, 600); var bmp = new Bitmap(800, 600);
using (var g = Graphics.FromImage(bmp)) using (var g = Graphics.FromImage(bmp))
{ {
g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height); g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);
g.DrawString("Test Image", new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Black, new PointF(50, 50)); g.DrawString("Test Image", new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Black,
new PointF(50, 50));
} }
await Device.SetAction(ChatAction.UploadPhoto); await Device.SetAction(ChatAction.UploadPhoto);
@ -115,9 +104,5 @@ namespace TelegramBotBaseTest.Tests
await Device.SendPhoto(bmp, "Test", "", btn); await Device.SendPhoto(bmp, "Test", "", btn);
}
} }
} }

View File

@ -3,13 +3,27 @@ using System.Collections.Generic;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
/// <summary> /// <summary>
/// Base class for given bot command results /// Base class for given bot command results
/// </summary> /// </summary>
public class BotCommandEventArgs : EventArgs public class BotCommandEventArgs : EventArgs
{ {
public BotCommandEventArgs()
{
}
public BotCommandEventArgs(string command, List<string> parameters, Message message, long deviceId,
DeviceSession device)
{
Command = command;
Parameters = parameters;
OriginalMessage = message;
DeviceId = deviceId;
Device = device;
}
public string Command { get; set; } public string Command { get; set; }
public List<string> Parameters { get; set; } public List<string> Parameters { get; set; }
@ -21,22 +35,4 @@ namespace TelegramBotBase.Args
public bool Handled { get; set; } = false; public bool Handled { get; set; } = false;
public Message OriginalMessage { get; set; } public Message OriginalMessage { get; set; }
public BotCommandEventArgs()
{
}
public BotCommandEventArgs(string command, List<string> parameters, Message message, long deviceId, DeviceSession device)
{
this.Command = command;
this.Parameters = parameters;
OriginalMessage = message;
this.DeviceId = deviceId;
this.Device = device;
}
}
} }

View File

@ -2,25 +2,15 @@
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form; using TelegramBotBase.Form;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
/// <summary> /// <summary>
/// Button get clicked event /// Button get clicked event
/// </summary> /// </summary>
public class ButtonClickedEventArgs : EventArgs public class ButtonClickedEventArgs : EventArgs
{ {
public ButtonBase Button { get; set; }
public int Index { get; set; }
public object Tag { get; set; }
public ButtonRow Row { get; set; }
public ButtonClickedEventArgs() public ButtonClickedEventArgs()
{ {
} }
public ButtonClickedEventArgs(ButtonBase button) public ButtonClickedEventArgs(ButtonBase button)
@ -32,14 +22,21 @@ namespace TelegramBotBase.Args
public ButtonClickedEventArgs(ButtonBase button, int index) public ButtonClickedEventArgs(ButtonBase button, int index)
{ {
Button = button; Button = button;
this.Index = index; Index = index;
} }
public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row) public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row)
{ {
Button = button; Button = button;
this.Index = index; Index = index;
Row = row; Row = row;
} }
}
public ButtonBase Button { get; set; }
public int Index { get; set; }
public object Tag { get; set; }
public ButtonRow Row { get; set; }
} }

View File

@ -1,10 +1,21 @@
using System; using System;
using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Controls.Hybrid;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class CheckedChangedEventArgs : EventArgs public class CheckedChangedEventArgs : EventArgs
{ {
public CheckedChangedEventArgs()
{
}
public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked)
{
Row = row;
Index = index;
Checked = @checked;
}
/// <summary> /// <summary>
/// Contains the index of the row where the button is inside. /// Contains the index of the row where the button is inside.
/// Contains -1 when it is a layout button or not found. /// Contains -1 when it is a layout button or not found.
@ -22,20 +33,4 @@ namespace TelegramBotBase.Args
/// Contains the new checked status of the row. /// Contains the new checked status of the row.
/// </summary> /// </summary>
public bool Checked { get; set; } public bool Checked { get; set; }
public CheckedChangedEventArgs()
{
}
public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked)
{
Row = row;
this.Index = index;
this.Checked = @checked;
}
}
} }

View File

@ -2,21 +2,17 @@
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base; using TelegramBotBase.Base;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class GroupChangedEventArgs : EventArgs public class GroupChangedEventArgs : EventArgs
{ {
public MessageType Type { get; set; }
public MessageResult OriginalMessage { get; set; }
public GroupChangedEventArgs(MessageType type, MessageResult message) public GroupChangedEventArgs(MessageType type, MessageResult message)
{ {
Type = type; Type = type;
OriginalMessage = message; OriginalMessage = message;
} }
public MessageType Type { get; set; }
public MessageResult OriginalMessage { get; set; }
}
} }

View File

@ -1,14 +1,13 @@
using System; using System;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class InitEventArgs : EventArgs public class InitEventArgs : EventArgs
{ {
public object[] Args { get; set; }
public InitEventArgs(params object[] args) public InitEventArgs(params object[] args)
{ {
Args = args; Args = args;
} }
}
public object[] Args { get; set; }
} }

View File

@ -1,17 +1,17 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class LoadStateEventArgs public class LoadStateEventArgs
{ {
public Dictionary<string,object> Values { get; set; }
public LoadStateEventArgs() public LoadStateEventArgs()
{ {
Values = new Dictionary<string, object>(); Values = new Dictionary<string, object>();
} }
public Dictionary<string, object> Values { get; set; }
public List<string> Keys => Values.Keys.ToList(); public List<string> Keys => Values.Keys.ToList();
public string Get(string key) public string Get(string key)
@ -23,7 +23,9 @@ namespace TelegramBotBase.Args
{ {
var i = 0; var i = 0;
if (int.TryParse(Values[key].ToString(), out i)) if (int.TryParse(Values[key].ToString(), out i))
{
return i; return i;
}
return 0; return 0;
} }
@ -32,7 +34,9 @@ namespace TelegramBotBase.Args
{ {
double d = 0; double d = 0;
if (double.TryParse(Values[key].ToString(), out d)) if (double.TryParse(Values[key].ToString(), out d))
{
return d; return d;
}
return 0; return 0;
} }
@ -41,7 +45,9 @@ namespace TelegramBotBase.Args
{ {
var b = false; var b = false;
if (bool.TryParse(Values[key].ToString(), out b)) if (bool.TryParse(Values[key].ToString(), out b))
{
return b; return b;
}
return false; return false;
} }
@ -50,6 +56,4 @@ namespace TelegramBotBase.Args
{ {
return Values[key]; return Values[key];
} }
}
} }

View File

@ -5,20 +5,13 @@ using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base; using TelegramBotBase.Base;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class MemberChangeEventArgs : EventArgs public class MemberChangeEventArgs : EventArgs
{ {
public List<User> Members { get; set; }
public MessageType Type { get; set; }
public MessageResult Result { get; set; }
public MemberChangeEventArgs() public MemberChangeEventArgs()
{ {
Members = new List<User>(); Members = new List<User>();
} }
public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members) public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members)
@ -28,9 +21,9 @@ namespace TelegramBotBase.Args
Members = members.ToList(); Members = members.ToList();
} }
public List<User> Members { get; set; }
public MessageType Type { get; set; }
public MessageResult Result { get; set; }
}
} }

View File

@ -1,16 +1,11 @@
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class MessageDeletedEventArgs public class MessageDeletedEventArgs
{ {
public int MessageId
{
get;set;
}
public MessageDeletedEventArgs(int messageId) public MessageDeletedEventArgs(int messageId)
{ {
MessageId = messageId; MessageId = messageId;
} }
} public int MessageId { get; set; }
} }

View File

@ -1,26 +1,20 @@
using System; using System;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
public class MessageIncomeEventArgs : EventArgs public class MessageIncomeEventArgs : EventArgs
{ {
public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message)
{
DeviceId = deviceId;
Device = device;
Message = message;
}
public long DeviceId { get; set; } public long DeviceId { get; set; }
public DeviceSession Device { get; set; } public DeviceSession Device { get; set; }
public MessageResult Message { get; set; } public MessageResult Message { get; set; }
public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message)
{
this.DeviceId = deviceId;
this.Device = device;
Message = message;
}
}
} }

View File

@ -1,17 +1,15 @@
using Telegram.Bot.Types; using Telegram.Bot.Types;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class MessageReceivedEventArgs public class MessageReceivedEventArgs
{ {
public int MessageId => Message.MessageId;
public Message Message { get; set; }
public MessageReceivedEventArgs(Message m) public MessageReceivedEventArgs(Message m)
{ {
Message = m; Message = m;
} }
} public int MessageId => Message.MessageId;
public Message Message { get; set; }
} }

View File

@ -1,10 +1,16 @@
using System; using System;
using Telegram.Bot.Types; using Telegram.Bot.Types;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class MessageSentEventArgs : EventArgs public class MessageSentEventArgs : EventArgs
{ {
public MessageSentEventArgs(Message message, Type origin)
{
Message = message;
Origin = origin;
}
public int MessageId => Message.MessageId; public int MessageId => Message.MessageId;
public Message Message { get; set; } public Message Message { get; set; }
@ -13,14 +19,4 @@ namespace TelegramBotBase.Args
/// Contains the element, which has called the method. /// Contains the element, which has called the method.
/// </summary> /// </summary>
public Type Origin { get; set; } public Type Origin { get; set; }
public MessageSentEventArgs(Message message, Type origin)
{
Message = message;
this.Origin = origin;
}
}
} }

View File

@ -1,10 +1,8 @@
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class PromptDialogCompletedEventArgs public class PromptDialogCompletedEventArgs
{ {
public object Tag { get; set; } public object Tag { get; set; }
public string Value { get; set; } public string Value { get; set; }
}
} }

View File

@ -1,18 +1,13 @@
using System; using System;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class RenderViewEventArgs : EventArgs public class RenderViewEventArgs : EventArgs
{ {
public int CurrentView { get; set; }
public RenderViewEventArgs(int viewIndex) public RenderViewEventArgs(int viewIndex)
{ {
CurrentView = viewIndex; CurrentView = viewIndex;
} }
public int CurrentView { get; set; }
}
} }

View File

@ -1,16 +1,16 @@
using System.Collections.Generic; using System.Collections.Generic;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class SaveStateEventArgs public class SaveStateEventArgs
{ {
public Dictionary<string, object> Values { get; set; }
public SaveStateEventArgs() public SaveStateEventArgs()
{ {
Values = new Dictionary<string, object>(); Values = new Dictionary<string, object>();
} }
public Dictionary<string, object> Values { get; set; }
public void Set(string key, string value) public void Set(string key, string value)
{ {
Values[key] = value; Values[key] = value;
@ -30,10 +30,9 @@ namespace TelegramBotBase.Args
{ {
Values[key] = value; Values[key] = value;
} }
public void SetObject(string key, object value) public void SetObject(string key, object value)
{ {
Values[key] = value; Values[key] = value;
} }
}
} }

View File

@ -1,15 +1,13 @@
using TelegramBotBase.Base; using TelegramBotBase.Base;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class SaveStatesEventArgs public class SaveStatesEventArgs
{ {
public StateContainer States { get; set; }
public SaveStatesEventArgs(StateContainer states) public SaveStatesEventArgs(StateContainer states)
{ {
States = states; States = states;
} }
}
public StateContainer States { get; set; }
} }

View File

@ -1,18 +1,17 @@
using System; using System;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
public class SessionBeginEventArgs : EventArgs public class SessionBeginEventArgs : EventArgs
{ {
public SessionBeginEventArgs(long deviceId, DeviceSession device)
{
DeviceId = deviceId;
Device = device;
}
public long DeviceId { get; set; } public long DeviceId { get; set; }
public DeviceSession Device { get; set; } public DeviceSession Device { get; set; }
public SessionBeginEventArgs(long deviceId, DeviceSession device)
{
this.DeviceId = deviceId;
this.Device = device;
}
}
} }

View File

@ -1,10 +1,21 @@
using System; using System;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class SystemExceptionEventArgs : EventArgs public class SystemExceptionEventArgs : EventArgs
{ {
public SystemExceptionEventArgs()
{
}
public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error)
{
Command = command;
DeviceId = deviceId;
Device = device;
Error = error;
}
public string Command { get; set; } public string Command { get; set; }
@ -13,20 +24,4 @@ namespace TelegramBotBase.Args
public DeviceSession Device { get; set; } public DeviceSession Device { get; set; }
public Exception Error { get; set; } public Exception Error { get; set; }
public SystemExceptionEventArgs()
{
}
public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error)
{
this.Command = command;
this.DeviceId = deviceId;
this.Device = device;
Error = error;
}
}
} }

View File

@ -2,10 +2,26 @@
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Args namespace TelegramBotBase.Args;
{
public class UnhandledCallEventArgs : EventArgs public class UnhandledCallEventArgs : EventArgs
{ {
public UnhandledCallEventArgs()
{
Handled = false;
}
public UnhandledCallEventArgs(string command, string rawData, long deviceId, int messageId, Message message,
DeviceSession device) : this()
{
Command = command;
RawData = rawData;
DeviceId = deviceId;
MessageId = messageId;
Message = message;
Device = device;
}
public string Command { get; set; } public string Command { get; set; }
public long DeviceId { get; set; } public long DeviceId { get; set; }
@ -19,23 +35,4 @@ namespace TelegramBotBase.Args
public Message Message { get; set; } public Message Message { get; set; }
public bool Handled { get; set; } public bool Handled { get; set; }
public UnhandledCallEventArgs()
{
Handled = false;
}
public UnhandledCallEventArgs(string command,string rawData, long deviceId, int messageId, Message message, DeviceSession device) : this()
{
this.Command = command;
this.RawData = rawData;
this.DeviceId = deviceId;
this.MessageId = messageId;
Message = message;
this.Device = device;
}
}
} }

View File

@ -1,7 +1,6 @@
using System; using System;
namespace TelegramBotBase.Attributes namespace TelegramBotBase.Attributes;
{
/// <summary> /// <summary>
/// Declares that this class should not be getting serialized /// Declares that this class should not be getting serialized
@ -9,7 +8,4 @@ namespace TelegramBotBase.Attributes
[AttributeUsage(AttributeTargets.Class)] [AttributeUsage(AttributeTargets.Class)]
public class IgnoreState : Attribute public class IgnoreState : Attribute
{ {
}
} }

View File

@ -1,13 +1,11 @@
using System; using System;
namespace TelegramBotBase.Attributes namespace TelegramBotBase.Attributes;
{
/// <summary> /// <summary>
/// Declares that the field or property should be save and recovered an restart. /// Declares that the field or property should be save and recovered an restart.
/// </summary> /// </summary>
public class SaveState : Attribute public class SaveState : Attribute
{ {
public string Key { get; set; } public string Key { get; set; }
}
} }

View File

@ -3,8 +3,8 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
public static class Async public static class Async
{ {
public delegate Task AsyncEventHandler<TEventArgs>(object sender, TEventArgs e) where TEventArgs : EventArgs; public delegate Task AsyncEventHandler<TEventArgs>(object sender, TEventArgs e) where TEventArgs : EventArgs;
@ -12,13 +12,16 @@ namespace TelegramBotBase.Base
public static IEnumerable<AsyncEventHandler<TEventArgs>> GetHandlers<TEventArgs>( public static IEnumerable<AsyncEventHandler<TEventArgs>> GetHandlers<TEventArgs>(
this AsyncEventHandler<TEventArgs> handler) this AsyncEventHandler<TEventArgs> handler)
where TEventArgs : EventArgs where TEventArgs : EventArgs
=> handler.GetInvocationList().Cast<AsyncEventHandler<TEventArgs>>(); {
return handler.GetInvocationList().Cast<AsyncEventHandler<TEventArgs>>();
}
public static Task InvokeAllAsync<TEventArgs>(this AsyncEventHandler<TEventArgs> handler, object sender, TEventArgs e) public static Task InvokeAllAsync<TEventArgs>(this AsyncEventHandler<TEventArgs> handler, object sender,
TEventArgs e)
where TEventArgs : EventArgs where TEventArgs : EventArgs
=> Task.WhenAll( {
return Task.WhenAll(
handler.GetHandlers() handler.GetHandlers()
.Select(handleAsync => handleAsync(sender, e))); .Select(handleAsync => handleAsync(sender, e)));
} }
} }

View File

@ -1,8 +1,8 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
/// <summary> /// <summary>
/// Base class for controls /// Base class for controls
/// </summary> /// </summary>
@ -25,7 +25,6 @@ namespace TelegramBotBase.Base
/// <returns></returns> /// <returns></returns>
public virtual void Init() public virtual void Init()
{ {
} }
public virtual Task Load(MessageResult result) public virtual Task Load(MessageResult result)
@ -39,7 +38,6 @@ namespace TelegramBotBase.Base
} }
public virtual Task Render(MessageResult result) public virtual Task Render(MessageResult result)
{ {
return Task.CompletedTask; return Task.CompletedTask;
@ -58,6 +56,4 @@ namespace TelegramBotBase.Base
{ {
return Task.CompletedTask; return Task.CompletedTask;
} }
}
} }

View File

@ -7,13 +7,17 @@ using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InputFiles; using Telegram.Bot.Types.InputFiles;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
/// <summary> /// <summary>
/// Returns a class to manage attachments within messages. /// Returns a class to manage attachments within messages.
/// </summary> /// </summary>
public class DataResult : ResultBase public class DataResult : ResultBase
{ {
public DataResult(UpdateResult update)
{
UpdateData = update;
}
//public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; } //public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; }
@ -41,22 +45,18 @@ namespace TelegramBotBase.Base
/// Returns the FileId of the first reachable element. /// Returns the FileId of the first reachable element.
/// </summary> /// </summary>
public string FileId => public string FileId =>
(Document?.FileId ?? Document?.FileId ??
Audio?.FileId ?? Audio?.FileId ??
Video?.FileId ?? Video?.FileId ??
Photos.FirstOrDefault()?.FileId); Photos.FirstOrDefault()?.FileId;
public DataResult(UpdateResult update)
{
UpdateData = update;
}
public async Task<InputOnlineFile> DownloadDocument() public async Task<InputOnlineFile> DownloadDocument()
{ {
var encryptedContent = new MemoryStream(); var encryptedContent = new MemoryStream();
encryptedContent.SetLength(Document.FileSize.Value); encryptedContent.SetLength(Document.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, encryptedContent); var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId,
encryptedContent);
return new InputOnlineFile(encryptedContent, Document.FileName); return new InputOnlineFile(encryptedContent, Document.FileName);
} }
@ -167,6 +167,4 @@ namespace TelegramBotBase.Base
fs.Close(); fs.Close();
fs.Dispose(); fs.Dispose();
} }
}
} }

View File

@ -9,13 +9,32 @@ using TelegramBotBase.Form.Navigation;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
using static TelegramBotBase.Base.Async; using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Form namespace TelegramBotBase.Form;
{
/// <summary> /// <summary>
/// Base class for forms /// Base class for forms
/// </summary> /// </summary>
public class FormBase : IDisposable public class FormBase : IDisposable
{ {
private static readonly object EvInit = new();
private static readonly object EvOpened = new();
private static readonly object EvClosed = new();
public EventHandlerList Events = new();
public FormBase()
{
Controls = new List<ControlBase>();
}
public FormBase(MessageClient client) : this()
{
Client = client;
}
public NavigationController NavigationController { get; set; } public NavigationController NavigationController { get; set; }
@ -30,25 +49,14 @@ namespace TelegramBotBase.Form
public List<ControlBase> Controls { get; set; } public List<ControlBase> Controls { get; set; }
/// <summary>
public EventHandlerList Events = new EventHandlerList(); /// Cleanup
/// </summary>
public void Dispose()
private static readonly object EvInit = new object();
private static readonly object EvOpened = new object();
private static readonly object EvClosed = new object();
public FormBase()
{ {
Controls = new List<ControlBase>(); Client = null;
} Device = null;
IsDisposed = true;
public FormBase(MessageClient client) : this()
{
this.Client = client;
} }
@ -56,7 +64,9 @@ namespace TelegramBotBase.Form
{ {
var handler = Events[EvInit]?.GetInvocationList().Cast<AsyncEventHandler<InitEventArgs>>(); var handler = Events[EvInit]?.GetInvocationList().Cast<AsyncEventHandler<InitEventArgs>>();
if (handler == null) if (handler == null)
{
return; return;
}
foreach (var h in handler) foreach (var h in handler)
{ {
@ -74,12 +84,13 @@ namespace TelegramBotBase.Form
} }
public async Task OnOpened(EventArgs e) public async Task OnOpened(EventArgs e)
{ {
var handler = Events[EvOpened]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>(); var handler = Events[EvOpened]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>();
if (handler == null) if (handler == null)
{
return; return;
}
foreach (var h in handler) foreach (var h in handler)
{ {
@ -98,12 +109,13 @@ namespace TelegramBotBase.Form
} }
public async Task OnClosed(EventArgs e) public async Task OnClosed(EventArgs e)
{ {
var handler = Events[EvClosed]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>(); var handler = Events[EvClosed]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>();
if (handler == null) if (handler == null)
{
return; return;
}
foreach (var h in handler) foreach (var h in handler)
{ {
@ -173,7 +185,9 @@ namespace TelegramBotBase.Form
foreach (var b in Controls) foreach (var b in Controls)
{ {
if (!b.Enabled) if (!b.Enabled)
{
continue; continue;
}
await b.Load(message); await b.Load(message);
} }
@ -221,14 +235,18 @@ namespace TelegramBotBase.Form
foreach (var b in Controls) foreach (var b in Controls)
{ {
if (!b.Enabled) if (!b.Enabled)
{
continue; continue;
}
await b.Action(message); await b.Action(message);
if (message.Handled) if (message.Handled)
{
return; return;
} }
} }
}
/// <summary> /// <summary>
/// Gets invoked if the user has clicked a button. /// Gets invoked if the user has clicked a button.
@ -260,7 +278,9 @@ namespace TelegramBotBase.Form
foreach (var b in Controls) foreach (var b in Controls)
{ {
if (!b.Enabled) if (!b.Enabled)
{
continue; continue;
}
await b.Render(message); await b.Render(message);
} }
@ -277,7 +297,6 @@ namespace TelegramBotBase.Form
} }
/// <summary> /// <summary>
/// Navigates to a new form /// Navigates to a new form
/// </summary> /// </summary>
@ -287,7 +306,9 @@ namespace TelegramBotBase.Form
{ {
var ds = Device; var ds = Device;
if (ds == null) if (ds == null)
{
return; return;
}
ds.FormSwitched = true; ds.FormSwitched = true;
@ -301,7 +322,9 @@ namespace TelegramBotBase.Form
foreach (var b in Controls) foreach (var b in Controls)
{ {
if (!b.Enabled) if (!b.Enabled)
{
continue; continue;
}
await b.Hidden(true); await b.Hidden(true);
} }
@ -324,7 +347,9 @@ namespace TelegramBotBase.Form
{ {
var ds = Device; var ds = Device;
if (ds == null) if (ds == null)
{
return; return;
}
var parentForm = this; var parentForm = this;
@ -337,15 +362,14 @@ namespace TelegramBotBase.Form
newForm.Device = ds; newForm.Device = ds;
newForm.ParentForm = parentForm; newForm.ParentForm = parentForm;
newForm.Closed += async (s, en) => newForm.Closed += async (s, en) => { await CloseModal(newForm, parentForm); };
{
await CloseModal(newForm, parentForm);
};
foreach (var b in Controls) foreach (var b in Controls)
{ {
if (!b.Enabled) if (!b.Enabled)
{
continue; continue;
}
await b.Hidden(false); await b.Hidden(false);
} }
@ -359,10 +383,14 @@ namespace TelegramBotBase.Form
{ {
var ds = Device; var ds = Device;
if (ds == null) if (ds == null)
{
return Task.CompletedTask; return Task.CompletedTask;
}
if (modalForm == null) if (modalForm == null)
{
throw new Exception("No modal form"); throw new Exception("No modal form");
}
ds.FormSwitched = true; ds.FormSwitched = true;
@ -380,7 +408,9 @@ namespace TelegramBotBase.Form
{ {
//Duplicate check //Duplicate check
if (Controls.Contains(control)) if (Controls.Contains(control))
{
throw new ArgumentException("Control has been already added."); throw new ArgumentException("Control has been already added.");
}
control.Id = Controls.Count + 1; control.Id = Controls.Count + 1;
control.Device = Device; control.Device = Device;
@ -396,7 +426,9 @@ namespace TelegramBotBase.Form
public void RemoveControl(ControlBase control) public void RemoveControl(ControlBase control)
{ {
if (!Controls.Contains(control)) if (!Controls.Contains(control))
{
return; return;
}
control.Cleanup().Wait(); control.Cleanup().Wait();
@ -415,15 +447,4 @@ namespace TelegramBotBase.Form
Controls.Remove(c); Controls.Remove(c);
} }
} }
/// <summary>
/// Cleanup
/// </summary>
public void Dispose()
{
Client = null;
Device = null;
IsDisposed = true;
}
}
} }

View File

@ -10,35 +10,27 @@ using Telegram.Bot.Exceptions;
using Telegram.Bot.Extensions.Polling; using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types; using Telegram.Bot.Types;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
/// <summary> /// <summary>
/// Base class for message handling /// Base class for message handling
/// </summary> /// </summary>
public class MessageClient public class MessageClient
{ {
private static readonly object EvOnMessageLoop = new();
private static object __evOnMessage = new();
public string ApiKey { get; set; } private static object __evOnMessageEdit = new();
public ITelegramBotClient TelegramClient { get; set; } private static object __evCallbackQuery = new();
private EventHandlerList Events { get; set; } = new EventHandlerList();
private static readonly object EvOnMessageLoop = new object();
private static object __evOnMessage = new object();
private static object __evOnMessageEdit = new object();
private static object __evCallbackQuery = new object();
private CancellationTokenSource _cancellationTokenSource; private CancellationTokenSource _cancellationTokenSource;
public MessageClient(string apiKey) public MessageClient(string apiKey)
{ {
this.ApiKey = apiKey; ApiKey = apiKey;
TelegramClient = new TelegramBotClient(apiKey); TelegramClient = new TelegramBotClient(apiKey);
Prepare(); Prepare();
@ -46,7 +38,7 @@ namespace TelegramBotBase.Base
public MessageClient(string apiKey, HttpClient proxy) public MessageClient(string apiKey, HttpClient proxy)
{ {
this.ApiKey = apiKey; ApiKey = apiKey;
TelegramClient = new TelegramBotClient(apiKey, proxy); TelegramClient = new TelegramBotClient(apiKey, proxy);
@ -54,10 +46,9 @@ namespace TelegramBotBase.Base
} }
public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null) public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null)
{ {
this.ApiKey = apiKey; ApiKey = apiKey;
var proxy = new WebProxy(proxyUrl) var proxy = new WebProxy(proxyUrl)
{ {
@ -81,7 +72,7 @@ namespace TelegramBotBase.Base
/// <param name="proxyPort">i.e. 10000</param> /// <param name="proxyPort">i.e. 10000</param>
public MessageClient(string apiKey, string proxyHost, int proxyPort) public MessageClient(string apiKey, string proxyHost, int proxyPort)
{ {
this.ApiKey = apiKey; ApiKey = apiKey;
var proxy = new WebProxy(proxyHost, proxyPort); var proxy = new WebProxy(proxyHost, proxyPort);
@ -95,31 +86,36 @@ namespace TelegramBotBase.Base
} }
public MessageClient(string apiKey, TelegramBotClient client) public MessageClient(string apiKey, TelegramBotClient client)
{ {
this.ApiKey = apiKey; ApiKey = apiKey;
TelegramClient = client; TelegramClient = client;
Prepare(); Prepare();
} }
public string ApiKey { get; set; }
public ITelegramBotClient TelegramClient { get; set; }
private EventHandlerList Events { get; } = new();
public void Prepare() public void Prepare()
{ {
TelegramClient.Timeout = new TimeSpan(0, 0, 30); TelegramClient.Timeout = new TimeSpan(0, 0, 30);
} }
public void StartReceiving() public void StartReceiving()
{ {
_cancellationTokenSource = new CancellationTokenSource(); _cancellationTokenSource = new CancellationTokenSource();
var receiverOptions = new ReceiverOptions(); var receiverOptions = new ReceiverOptions();
TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, _cancellationTokenSource.Token); TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions,
_cancellationTokenSource.Token);
} }
public void StopReceiving() public void StopReceiving()
@ -135,7 +131,8 @@ namespace TelegramBotBase.Base
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception,
CancellationToken cancellationToken)
{ {
if (exception is ApiRequestException exApi) if (exception is ApiRequestException exApi)
{ {
@ -145,6 +142,7 @@ namespace TelegramBotBase.Base
{ {
Console.WriteLine(exception.ToString()); Console.WriteLine(exception.ToString());
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -164,7 +162,8 @@ namespace TelegramBotBase.Base
/// </summary> /// </summary>
/// <param name="botcommands"></param> /// <param name="botcommands"></param>
/// <returns></returns> /// <returns></returns>
public async Task SetBotCommands(List<BotCommand> botcommands, BotCommandScope scope = null, string languageCode = null) public async Task SetBotCommands(List<BotCommand> botcommands, BotCommandScope scope = null,
string languageCode = null)
{ {
await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode); await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode);
} }
@ -181,8 +180,6 @@ namespace TelegramBotBase.Base
#region "Events" #region "Events"
public event Async.AsyncEventHandler<UpdateResult> MessageLoop public event Async.AsyncEventHandler<UpdateResult> MessageLoop
{ {
add => Events.AddHandler(EvOnMessageLoop, value); add => Events.AddHandler(EvOnMessageLoop, value);
@ -194,9 +191,5 @@ namespace TelegramBotBase.Base
(Events[EvOnMessageLoop] as Async.AsyncEventHandler<UpdateResult>)?.Invoke(this, update); (Events[EvOnMessageLoop] as Async.AsyncEventHandler<UpdateResult>)?.Invoke(this, update);
} }
#endregion #endregion
}
} }

View File

@ -5,10 +5,18 @@ using Newtonsoft.Json;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
public class MessageResult : ResultBase public class MessageResult : ResultBase
{ {
internal MessageResult()
{
}
public MessageResult(Update update)
{
UpdateData = update;
}
public Update UpdateData { get; set; } public Update UpdateData { get; set; }
@ -40,22 +48,25 @@ namespace TelegramBotBase.Base
/// <summary> /// <summary>
/// Is this an action ? (i.e. button click) /// Is this an action ? (i.e. button click)
/// </summary> /// </summary>
public bool IsAction => (UpdateData.CallbackQuery != null); public bool IsAction => UpdateData.CallbackQuery != null;
/// <summary> /// <summary>
/// Is this a command ? Starts with a slash '/' and a command /// Is this a command ? Starts with a slash '/' and a command
/// </summary> /// </summary>
public bool IsBotCommand => (MessageText.StartsWith("/")); public bool IsBotCommand => MessageText.StartsWith("/");
/// <summary> /// <summary>
/// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => 123,456,789) /// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 =>
/// 123,456,789)
/// </summary> /// </summary>
public List<string> BotCommandParameters public List<string> BotCommandParameters
{ {
get get
{ {
if (!IsBotCommand) if (!IsBotCommand)
{
return new List<string>(); return new List<string>();
}
//Split by empty space and skip first entry (command itself), return as list //Split by empty space and skip first entry (command itself), return as list
return MessageText.Split(' ').Skip(1).ToList(); return MessageText.Split(' ').Skip(1).ToList();
@ -70,7 +81,9 @@ namespace TelegramBotBase.Base
get get
{ {
if (!IsBotCommand) if (!IsBotCommand)
{
return null; return null;
}
return MessageText.Split(' ')[0]; return MessageText.Split(' ')[0];
} }
@ -97,7 +110,6 @@ namespace TelegramBotBase.Base
} }
catch catch
{ {
} }
return null; return null;
@ -121,20 +133,6 @@ namespace TelegramBotBase.Base
} }
catch catch
{ {
} }
} }
internal MessageResult()
{
}
public MessageResult(Update update)
{
UpdateData = update;
}
}
} }

View File

@ -4,15 +4,11 @@ using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
public class ResultBase : EventArgs public class ResultBase : EventArgs
{ {
public DeviceSession Device public DeviceSession Device { get; set; }
{
get;
set;
}
public virtual long DeviceId { get; set; } public virtual long DeviceId { get; set; }
@ -39,13 +35,11 @@ namespace TelegramBotBase.Base
{ {
try try
{ {
await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, (messageId == -1 ? MessageId : messageId)); await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId,
messageId == -1 ? MessageId : messageId);
} }
catch catch
{ {
} }
} }
}
} }

View File

@ -1,32 +1,24 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
public class StateContainer public class StateContainer
{ {
public List<StateEntry> States { get; set; }
public List<long> ChatIds
{
get
{
return States.Where(a => a.DeviceId > 0).Select(a => a.DeviceId).ToList();
}
}
public List<long> GroupIds
{
get
{
return States.Where(a => a.DeviceId < 0).Select(a => a.DeviceId).ToList();
}
}
public StateContainer() public StateContainer()
{ {
States = new List<StateEntry>(); States = new List<StateEntry>();
} }
public List<StateEntry> States { get; set; }
public List<long> ChatIds
{
get { return States.Where(a => a.DeviceId > 0).Select(a => a.DeviceId).ToList(); }
}
public List<long> GroupIds
{
get { return States.Where(a => a.DeviceId < 0).Select(a => a.DeviceId).ToList(); }
} }
} }

View File

@ -1,12 +1,16 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
[DebuggerDisplay("Device: {DeviceId}, {FormUri}")] [DebuggerDisplay("Device: {DeviceId}, {FormUri}")]
public class StateEntry public class StateEntry
{ {
public StateEntry()
{
Values = new Dictionary<string, object>();
}
/// <summary> /// <summary>
/// Contains the DeviceId of the entry. /// Contains the DeviceId of the entry.
/// </summary> /// </summary>
@ -31,11 +35,4 @@ namespace TelegramBotBase.Base
/// Contains the assembly, where to find that form. /// Contains the assembly, where to find that form.
/// </summary> /// </summary>
public string QualifiedName { get; set; } public string QualifiedName { get; set; }
public StateEntry()
{
Values = new Dictionary<string, object>();
}
}
} }

View File

@ -1,16 +1,14 @@
using Telegram.Bot.Types; using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base;
{
public class UpdateResult : ResultBase public class UpdateResult : ResultBase
{ {
public UpdateResult(Update rawData, DeviceSession device) public UpdateResult(Update rawData, DeviceSession device)
{ {
RawData = rawData; RawData = rawData;
Device = device; Device = device;
} }
/// <summary> /// <summary>
@ -31,5 +29,3 @@ namespace TelegramBotBase.Base
?? RawData?.EditedChannelPost ?? RawData?.EditedChannelPost
?? RawData?.CallbackQuery?.Message; ?? RawData?.CallbackQuery?.Message;
} }
}

View File

@ -2,30 +2,42 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.MessageLoops;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces; using TelegramBotBase.Interfaces;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
using Console = TelegramBotBase.Tools.Console;
namespace TelegramBotBase;
namespace TelegramBotBase
{
/// <summary> /// <summary>
/// Bot base class for full Device/Context and Messagehandling /// Bot base class for full Device/Context and Messagehandling
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class BotBase public class BotBase
{ {
public BotBase()
{
SystemSettings = new Dictionary<ESettings, uint>();
SetSetting(ESettings.MaxNumberOfRetries, 5);
SetSetting(ESettings.NavigationMaximum, 10);
SetSetting(ESettings.LogAllMessages, false);
SetSetting(ESettings.SkipAllMessages, false);
SetSetting(ESettings.SaveSessionsOnConsoleExit, false);
BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>();
Sessions = new SessionBase
{
BotBase = this
};
}
public MessageClient Client { get; set; } public MessageClient Client { get; set; }
/// <summary> /// <summary>
@ -41,26 +53,7 @@ namespace TelegramBotBase
/// <summary> /// <summary>
/// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start /// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start
/// </summary> /// </summary>
public Dictionary<BotCommandScope, List<BotCommand>> BotCommandScopes { get; set; } = new Dictionary<BotCommandScope, List<BotCommand>>(); public Dictionary<BotCommandScope, List<BotCommand>> BotCommandScopes { get; set; } = new();
#region "Events"
private readonly EventHandlerList _events = new EventHandlerList();
private static readonly object EvSessionBegins = new object();
private static readonly object EvMessage = new object();
private static object __evSystemCall = new object();
public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e);
private static readonly object EvException = new object();
private static readonly object EvUnhandledCall = new object();
#endregion
/// <summary> /// <summary>
@ -81,26 +74,7 @@ namespace TelegramBotBase
/// <summary> /// <summary>
/// All internal used settings. /// All internal used settings.
/// </summary> /// </summary>
public Dictionary<ESettings, uint> SystemSettings { get; private set; } public Dictionary<ESettings, uint> SystemSettings { get; }
public BotBase()
{
SystemSettings = new Dictionary<ESettings, uint>();
SetSetting(ESettings.MaxNumberOfRetries, 5);
SetSetting(ESettings.NavigationMaximum, 10);
SetSetting(ESettings.LogAllMessages, false);
SetSetting(ESettings.SkipAllMessages, false);
SetSetting(ESettings.SaveSessionsOnConsoleExit, false);
BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>();
Sessions = new SessionBase
{
BotBase = this
};
}
/// <summary> /// <summary>
@ -109,7 +83,9 @@ namespace TelegramBotBase
public void Start() public void Start()
{ {
if (Client == null) if (Client == null)
{
return; return;
}
Client.MessageLoop += Client_MessageLoop; Client.MessageLoop += Client_MessageLoop;
@ -122,10 +98,7 @@ namespace TelegramBotBase
//Enable auto session saving //Enable auto session saving
if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false)) if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false))
{ {
Tools.Console.SetHandler(() => Console.SetHandler(() => { Sessions.SaveSessionStates(); });
{
Sessions.SaveSessionStates();
});
} }
DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5); DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5);
@ -161,7 +134,6 @@ namespace TelegramBotBase
await MessageLoopFactory.MessageLoop(this, ds, e, mr); await MessageLoopFactory.MessageLoop(this, ds, e, mr);
mr.IsFirstHandler = false; mr.IsFirstHandler = false;
} while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10)); } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10));
} }
@ -172,7 +144,9 @@ namespace TelegramBotBase
public void Stop() public void Stop()
{ {
if (Client == null) if (Client == null)
{
return; return;
}
Client.MessageLoop -= Client_MessageLoop; Client.MessageLoop -= Client_MessageLoop;
@ -190,7 +164,9 @@ namespace TelegramBotBase
public async Task SentToAll(string message) public async Task SentToAll(string message)
{ {
if (Client == null) if (Client == null)
{
return; return;
}
foreach (var s in Sessions.SessionList) foreach (var s in Sessions.SessionList)
{ {
@ -199,16 +175,16 @@ namespace TelegramBotBase
} }
/// <summary> /// <summary>
/// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. /// This will invoke the full message loop for the device even when no "userevent" like message or action has been
/// raised.
/// </summary> /// </summary>
/// <param name="deviceId">Contains the device/chat id of the device to update.</param> /// <param name="deviceId">Contains the device/chat id of the device to update.</param>
public async Task InvokeMessageLoop(long deviceId) public async Task InvokeMessageLoop(long deviceId)
{ {
var mr = new MessageResult var mr = new MessageResult
{ {
UpdateData = new Update() UpdateData = new Update
{ {
Message = new Message() Message = new Message()
} }
@ -218,7 +194,8 @@ namespace TelegramBotBase
} }
/// <summary> /// <summary>
/// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. /// This will invoke the full message loop for the device even when no "userevent" like message or action has been
/// raised.
/// </summary> /// </summary>
/// <param name="deviceId">Contains the device/chat id of the device to update.</param> /// <param name="deviceId">Contains the device/chat id of the device to update.</param>
/// <param name="e"></param> /// <param name="e"></param>
@ -265,7 +242,6 @@ namespace TelegramBotBase
{ {
await Client.DeleteBotCommands(bs.Key); await Client.DeleteBotCommands(bs.Key);
} }
} }
} }
@ -279,8 +255,10 @@ namespace TelegramBotBase
foreach (var scope in BotCommandScopes) foreach (var scope in BotCommandScopes)
{ {
if (scope.Value.Any(a => "/" + a.Command == command)) if (scope.Value.Any(a => "/" + a.Command == command))
{
return true; return true;
} }
}
return false; return false;
} }
@ -302,7 +280,7 @@ namespace TelegramBotBase
/// <param name="value"></param> /// <param name="value"></param>
public void SetSetting(ESettings set, bool value) public void SetSetting(ESettings set, bool value)
{ {
SystemSettings[set] = (value ? 1u : 0u); SystemSettings[set] = value ? 1u : 0u;
} }
/// <summary> /// <summary>
@ -314,7 +292,9 @@ namespace TelegramBotBase
public uint GetSetting(ESettings set, uint defaultValue) public uint GetSetting(ESettings set, uint defaultValue)
{ {
if (!SystemSettings.ContainsKey(set)) if (!SystemSettings.ContainsKey(set))
{
return defaultValue; return defaultValue;
}
return SystemSettings[set]; return SystemSettings[set];
} }
@ -328,17 +308,37 @@ namespace TelegramBotBase
public bool GetSetting(ESettings set, bool defaultValue) public bool GetSetting(ESettings set, bool defaultValue)
{ {
if (!SystemSettings.ContainsKey(set)) if (!SystemSettings.ContainsKey(set))
{
return defaultValue; return defaultValue;
}
return SystemSettings[set] == 0u ? false : true; return SystemSettings[set] == 0u ? false : true;
} }
#region "Events"
private readonly EventHandlerList _events = new();
private static readonly object EvSessionBegins = new();
private static readonly object EvMessage = new();
private static object __evSystemCall = new();
public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e);
private static readonly object EvException = new();
private static readonly object EvUnhandledCall = new();
#endregion
#region "Events" #region "Events"
/// <summary> /// <summary>
/// Will be called if a session/context gets started /// Will be called if a session/context gets started
/// </summary> /// </summary>
public event EventHandler<SessionBeginEventArgs> SessionBegins public event EventHandler<SessionBeginEventArgs> SessionBegins
{ {
add => _events.AddHandler(EvSessionBegins, value); add => _events.AddHandler(EvSessionBegins, value);
@ -348,7 +348,6 @@ namespace TelegramBotBase
public void OnSessionBegins(SessionBeginEventArgs e) public void OnSessionBegins(SessionBeginEventArgs e)
{ {
(_events[EvSessionBegins] as EventHandler<SessionBeginEventArgs>)?.Invoke(this, e); (_events[EvSessionBegins] as EventHandler<SessionBeginEventArgs>)?.Invoke(this, e);
} }
/// <summary> /// <summary>
@ -363,7 +362,6 @@ namespace TelegramBotBase
public void OnMessage(MessageIncomeEventArgs e) public void OnMessage(MessageIncomeEventArgs e)
{ {
(_events[EvMessage] as EventHandler<MessageIncomeEventArgs>)?.Invoke(this, e); (_events[EvMessage] as EventHandler<MessageIncomeEventArgs>)?.Invoke(this, e);
} }
/// <summary> /// <summary>
@ -375,8 +373,10 @@ namespace TelegramBotBase
public async Task OnBotCommand(BotCommandEventArgs e) public async Task OnBotCommand(BotCommandEventArgs e)
{ {
if (BotCommand != null) if (BotCommand != null)
{
await BotCommand(this, e); await BotCommand(this, e);
} }
}
/// <summary> /// <summary>
/// Will be called on an inner exception /// Will be called on an inner exception
@ -390,7 +390,6 @@ namespace TelegramBotBase
public void OnException(SystemExceptionEventArgs e) public void OnException(SystemExceptionEventArgs e)
{ {
(_events[EvException] as EventHandler<SystemExceptionEventArgs>)?.Invoke(this, e); (_events[EvException] as EventHandler<SystemExceptionEventArgs>)?.Invoke(this, e);
} }
/// <summary> /// <summary>
@ -405,10 +404,7 @@ namespace TelegramBotBase
public void OnUnhandledCall(UnhandledCallEventArgs e) public void OnUnhandledCall(UnhandledCallEventArgs e)
{ {
(_events[EvUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e); (_events[EvUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
} }
#endregion #endregion
}
} }

View File

@ -13,28 +13,52 @@ using TelegramBotBase.Localizations;
using TelegramBotBase.MessageLoops; using TelegramBotBase.MessageLoops;
using TelegramBotBase.States; using TelegramBotBase.States;
namespace TelegramBotBase.Builder namespace TelegramBotBase.Builder;
{
public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, ILanguageSelectionStage public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage,
IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage,
ILanguageSelectionStage
{ {
private string _apiKey; private string _apiKey;
private MessageClient _client;
private IStartFormFactory _factory; private IStartFormFactory _factory;
private MessageClient _client; private IMessageLoopFactory _messageLoopFactory;
private IStateMachine _statemachine;
private BotBaseBuilder()
{
}
/// <summary> /// <summary>
/// Contains different Botcommands for different areas. /// Contains different Botcommands for different areas.
/// </summary> /// </summary>
private Dictionary<BotCommandScope, List<BotCommand>> BotCommandScopes { get; set; } = new Dictionary<BotCommandScope, List<BotCommand>>(); private Dictionary<BotCommandScope, List<BotCommand>> BotCommandScopes { get; } = new();
private IStateMachine _statemachine;
private IMessageLoopFactory _messageLoopFactory; public BotBase Build()
private BotBaseBuilder()
{ {
var bb = new BotBase
{
ApiKey = _apiKey,
StartFormFactory = _factory,
Client = _client
};
bb.Sessions.Client = bb.Client;
bb.BotCommandScopes = BotCommandScopes;
bb.StateMachine = _statemachine;
bb.MessageLoopFactory = _messageLoopFactory;
bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall;
return bb;
} }
public static IAPIKeySelectionStage Create() public static IAPIKeySelectionStage Create()
@ -138,7 +162,8 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage CustomMessageLoop<T>() public IStartFormSelectionStage CustomMessageLoop<T>()
where T : class, new() where T : class, new()
{ {
_messageLoopFactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory; _messageLoopFactory =
typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory;
return this; return this;
} }
@ -249,7 +274,6 @@ namespace TelegramBotBase.Builder
return this; return this;
} }
#endregion #endregion
@ -265,7 +289,6 @@ namespace TelegramBotBase.Builder
BotCommandScopes.Start("Starts the bot"); BotCommandScopes.Start("Starts the bot");
return this; return this;
} }
public ISessionSerializationStage DefaultCommands() public ISessionSerializationStage DefaultCommands()
@ -346,29 +369,4 @@ namespace TelegramBotBase.Builder
} }
#endregion #endregion
public BotBase Build()
{
var bb = new BotBase
{
ApiKey = _apiKey,
StartFormFactory = _factory,
Client = _client
};
bb.Sessions.Client = bb.Client;
bb.BotCommandScopes = BotCommandScopes;
bb.StateMachine = _statemachine;
bb.MessageLoopFactory = _messageLoopFactory;
bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall;
return bb;
}
}
} }

View File

@ -2,8 +2,8 @@
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Interfaces; using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces;
{
public interface IAPIKeySelectionStage public interface IAPIKeySelectionStage
{ {
/// <summary> /// <summary>
@ -40,4 +40,3 @@ namespace TelegramBotBase.Builder.Interfaces
/// <returns></returns> /// <returns></returns>
IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory); IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory);
} }
}

View File

@ -2,8 +2,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using Telegram.Bot.Types; using Telegram.Bot.Types;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces;
{
public interface IBotCommandsStage public interface IBotCommandsStage
{ {
/// <summary> /// <summary>
@ -32,9 +32,5 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary> /// </summary>
/// <param name="action"></param> /// <param name="action"></param>
/// <returns></returns> /// <returns></returns>
ISessionSerializationStage CustomCommands(Action<Dictionary<BotCommandScope, List<BotCommand>>> action); ISessionSerializationStage CustomCommands(Action<Dictionary<BotCommandScope, List<BotCommand>>> action);
}
} }

View File

@ -1,7 +1,6 @@
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces;
{
public interface IBuildingStage public interface IBuildingStage
{ {
BotBase Build(); BotBase Build();
} }
}

View File

@ -1,10 +1,9 @@
using TelegramBotBase.Localizations; using TelegramBotBase.Localizations;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces;
{
public interface ILanguageSelectionStage public interface ILanguageSelectionStage
{ {
/// <summary> /// <summary>
/// Selects the default language for control usage. (English) /// Selects the default language for control usage. (English)
/// </summary> /// </summary>
@ -28,6 +27,4 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
IBuildingStage Custom(Localization language); IBuildingStage Custom(Localization language);
}
} }

View File

@ -1,10 +1,9 @@
using TelegramBotBase.Interfaces; using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces;
{
public interface IMessageLoopSelectionStage public interface IMessageLoopSelectionStage
{ {
/// <summary> /// <summary>
/// Chooses a default message loop. /// Chooses a default message loop.
/// </summary> /// </summary>
@ -34,7 +33,4 @@ namespace TelegramBotBase.Builder.Interfaces
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <returns></returns> /// <returns></returns>
IStartFormSelectionStage CustomMessageLoop<T>() where T : class, new(); IStartFormSelectionStage CustomMessageLoop<T>() where T : class, new();
}
} }

View File

@ -1,11 +1,10 @@
using System.Net.Http; using System.Net.Http;
using Telegram.Bot; using Telegram.Bot;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces;
{
public interface INetworkingSelectionStage public interface INetworkingSelectionStage
{ {
/// <summary> /// <summary>
/// Chooses a proxy as network configuration. /// Chooses a proxy as network configuration.
/// </summary> /// </summary>
@ -42,7 +41,4 @@ namespace TelegramBotBase.Builder.Interfaces
/// <param name="client"></param> /// <param name="client"></param>
/// <returns></returns> /// <returns></returns>
IBotCommandsStage WithHttpClient(HttpClient client); IBotCommandsStage WithHttpClient(HttpClient client);
}
} }

View File

@ -1,7 +1,7 @@
using TelegramBotBase.Interfaces; using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces;
{
public interface ISessionSerializationStage public interface ISessionSerializationStage
{ {
/// <summary> /// <summary>
@ -41,6 +41,4 @@ namespace TelegramBotBase.Builder.Interfaces
/// <param name="path"></param> /// <param name="path"></param>
/// <returns></returns> /// <returns></returns>
ILanguageSelectionStage UseXML(string path); ILanguageSelectionStage UseXML(string path);
}
} }

View File

@ -2,11 +2,10 @@
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Interfaces; using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Builder.Interfaces namespace TelegramBotBase.Builder.Interfaces;
{
public interface IStartFormSelectionStage public interface IStartFormSelectionStage
{ {
/// <summary> /// <summary>
/// Chooses a start form type which will be used for new sessions. /// Chooses a start form type which will be used for new sessions.
/// </summary> /// </summary>
@ -43,6 +42,4 @@ namespace TelegramBotBase.Builder.Interfaces
/// <param name="factory"></param> /// <param name="factory"></param>
/// <returns></returns> /// <returns></returns>
INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory); INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory);
}
} }

View File

@ -2,8 +2,8 @@
using System.Linq; using System.Linq;
using Telegram.Bot.Types; using Telegram.Bot.Types;
namespace TelegramBotBase.Commands namespace TelegramBotBase.Commands;
{
public static class Extensions public static class Extensions
{ {
/// <summary> /// <summary>
@ -12,7 +12,8 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="command"></param> /// <param name="command"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void Add(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description, BotCommandScope scope = null) public static void Add(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command,
string description, BotCommandScope scope = null)
{ {
if (scope == null) if (scope == null)
{ {
@ -27,7 +28,7 @@ namespace TelegramBotBase.Commands
} }
else else
{ {
cmds.Add(scope, new List<BotCommand> { new BotCommand { Command = command, Description = description } }); cmds.Add(scope, new List<BotCommand> { new() { Command = command, Description = description } });
} }
} }
@ -61,33 +62,48 @@ namespace TelegramBotBase.Commands
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void Start(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description) => Add(cmds, "start", description); public static void Start(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description)
{
Add(cmds, "start", description);
}
/// <summary> /// <summary>
/// Adding the default /help command with a description. /// Adding the default /help command with a description.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void Help(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description) => Add(cmds, "help", description); public static void Help(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description)
{
Add(cmds, "help", description);
}
/// <summary> /// <summary>
/// Adding the default /settings command with a description. /// Adding the default /settings command with a description.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void Settings(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description) => Add(cmds, "settings", description); public static void Settings(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description)
{
Add(cmds, "settings", description);
}
/// <summary> /// <summary>
/// Clears all default commands. /// Clears all default commands.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
public static void ClearDefaultCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds); public static void ClearDefaultCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds)
{
Clear(cmds);
}
/// <summary> /// <summary>
/// Clears all commands of a specific device. /// Clears all commands of a specific device.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
public static void ClearChatCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long deviceId) => Clear(cmds, new BotCommandScopeChat { ChatId = deviceId }); public static void ClearChatCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long deviceId)
{
Clear(cmds, new BotCommandScopeChat { ChatId = deviceId });
}
/// <summary> /// <summary>
/// Adding a chat command with a description. /// Adding a chat command with a description.
@ -95,7 +111,11 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="command"></param> /// <param name="command"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void AddChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long deviceId, string command, string description) => Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId }); public static void AddChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long deviceId,
string command, string description)
{
Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId });
}
/// <summary> /// <summary>
/// Adding a group command with a description. /// Adding a group command with a description.
@ -103,13 +123,20 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="command"></param> /// <param name="command"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void AddGroupCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllGroupChats()); public static void AddGroupCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command,
string description)
{
Add(cmds, command, description, new BotCommandScopeAllGroupChats());
}
/// <summary> /// <summary>
/// Clears all group commands. /// Clears all group commands.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
public static void ClearGroupCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds, new BotCommandScopeAllGroupChats()); public static void ClearGroupCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds)
{
Clear(cmds, new BotCommandScopeAllGroupChats());
}
/// <summary> /// <summary>
/// Adding group admin command with a description. /// Adding group admin command with a description.
@ -117,13 +144,20 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="command"></param> /// <param name="command"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void AddGroupAdminCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllChatAdministrators()); public static void AddGroupAdminCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command,
string description)
{
Add(cmds, command, description, new BotCommandScopeAllChatAdministrators());
}
/// <summary> /// <summary>
/// Clears all group admin commands. /// Clears all group admin commands.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
public static void ClearGroupAdminCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds, new BotCommandScopeAllChatAdministrators()); public static void ClearGroupAdminCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds)
{
Clear(cmds, new BotCommandScopeAllChatAdministrators());
}
/// <summary> /// <summary>
/// Adding a privat command with a description. /// Adding a privat command with a description.
@ -131,12 +165,18 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param> /// <param name="cmds"></param>
/// <param name="command"></param> /// <param name="command"></param>
/// <param name="description"></param> /// <param name="description"></param>
public static void AddPrivateChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllPrivateChats()); public static void AddPrivateChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds,
string command, string description)
{
Add(cmds, command, description, new BotCommandScopeAllPrivateChats());
}
/// <summary> /// <summary>
/// Clears all private commands. /// Clears all private commands.
/// </summary> /// </summary>
/// <param name="cmds"></param> /// <param name="cmds"></param>
public static void ClearPrivateChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds, new BotCommandScopeAllPrivateChats()); public static void ClearPrivateChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds)
{
Clear(cmds, new BotCommandScopeAllPrivateChats());
} }
} }

Some files were not shown because too many files have changed in this diff Show More