├── .github └── workflows │ └── dotnetcore.yml ├── .gitignore ├── Config.Translation.cs ├── Config.cs ├── DB.cs ├── LICENSE ├── PollBot.csproj ├── PollBot.sln ├── Program.cs ├── README.md ├── StringEx.cs └── example.yaml /.github/workflows/dotnetcore.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | os: [win-x64, linux-x64] 11 | 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Setup .NET Core 15 | uses: actions/setup-dotnet@v1 16 | with: 17 | dotnet-version: 3.1.100 18 | - name: Build with dotnet 19 | run: dotnet build -c Release 20 | - name: Publish 21 | run: dotnet publish -c Release -r ${{ matrix.os }} -o dist --self-contained 22 | - name: Upload artifact 23 | uses: actions/upload-artifact@v1.0.0 24 | with: 25 | name: ${{ matrix.os }} 26 | path: dist 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | 352 | launchSettings.json -------------------------------------------------------------------------------- /Config.Translation.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using YamlDotNet.Serialization; 3 | 4 | namespace PollBot { 5 | 6 | public partial class Config { 7 | 8 | public class Translation { 9 | 10 | [Required, YamlMember(Alias = "approve")] 11 | public string Approve { get; set; } = "approve"; 12 | 13 | [Required, YamlMember(Alias = "reject")] 14 | public string Reject { get; set; } = "reject"; 15 | 16 | [Required, YamlMember(Alias = "duplicate")] 17 | public string Duplicate { get; set; } = "duplicate"; 18 | 19 | [Required, YamlMember(Alias = "approved")] 20 | public string Approved { get; set; } = "approved"; 21 | 22 | [Required, YamlMember(Alias = "approvedby")] 23 | public string ApprovedBy { get; set; } = "approvedby"; 24 | 25 | [Required, YamlMember(Alias = "rejected")] 26 | public string Rejected { get; set; } = "rejected"; 27 | 28 | [Required, YamlMember(Alias = "rejectedby")] 29 | public string RejectedBy { get; set; } = "rejectedby"; 30 | 31 | [Required, YamlMember(Alias = "stats")] 32 | public string Stats { get; set; } = "stats"; 33 | 34 | [Required, YamlMember(Alias = "help")] 35 | public string Help { get; set; } = "help"; 36 | 37 | [Required, YamlMember(Alias = "error-format")] 38 | public string FormatError { get; set; } = "error-format"; 39 | 40 | [Required, YamlMember(Alias = "error-disallow")] 41 | public string DisallowError { get; set; } = "error-disallow"; 42 | 43 | [Required, YamlMember(Alias = "error-reject")] 44 | public string RejectError { get; set; } = "error-reject"; 45 | 46 | [Required, YamlMember(Alias = "error-changed")] 47 | public string HashMisMatchError { get; set; } = "error-changed"; 48 | 49 | [Required, YamlMember(Alias = "error-permission")] 50 | public string PermissionError { get; set; } = "error-permission"; 51 | 52 | [Required, YamlMember(Alias = "error-permissionwithauthor")] 53 | public string PermissionWithAuthorError { get; set; } = "error-permissionwithauthor"; 54 | 55 | [Required, YamlMember(Alias = "error-exception")] 56 | public string ExceptionError { get; set; } = "error-exception"; 57 | 58 | [Required, YamlMember(Alias = "error-noreply")] 59 | public string NoReplyError { get; set; } = "error-noreply"; 60 | 61 | [Required, YamlMember(Alias = "error-notpoll")] 62 | public string NotPollError { get; set; } = "error-notpoll"; 63 | 64 | [Required, YamlMember(Alias = "error-notclosed")] 65 | public string NotClosedError { get; set; } = "error-notclosed"; 66 | 67 | [Required, YamlMember(Alias = "error-notquiz")] 68 | public string NotQuizError { get; set; } = "error-notquiz"; 69 | 70 | [Required, YamlMember(Alias = "error-questiontoolong")] 71 | public string QuestionTooLongError { get; set; } = "error-questiontoolong"; 72 | 73 | [Required, YamlMember(Alias = "error-optiontoolong")] 74 | public string OptionTooLongError { get; set; } = "error-optiontoolong"; 75 | 76 | [Required, YamlMember(Alias = "error-wrongoptionsize")] 77 | public string WrongOptionSizeError { get; set; } = "error-wrongoptionsize"; 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /Config.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.ComponentModel.DataAnnotations; 3 | using YamlDotNet.Serialization; 4 | 5 | namespace PollBot { 6 | 7 | public partial class Config { 8 | 9 | [Required, YamlMember(Alias = "token")] 10 | public string TelegramToken { get; set; } = ""; 11 | 12 | [YamlMember(Alias = "debug-mode")] 13 | public bool DebugMode { get; set; } = false; 14 | 15 | [Required, YamlMember(Alias = "main-id")] 16 | public string MainChatId { get; set; } 17 | 18 | [Required, YamlMember(Alias = "send-id")] 19 | public string SendChatId { get; set; } 20 | 21 | [Required, YamlMember(Alias = "database")] 22 | public string Database { get; set; } = ""; 23 | 24 | [Required, YamlMember(Alias = "delete-origin")] 25 | public bool DeleteOrigin { get; set; } = false; 26 | 27 | [Required, YamlMember(Alias = "admin-direct-send")] 28 | public bool DirectSend { get; set; } = true; 29 | 30 | [YamlIgnore] 31 | public IEnumerable Admins { get; set; } 32 | 33 | [Required, YamlMember(Alias = "texts")] 34 | public Translation translation; 35 | } 36 | } -------------------------------------------------------------------------------- /DB.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data.SQLite; 4 | 5 | namespace PollBot { 6 | 7 | internal class DB : IDisposable { 8 | private readonly SQLiteConnection connection; 9 | 10 | public DB(string conn) { 11 | connection = new SQLiteConnection(conn); 12 | connection.Open(); 13 | using var trans = connection.BeginTransaction(); 14 | using var cmd = new SQLiteCommand { 15 | Connection = connection, 16 | CommandText = "CREATE TABLE IF NOT EXISTS stat(id INTEGER PRIMARY KEY, time DATETIME DEFAULT CURRENT_TIMESTAMP, user INTEGER, content TEXT, msgid INTEGER)" 17 | }; 18 | cmd.ExecuteNonQuery(); 19 | cmd.CommandText = "CREATE TABLE IF NOT EXISTS namemap(user INTEGER PRIMARY KEY, username TEXT, first_name TEXT, last_name TEXT)"; 20 | cmd.ExecuteNonQuery(); 21 | trans.Commit(); 22 | } 23 | 24 | public void AddLog(long userid, string username, string first_name, string last_name, string content, long msgid) { 25 | using var trans = connection.BeginTransaction(); 26 | using var main_insert = new SQLiteCommand { 27 | Connection = connection, 28 | CommandText = "INSERT INTO stat(user, content, msgid) VALUES (@user, @content, @msgid)" 29 | }; 30 | main_insert.Parameters.AddWithValue("@user", userid); 31 | main_insert.Parameters.AddWithValue("@content", content); 32 | main_insert.Parameters.AddWithValue("@msgid", msgid); 33 | main_insert.Prepare(); 34 | main_insert.ExecuteNonQuery(); 35 | using var namemap_insert = new SQLiteCommand { 36 | Connection = connection, 37 | CommandText = "INSERT OR REPLACE INTO namemap VALUES (@user, @username, @first_name, @last_name)" 38 | }; 39 | namemap_insert.Parameters.AddWithValue("@user", userid); 40 | namemap_insert.Parameters.AddWithValue("@username", username); 41 | namemap_insert.Parameters.AddWithValue("@first_name", first_name); 42 | namemap_insert.Parameters.AddWithValue("@last_name", last_name); 43 | namemap_insert.Prepare(); 44 | namemap_insert.ExecuteNonQuery(); 45 | trans.Commit(); 46 | } 47 | 48 | public struct Entry { 49 | public long UserId; 50 | public string Username; 51 | public string FirstName; 52 | public string LastName; 53 | public int Count; 54 | 55 | public string Name { 56 | get { 57 | if (Username.Length == 0) { 58 | return $"{FirstName} {LastName}"; 59 | } 60 | return $"{Username}"; 61 | } 62 | } 63 | } 64 | 65 | public IEnumerable StatLog() { 66 | using var query = new SQLiteCommand { 67 | Connection = connection, 68 | CommandText = "SELECT namemap.*, count(stat.user) as count FROM stat JOIN namemap USING(user) WHERE stat.time > datetime('now', '-7 days') GROUP BY stat.user ORDER BY count(stat.user) DESC LIMIT 10;" 69 | }; 70 | using var reader = query.ExecuteReader(); 71 | while (reader.Read()) { 72 | yield return new Entry { 73 | UserId = reader.GetInt64(0), 74 | Username = reader.IsDBNull(1) ? "" : reader.GetString(1), 75 | FirstName = reader.IsDBNull(2) ? "" : reader.GetString(2), 76 | LastName = reader.IsDBNull(3) ? "" : reader.GetString(3), 77 | Count = reader.GetInt32(4) 78 | }; 79 | } 80 | } 81 | 82 | public void Dispose() => connection.Dispose(); 83 | } 84 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Code Hz 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /PollBot.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | latestmajor 10 | 11 | 12 | latestmajor 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /PollBot.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29806.167 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PollBot", "PollBot.csproj", "{B91616E8-03BA-4BC0-BE0C-9425BF1E0791}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {B91616E8-03BA-4BC0-BE0C-9425BF1E0791}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {B91616E8-03BA-4BC0-BE0C-9425BF1E0791}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {B91616E8-03BA-4BC0-BE0C-9425BF1E0791}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {B91616E8-03BA-4BC0-BE0C-9425BF1E0791}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {F346DFB8-E7AE-4399-9761-A582E1C2856A} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text.RegularExpressions; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Telegram.Bot; 8 | using Telegram.Bot.Args; 9 | using Telegram.Bot.Types; 10 | using Telegram.Bot.Types.Enums; 11 | using Telegram.Bot.Types.ReplyMarkups; 12 | 13 | namespace PollBot { 14 | 15 | internal class Program { 16 | private static Config cfg; 17 | private static DB db; 18 | private static TelegramBotClient botClient; 19 | private static string botname; 20 | 21 | private static readonly Regex DIVIDER_REGEX = new Regex(@"^-{3,}$", RegexOptions.Compiled); 22 | 23 | private const int MAX_QUESTION_LENGTH = 255; 24 | private const int MAX_OPTION_LENGTH = 100; 25 | private const int MAX_OPTIONS = 10; 26 | private const int MIN_OPTIONS = 2; 27 | 28 | private static void Main(string[] _) { 29 | var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build(); 30 | cfg = deserializer.Deserialize(input: System.IO.File.ReadAllText("config.yaml")); 31 | db = new DB(cfg.Database); 32 | botClient = new TelegramBotClient(token: cfg.TelegramToken); 33 | var me = botClient.GetMeAsync().Result; 34 | botname = me.Username; 35 | Console.WriteLine($"UserID {me.Id} NAME: {me.Username}."); 36 | cfg.Admins = botClient.GetChatAdministratorsAsync(cfg.MainChatId).Result.Select(x => x.User.Id); 37 | botClient.StartReceiving(allowedUpdates: new UpdateType[] { UpdateType.Message, UpdateType.CallbackQuery }); 38 | botClient.OnMessage += BotClient_OnMessage; 39 | botClient.OnCallbackQuery += BotClient_OnCallbackQuery; 40 | while (true) { 41 | Thread.Sleep(millisecondsTimeout: int.MaxValue); 42 | } 43 | } 44 | 45 | private static async void BotClient_OnMessage(object sender, MessageEventArgs e) { 46 | if (e.Message.Text != null) { 47 | if (cfg.DebugMode) 48 | Console.WriteLine(ObjectDumper.Dump(e.Message)); 49 | var text = e.Message.Text; 50 | var user = e.Message.From; 51 | if (text.StartsWith("/poll") || text.StartsWith("/mpoll")) { 52 | HandleCreate(chat_id: e.Message.Chat.Id, message: e.Message, text: e.Message.Text, msg: e.Message.MessageId); 53 | } else if (text == "/help" || text == $"/help@{botname}") { 54 | await botClient.SendTextMessageAsync(e.Message.Chat.Id, cfg.translation.Help, replyToMessageId: e.Message.MessageId); 55 | } else if (text == "/stats" || text == $"/stats@{botname}") { 56 | HandleStat(chat_id: e.Message.Chat.Id, e.Message.MessageId); 57 | } else if (text == "/refresh_admin" || text == $"/refresh_admin@{botname}") { 58 | cfg.Admins = (await botClient.GetChatAdministratorsAsync(cfg.MainChatId)).Select(x => x.User.Id); 59 | } else if (text == "/dup" || text == $"/dup@{botname}") { 60 | HandleDuplicate(msg: e.Message); 61 | } 62 | } 63 | } 64 | 65 | private static async void HandleDuplicate(Message msg) { 66 | if ((ChatId) msg.Chat.Id != cfg.MainChatId) { 67 | await botClient.SendTextMessageAsync(msg.Chat.Id, cfg.translation.DisallowError); 68 | return; 69 | } 70 | if (cfg.DeleteOrigin) 71 | await botClient.DeleteMessageAsync(cfg.MainChatId, msg.MessageId); 72 | var rep = msg.ReplyToMessage; 73 | if (rep == null) { 74 | await botClient.SendTextMessageAsync(cfg.MainChatId, cfg.translation.NoReplyError); 75 | return; 76 | } 77 | if (rep.Poll == null) { 78 | await botClient.SendTextMessageAsync(cfg.MainChatId, cfg.translation.NotPollError); 79 | return; 80 | } 81 | if (!rep.Poll.IsClosed) { 82 | await botClient.SendTextMessageAsync(cfg.MainChatId, cfg.translation.NotClosedError); 83 | return; 84 | } 85 | if (rep.Poll.Type == "quiz") { 86 | await botClient.SendTextMessageAsync(cfg.MainChatId, cfg.translation.NotQuizError); 87 | return; 88 | } 89 | await botClient.SendTextMessageAsync(cfg.MainChatId, cfg.translation.Duplicate, 90 | parseMode: ParseMode.Html, 91 | disableWebPagePreview: true, 92 | disableNotification: true, 93 | replyToMessageId: rep.MessageId, 94 | replyMarkup: new InlineKeyboardMarkup(new InlineKeyboardButton[] { 95 | InlineKeyboardButton.WithCallbackData(cfg.translation.Approve, "duplicate"), 96 | InlineKeyboardButton.WithCallbackData(cfg.translation.Reject, "reject") })); 97 | } 98 | 99 | [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "")] 100 | private static async void BotClient_OnCallbackQuery(object sender, CallbackQueryEventArgs e) { 101 | const string _approve = "approve "; 102 | const string _duplicate = "duplicate"; 103 | var query = e.CallbackQuery; 104 | try { 105 | if (query.Data.StartsWith(_approve)) { // Update / approve 106 | var hash = int.Parse(query.Data.Remove(0, _approve.Length)); 107 | var origin = query.Message.ReplyToMessage; 108 | var text = origin.Text; 109 | var shash = text.GetHashCode(); 110 | 111 | // Check permission 112 | if (hash != shash) { // edited, update 113 | // check admin / author permission 114 | if (!cfg.Admins.Contains(query.From.Id) && query.From.Id != query.Message.ReplyToMessage.From.Id) { 115 | await botClient.AnswerCallbackQueryAsync(query.Id, cfg.translation.PermissionWithAuthorError); 116 | return; 117 | } 118 | } else { // not edited, approve 119 | // check admin permission 120 | if (!cfg.Admins.Contains(query.From.Id)) { 121 | await botClient.AnswerCallbackQueryAsync(query.Id, cfg.translation.PermissionError); 122 | return; 123 | } 124 | } 125 | var error = VerifyMessage(text, origin, out var firstline, out var opts, out var multi); 126 | if (error != null) { 127 | await botClient.DeleteMessageAsync(cfg.MainChatId, query.Message.MessageId); 128 | await botClient.SendTextMessageAsync(origin.Chat.Id, error); 129 | return; 130 | } 131 | if (hash != shash) { // message edited 132 | await Task.WhenAll( 133 | botClient.AnswerCallbackQueryAsync(query.Id, cfg.translation.HashMisMatchError), 134 | botClient.DeleteMessageAsync(cfg.MainChatId, query.Message.MessageId), 135 | SendRequest(firstline, opts, origin.MessageId, shash, multi)); 136 | return; 137 | } 138 | await SendPoll(origin.From, firstline, opts, multi); 139 | await botClient.SendTextMessageAsync(origin.Chat.Id, 140 | String.Format(cfg.translation.ApprovedBy, BuildName(query.From))); 141 | await Task.WhenAll( 142 | botClient.DeleteMessageAsync(cfg.MainChatId, query.Message.MessageId), 143 | botClient.AnswerCallbackQueryAsync(query.Id, cfg.translation.Approved)); 144 | if (cfg.DeleteOrigin) 145 | await botClient.DeleteMessageAsync(cfg.MainChatId, origin.MessageId); 146 | } else if (query.Data == _duplicate) { // Duplicate 147 | // check admin permission 148 | if (!cfg.Admins.Contains(query.From.Id)) { 149 | await botClient.AnswerCallbackQueryAsync(query.Id, cfg.translation.PermissionError); 150 | return; 151 | } 152 | 153 | var origin = query.Message.ReplyToMessage; 154 | await DuplicatePoll(origin); 155 | await Task.WhenAll( 156 | botClient.DeleteMessageAsync(cfg.MainChatId, query.Message.MessageId), 157 | botClient.AnswerCallbackQueryAsync(query.Id, cfg.translation.Approved)); 158 | if (cfg.DeleteOrigin) 159 | await botClient.DeleteMessageAsync(cfg.MainChatId, origin.MessageId); 160 | } else { // Reject 161 | // check admin / author permission 162 | if (!cfg.Admins.Contains(query.From.Id) && query.From.Id != query.Message.ReplyToMessage.From.Id) { 163 | await botClient.AnswerCallbackQueryAsync(query.Id, cfg.translation.PermissionWithAuthorError); 164 | return; 165 | } 166 | 167 | // Reject 168 | await Task.WhenAll( 169 | botClient.SendTextMessageAsync(cfg.MainChatId, String.Format( 170 | cfg.translation.RejectedBy, BuildName(query.From) 171 | ), replyToMessageId: query.Message.ReplyToMessage.MessageId), 172 | botClient.DeleteMessageAsync(cfg.MainChatId, query.Message.MessageId), 173 | botClient.AnswerCallbackQueryAsync(query.Id, cfg.translation.Rejected) 174 | ); 175 | } 176 | } catch (Exception ex) { 177 | Console.WriteLine(ex); 178 | try { 179 | await botClient.DeleteMessageAsync(query.Message.Chat.Id, query.Message.MessageId); 180 | } catch { } 181 | try { 182 | await botClient.AnswerCallbackQueryAsync(query.Id, cfg.translation.ExceptionError); 183 | await botClient.SendTextMessageAsync(cfg.MainChatId, cfg.translation.ExceptionError); 184 | } catch { } 185 | } 186 | } 187 | 188 | private static async void HandleCreate(ChatId chat_id, Message message, string text, int msg) { 189 | try { 190 | var direct_send = cfg.Admins.Contains(message.From.Id) && cfg.DirectSend; 191 | if (chat_id != cfg.MainChatId && !direct_send) { 192 | await botClient.SendTextMessageAsync(chat_id, cfg.translation.DisallowError); 193 | return; 194 | } 195 | string error = VerifyMessage(text, message, out var firstline, out var opts, out var multi); 196 | if (error != null) { 197 | await botClient.SendTextMessageAsync(chat_id, error); 198 | return; 199 | } 200 | if (direct_send) { 201 | await SendPoll(message.From, firstline, opts, multi); 202 | } else { 203 | await SendRequest(firstline, opts, msg, text.GetHashCode(), multi); 204 | } 205 | } catch (Exception ex) { 206 | Console.WriteLine(ex.StackTrace); 207 | await botClient.SendTextMessageAsync(chat_id, cfg.translation.ExceptionError); 208 | return; 209 | } 210 | } 211 | 212 | [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0018:Inline variable declaration", Justification = "")] 213 | private static async Task SendRequest(string question, IEnumerable opts, int msg, int hash, bool multi) { 214 | await botClient.SendPollAsync(cfg.MainChatId, question, opts, 215 | allowsMultipleAnswers: multi, 216 | isAnonymous: true, 217 | replyToMessageId: msg, 218 | isClosed: true, 219 | replyMarkup: new InlineKeyboardMarkup(new InlineKeyboardButton[] { 220 | InlineKeyboardButton.WithCallbackData(cfg.translation.Approve, $"approve {hash}"), 221 | InlineKeyboardButton.WithCallbackData(cfg.translation.Reject, "reject") })); 222 | } 223 | 224 | [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0018:Inline variable declaration", Justification = "")] 225 | private static async Task SendPoll(User user, string question, IEnumerable opts, bool multi) { 226 | var msg = await botClient.SendPollAsync(cfg.SendChatId, question, opts, allowsMultipleAnswers: multi, isAnonymous: true); 227 | db.AddLog(user.Id, user.Username, user.FirstName, user.LastName, question, msg.MessageId); 228 | } 229 | 230 | private static async Task DuplicatePoll(Message origin) { 231 | var poll = origin.Poll; 232 | var user = origin.From; 233 | string authorSuffix = BuildAuthorSuffix(origin); 234 | var msg = await botClient.SendPollAsync(cfg.MainChatId, $"{poll.Question} {authorSuffix}", 235 | options: poll.Options.Select(op => op.Text), 236 | allowsMultipleAnswers: poll.AllowsMultipleAnswers, 237 | isAnonymous: true); 238 | db.AddLog(user.Id, user.Username, user.FirstName, user.LastName, poll.Question, msg.MessageId); 239 | } 240 | 241 | private static string VerifyMessage(string data, Message message, out string firstline, out IEnumerable opts, out Boolean multi) { 242 | // Default values; 243 | firstline = null; 244 | opts = null; 245 | multi = false; 246 | 247 | string trimmed = data; 248 | 249 | // Poll types 250 | if (data.TryRemovePrefix("/poll ", out trimmed) || data.TryRemovePrefix($"/poll@{botname} ", out trimmed)) { 251 | multi = false; 252 | } else if (data.TryRemovePrefix("/mpoll ", out trimmed) || data.TryRemovePrefix($"/mpoll@{botname} ", out trimmed)) { 253 | multi = true; 254 | } else { 255 | Console.WriteLine($"Unexcepted request: {data}"); 256 | return cfg.translation.Help; 257 | } 258 | 259 | // data preparation 260 | var lines = trimmed.Split("\n").ToList(); 261 | string question = null; 262 | IEnumerable options = null; 263 | string authorSuffix = " " + BuildAuthorSuffix(message); 264 | int authorSuffixLength = authorSuffix.UTF16Length(); 265 | int i = 0; 266 | while (i < lines.Count) { 267 | if (DIVIDER_REGEX.Match(lines[i]).Success) { 268 | question = string.Join("\n", lines.Take(i)).Trim(); 269 | options = lines.TakeLast(lines.Count - i - 1).Select(x => x.Trim()); 270 | break; 271 | } 272 | i++; 273 | } 274 | if (question == null) { 275 | question = lines[0].Trim(); 276 | options = lines.TakeLast(lines.Count - 1).Select(x => x.Trim()); 277 | } 278 | if (question.UTF16Length() > MAX_QUESTION_LENGTH - authorSuffixLength) { 279 | return String.Format( 280 | cfg.translation.QuestionTooLongError, 281 | MAX_QUESTION_LENGTH - authorSuffixLength, question.UTF16Length() 282 | ); 283 | } 284 | question += authorSuffix; 285 | if (options.Count() < MIN_OPTIONS || options.Count() > MAX_OPTIONS) { 286 | return String.Format( 287 | cfg.translation.WrongOptionSizeError, 288 | MIN_OPTIONS, MAX_OPTIONS, options.Count() 289 | ); 290 | } 291 | foreach (string option in options) { 292 | if (option.UTF16Length() > MAX_OPTION_LENGTH) { 293 | return String.Format( 294 | cfg.translation.OptionTooLongError, 295 | MAX_OPTION_LENGTH, option.UTF16Length(), option 296 | ); 297 | } 298 | } 299 | firstline = question; 300 | opts = options; 301 | return null; 302 | } 303 | 304 | private static string BuildName(User user) { 305 | string firstName = user.FirstName; 306 | string lastName = user.LastName; 307 | if (!string.IsNullOrWhiteSpace(lastName)) { 308 | return firstName + " " + lastName; 309 | } 310 | return firstName; 311 | } 312 | 313 | private static string BuildAuthorSuffix(Message message) { 314 | if (!string.IsNullOrWhiteSpace(message.ForwardSenderName)) { 315 | return message.ForwardSenderName; 316 | } 317 | string firstName, lastName; 318 | if (message.ForwardFromChat != null) { 319 | firstName = message.ForwardFromChat.FirstName; 320 | lastName = message.ForwardFromChat.LastName; 321 | } else { 322 | User user; 323 | if (message.ForwardFrom != null) { 324 | user = message.ForwardFrom; 325 | } else { 326 | user = message.From; 327 | } 328 | firstName = user.FirstName; 329 | lastName = user.LastName; 330 | } 331 | string authorSuffix = $"by {firstName}"; 332 | if (!string.IsNullOrWhiteSpace(lastName)) { 333 | authorSuffix += " " + lastName; 334 | } 335 | return authorSuffix; 336 | } 337 | 338 | private static async void HandleStat(long chat_id, int msg_id) { 339 | var log = cfg.translation.Stats + "\n"; 340 | foreach (var entry in db.StatLog()) { 341 | log += $"{entry.Count}: {entry.Name}\n"; 342 | } 343 | await botClient.SendTextMessageAsync(chat_id, log, replyToMessageId: msg_id, disableWebPagePreview: true, parseMode: ParseMode.Html); 344 | } 345 | } 346 | } 347 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DiscussPollBot 2 | Just a telegram poll bot 3 | -------------------------------------------------------------------------------- /StringEx.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | 4 | namespace PollBot { 5 | public static class StringEx { 6 | public static bool TryRemovePrefix(this string self, string prefix, out string rest) { 7 | if (self == null) { 8 | rest = null; 9 | return false; 10 | } 11 | if (self.ToLower().StartsWith(prefix.ToLower())) { 12 | rest = self.Remove(0, prefix.Length); 13 | return true; 14 | } 15 | Console.WriteLine($"Prefix is not found: {prefix} in {self}"); 16 | rest = ""; 17 | return false; 18 | } 19 | 20 | public static int UTF16Length(this string self) { 21 | return Encoding.Unicode.GetByteCount(self) / 2; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /example.yaml: -------------------------------------------------------------------------------- 1 | token: your token here 2 | debug-mode: true 3 | main-id: main group 4 | send-id: channel 5 | database: URI=file:stat.db 6 | delete-origin: true 7 | admin-direct-send: false 8 | 9 | texts: 10 | approve: 刷新/发到频道 11 | reject: 退稿 12 | # reply: 请求已经收到,请管理员审核 13 | approved: 投票已经创建 14 | approvedby: 投票由 {0} 审核通过。 15 | rejected: 请求已拒绝 16 | rejectedby: 投票由 {0} 退稿。 17 | stats: 投票统计 18 | help: |- 19 | 使用方式:发送 /poll 或者 /mpoll 创建投票和多选投票,暂时不支持 quiz 模式。 20 | 格式:第一行为投票标题,随后每一行都是一个选项。 21 | 多行标题可用 --- 分割标题与选项。 22 | 可以通过 /stats 查询统计信息。 23 | error-format: 格式错误,请检查你的格式并重新提交 24 | error-disallow: 您不能在这里投稿,请去 XXXXX 25 | error-reject: 请求被拒绝 26 | error-changed: 原消息已经改变,需要重新审核 27 | error-permission: 只有管理员能进行这项操作 28 | error-permissionwithauthor: 只有管理员和原作者能进行这项操作 29 | duplicate: duplicate 30 | error-exception: error-exception 31 | error-noreply: error-noreply 32 | error-notclosed: error-notclosed 33 | error-notpoll: error-notpoll 34 | error-notquiz: error-notquiz 35 | error-optiontoolong: 选项长度不能超过 {0},您的选项「{2}」长度为 {1}。 36 | error-questiontoolong: 题目长度不能超过 {0},您的问题长度为 {1}。 37 | error-wrongoptionsize: 选项个数应介于 {0} 与 {1} 之间,您提供了 {2} 个选项。 --------------------------------------------------------------------------------